Unable to use generated client from swagger api - api

I am trying to use a third party api in the project where the way to access those apis are provide in swagger
When i generate the client using swagger and try to use in my local i am getting the error has
io.swagger.client.ApiException: java.net.SocketTimeoutException: connect timed out
at io.swagger.client.ApiClient.execute(ApiClient.java:973)
at io.swagger.client.api.PlatformApi.getAppsWithHttpInfo(PlatformApi.java:729)
at io.swagger.client.api.PlatformApi.getApps(PlatformApi.java:716)
at io.swagger.client.api.testSample.getNodesTest(testSample.java:16)
at io.swagger.client.api.testSample.main(testSample.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.squareup.okhttp.internal.Platform.connectSocket(Platform.java:120)
at com.squareup.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
at com.squareup.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
at com.squareup.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
at com.squareup.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.squareup.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.squareup.okhttp.Call.getResponse(Call.java:286)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:243)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:205)
at com.squareup.okhttp.Call.execute(Call.java:80)
at io.swagger.client.ApiClient.execute(ApiClient.java:969)
... 9 more
i am trying to use one of the method from the generated client as shown below
package io.swagger.client.api;
import com.squareup.okhttp.OkHttpClient;
import io.swagger.client.ApiClient;
import io.swagger.client.ApiException;
import io.swagger.client.Configuration;
import io.swagger.client.model.AppModel;
import io.swagger.client.model.NodeModel;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class testSample {
private final PlatformApi api = new PlatformApi();
public void getNodesTest() throws ApiException {
List<AppModel> response = api.getApps();
System.out.print("------------------------inside testsample------------------------");
System.out.print(response);
}
public static void main(String args[]){
testSample t1=new testSample();
System.out.print("------------------------inside main------------------------");
try{
ApiClient defaultApiClient = Configuration.getDefaultApiClient();
ApiClient apiClient = t1.api.getApiClient();
System.out.println(defaultApiClient);
System.out.println(apiClient);
t1.getNodesTest();
}
catch(Exception e){
System.out.println("inside exeption");
e.printStackTrace();
}
}
}
Please provide some suggestion how to use the generated java client from swagger in local

I hope these helps someone;
DefaultApi defaultApi = new DefaultApi();
ApiClient apiClient = new ApiClient();
apiClient.setBasePath("http://....");
apiClient.addDefaultHeader("Authorization", "bearer TOKEN");
OkHttpClient httpClient = apiClient.getHttpClient();
httpClient.setConnectTimeout(60, TimeUnit.SECONDS);
httpClient.setReadTimeout(60, TimeUnit.SECONDS);
httpClient.setWriteTimeout(60, TimeUnit.SECONDS);
defaultApi.setApiClient(apiClient);
SomeModel var1 = defaultApi.getNodesTest();
generator sample command;
> java -jar swagger-codegen-cli-2.2.2.jar generate -l java -o myModule --library okhttp-gson -i http://..../swagger
to download jar file;
http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/
for more info;
https://github.com/swagger-api/swagger-codegen

The error below suggests that the Java API client couldn't connect to the API server:
io.swagger.client.ApiException: java.net.SocketTimeoutException: connect timed out
I would suggest you to verify the Swagger/OpenAPI spec to ensure it has a proper host setting, e.g.
host: petstore.swagger.io
e.g. https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml#L12
Ref: Swagger 2.0 spec: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object

Related

RestAssured - Testing Restful API using Selenium and Test NG - when run throws connection timeout error

I am testing a Weather Rest API using Restassured and TestNG framework. Following is the code:
I made sure I have all the dependencies covered in pom.xml file
This is the error:
java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:122)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class RestApi_Weather_GET {
#Test
void GetWeatherDetails(){
//specify the base uri
RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city/";
//Request object is being created
RequestSpecification ahttprequest = RestAssured.given();
//Response object
Response aresponse = ahttprequest.request(Method.GET, "Alameda");
//print response in console
String aresponseBody = aresponse.getBody().asString();
System.out.println("Response body is : "+aresponseBody);
}
}

How to create a cucumber-java custom formatter to get cucumber tags

I have a cucumber project and I want to get al the tags in the project to be able to choose them as parameters.
I found this question where cucumber had an option to get the tags but I found that doesn't work anymore, then I found this other question where I found I need a custom formatter to get my tags, but it is for ruby, and I need it for Java, so then I found this article on how to create a custom formatter, but I found that this worked for the cukes version and I'm using the io one.
So I searched inside the cucumber packages and created a custom formatter from a copy of the JSONFormatter inside the package cucumber.runtime.formatter, here is my code:
import cucumber.api.TestCase;
import cucumber.api.event.*;
import cucumber.api.formatter.Formatter;
import cucumber.api.formatter.NiceAppendable;
import gherkin.deps.com.google.gson.Gson;
import gherkin.deps.com.google.gson.GsonBuilder;
import gherkin.pickles.PickleTag;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class TagsFormatter implements Formatter {
private String currentFeatureFile;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private final NiceAppendable out;
private List<String> tags = new ArrayList<>();
private EventHandler<TestCaseStarted> caseStartedHandler = this::handleTestCaseStarted;
private EventHandler<TestRunFinished> runFinishedHandler = event -> finishReport();
public TagsFormatter(Appendable out) {
this.out = new NiceAppendable(out);
}
#Override
public void setEventPublisher(EventPublisher publisher) {
publisher.registerHandlerFor(TestCaseStarted.class, caseStartedHandler);
publisher.registerHandlerFor(TestRunFinished.class, runFinishedHandler);
}
private void handleTestCaseStarted(TestCaseStarted event) {
if (currentFeatureFile == null || !currentFeatureFile.equals(event.testCase.getUri())) {
currentFeatureFile = event.testCase.getUri();
collectTags(event.testCase);
}
}
private void finishReport() {
out.append(gson.toJson(tags));
out.close();
}
private void collectTags(TestCase testCase) {
testCase.getTags();
tags.addAll(testCase.getTags()
.stream()
.map(PickleTag::getName)
.collect(Collectors.toList()));
}
}
I copied the libraries I need to run cucumber in a lib folder inside my project and tried running it using my formatter like this:
java -cp .\lib\cucumber-core-2.4.0.jar;.\lib\gherkin-5.0.0.jar;.\lib\cucumber-java-2.4.0.jar;.\lib\cucumber-jvm-deps-1.0.6.jar cucumber.api.cli.Main -p "com.myproject.formatters.TagsFormatter:tags.txt"
But Im getting a class not found exception:
λ java -cp .\lib\cucumber-core-2.4.0.jar;.\lib\gherkin-5.0.0.jar;.\lib\cucumber-java-2.4.0.jar;.\lib\cucumber-jvm-deps-1.0.6.jar cucumber.api.cli.Main -p "com.myproject.formatters.TagsFormatter:tags.txt"
Exception in thread "main" cucumber.runtime.CucumberException: Couldn't load plugin class: com.myproject.formatters.TagsFormatter
at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:181)
at cucumber.runtime.formatter.PluginFactory.pluginClass(PluginFactory.java:166)
at cucumber.runtime.formatter.PluginFactory.getPluginClass(PluginFactory.java:223)
at cucumber.runtime.formatter.PluginFactory.isFormatterName(PluginFactory.java:201)
at cucumber.runtime.RuntimeOptions$ParsedPluginData.addPluginName(RuntimeOptions.java:471)
at cucumber.runtime.RuntimeOptions.parse(RuntimeOptions.java:157)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:115)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:108)
at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:100)
at cucumber.api.cli.Main.run(Main.java:31)
at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.ClassNotFoundException: com.myproject.formatters.TagsFormatter
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:174)
... 10 more
So, how can I create this formatter in a way it is recognized? or at least get the tags list from cucumber from console?
Thanks
By just eyeballing your code, I don't think there is anything wrong with it. However your command does not appear to include a compiled version of the TagsFormatter on the class path.
If your compiled sources are in .\bin\ make sure to include that folder ie:
java -cp .\lib\cucumber-core-2.4.0.jar;.\lib\gherkin-5.0.0.jar;.\lib\cucumber-java-2.4.0.jar;.\lib\cucumber-jvm-deps-1.0.6.jar;.\bin\* cucumber.api.cli.Main -p "com.myproject.formatters.TagsFormatter:tags.txt"

Domino Java Agent Error

When i try an java agent to run i get this error on java console. Target property of agent is None. Trigger is "On Event, "Action Menu Selected".I do ot know what i have to do to solve this problem. Any suggestion.
import org.openntf.domino.*;
import org.json.JSONArray;
import org.json.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.openntf.domino.ext.Session.Fixes;
import org.openntf.domino.utils.Factory;
public class JavaAgent extends AgentBase
{
public void NotesMain()
{
try
{
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
ERROR LINE:
Unexpected error while executing java agent:JavaAgent
-->java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=, offset=6
java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=, offset=6
at java.lang.ClassLoader.defineClass(ClassLoader.java:287)
at java.lang.ClassLoader.defineClass(ClassLoader.java:224)
at lotus.domino.AgentLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(ClassLoader.java:638)
at java.lang.ClassLoader.defineClassImpl(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:287)
at java.lang.ClassLoader.defineClass(ClassLoader.java:224)
at lotus.domino.AgentLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(ClassLoader.java:638)
at lotus.domino.AgentLoader.runAgent(Unknown Source)
I have added this .jar file in to archive that

PDF reader not working

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.file.Files;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
`
public class Test{
public static void main(String []args) throws IOException
{
String pdf= "c:\\sample.pdf";
PdfReader reader = new PdfReader(pdf);
}
}
it not working
like it should i am running windows
need help please help i tried a lot of things but still getting the same message
here is the error message
this is the output i get when i tried ur code
File Exists: true
Exception in thread "main" java.lang.NoClassDefFoundError:
org/bouncycastle/asn1/ASN1Encodable
at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:1024)
at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1430)
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:732)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:181)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:219)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:207)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:197)
at pdfconverter.Test.main(Test.java:37)
Caused by: java.lang.ClassNotFoundException:
org.bouncycastle.asn1.ASN1Encodable
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 9 more
The code looks good to me. Perhaps more information on the error you are having? For instance, it could be a classpath error - something like the itextpdf classes not being located...
In case it helps as a baseline - the following code works for me. I removed the extraneous includes, though they won't hurt to leave them in.
import java.io.File;
import com.itextpdf.text.pdf.PdfReader;
public class Test {
public static void main(String[] args) {
String pdf= "C:\\Java-Design-Patterns.pdf";
try {
System.out.println("File Exists: "+new File(pdf).exists());
PdfReader reader = new PdfReader(pdf);
int count = reader.getNumberOfPages();
System.out.println("PDF has "+count+" pages.");
} catch (Exception e) {
System.out.println("Failed to open PDF ["+pdf+"]: "+e);
e.printStackTrace();
}
}
}
The output is:
File Exists: true
PDF has 183 pages.
The itext jar I used is: itextpdf-5.5.12.jar (included via maven).
The pdf I used (courtesy of google: java design patterns pdf) is here: http://enos.itcollege.ee/~jpoial/java/naited/Java-Design-Patterns.pdf
I haven't read it yet, but the first page looks good ;)
That said, itextpdf is quite awesome.
java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable
clearly indicates the issue: Bouncy Castle is missing! (Or at least the required version is missing.)
Bouncy Castle is a library used by iText for encryption, decryption, signing, and signature verification, here their web representation.
Thus, add the Bouncy Castle libraries to your class path. Please be aware, though, that the BC version required depends on the iText version in question. The maven link you provided for your itext7 version indicates that BC 1.49 is required.

Selenium Server not starting

package com.memoir.client.widgets.memogen;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.thoughtworks.selenium.DefaultSelenium;
#SuppressWarnings("deprecation")
public class TestHomepage extends SeleneseTestCase {
#Override
#Before
public void setUp() throws Exception {
//selenium = new DefaultSelenium("localhost", 4444, "*firefox", "https://64.79.128.233/staging/");
selenium = new DefaultSelenium("localhost", 4444, "*firefox /usr/bin/firefox", "https://64.79.128.233/staging/");
selenium.start();
}
#Test
public void testTesting4() throws Exception {
selenium.setSpeed("2000");
selenium.windowMaximize();
//selenium.open("/memosyn/");
selenium.open("/staging/");
selenium.waitForPageToLoad("60000");
//Checking for page layout in the beginning of the web page
assertEquals("1", selenium.getElementIndex("//*[#id='isc_G']"));
assertEquals("Please contact support#systems.com for questions or comments.", selenium.getText("id=contactText"));
//assertEquals("MemoWeb V3.3.5963M", selenium.getText("//*[#id='isc_WidgetCanvas_1_widget']/div/table/tbody/tr/td[2]"));
assertEquals("14", selenium.getElementHeight("scLocator=//VLayout[ID=\"loginBox\"]/"));
assertEquals("447", selenium.getElementWidth("scLocator=//VLayout[ID=\"loginBox\"]/"));
assertEquals("35", selenium.getElementHeight("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=email]/title"));
assertEquals("207", selenium.getElementWidth("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=email]/title"));
assertEquals("35", selenium.getElementHeight("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=password]/title"));
assertEquals("207", selenium.getElementWidth("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=password]/title"));
assertEquals("35", selenium.getElementHeight("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=rememberMe]/textbox"));
assertEquals("203", selenium.getElementWidth("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=rememberMe]/textbox"));
assertEquals("22", selenium.getElementHeight("scLocator=//Button[ID=\"submitButton\"]/"));
assertEquals("100", selenium.getElementWidth("scLocator=//Button[ID=\"submitButton\"]/"));
assertEquals("MemoWeb", selenium.getTitle());
assertEquals("Email :", selenium.getText("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=email||title=Email]/title"));
assertEquals("Password :", selenium.getText("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=password||title=Password]/title"));
assertEquals("Remember me on this computer", selenium.getText("scLocator=//DynamicForm[ID=\"loginItems\"]/item[name=rememberMe||title=Remember%20me%20on%20this%20computer]/textbox"));
}
#Override
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
This is the code and when I run this by starting the selenium server i get this error.
What could be the reason for the error? Is it that my firefox profile is not set properly?
java.lang.RuntimeException: Could not start Selenium session: Failed to start new browser session: org.openqa.selenium.server.browserlaunchers.InvalidBrowserExecutableException: The specified path to the browser executable is invalid.
at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:109)
at com.memoir.client.widgets.memogen.TestHomepage.setUp(TestHomepage.java:16)
at junit.framework.TestCase.runBare(TestCase.java:132)
at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:230)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.thoughtworks.selenium.SeleniumException: Failed to start new browser session: org.openqa.selenium.server.browserlaunchers.InvalidBrowserExecutableException: The specified path to the browser executable is invalid.
at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:112)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:106)
at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:275)
at com.thoughtworks.selenium.HttpCommandProcessor.start(HttpCommandProcessor.java:237)
at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:100)
... 16 more
Can anyone help me fix this?
I get those errors and I have no clue please help me .
Selenium RC works on Eclipse with versions less that 12 . Can you pls check which version you are using