SOAPUI : Need Sample REST APIs to test using SOAPUI Tool - rest

Hi Can anyone let me know where I can find sample RESTFul APIs so that I can have hands on experience working on them using GET/POST/DELETE methods.
Thanks.

If you have an idea about Java, Servlet, Wildfly / Tomcat server, Mysql then you can create a basic program for Get / Post Method and deploy on the local server.
You will learn to create basic API also. The best way you install eclipse and integrate server. With Eclipse, you can easily create Servlet as it provides template and web.xml generate automatically.
Create a basic object Class. Call it in servelet fill some data.
Convert it to JSON by using GSON
#WebServlet(asyncSupported = true, urlPatterns = { "/School_getEmployee" })
public class School_Employee_servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(Object);
PrintWriter out = response.getWriter();
out.println(json);
}
Now you can use this servlet as API for testing.

You can use JSON-SERVER, I'm using these to make GET/PUT/POST/DELETE

Related

is there a way to mock internal service calls while writing Component testcases

I'm writing my component level test-cases for my repository. My API calls internally a third party API which I need to mock. I don't have direct access to that API neither I can directly call it, it needs to be called from within the API calls. I need to mock in order to run the component test-cases successfully. I tried wiremock but looks like it is not working and my API is still calling the 3rd party URL. Is there any way to solve this problem. Here is my code -
Annotation at class level
#Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8888));
WireMockServer wm;
Started server
#BeforeEach
void setUp() {
wm = new WireMockServer(WireMockConfiguration.options().port(8888));
wm.start();
}
In the tests.
wireMockServer.start();
wm.stubFor(get("https://someurl")
.willReturn(badRequest()
.withHeader("Content-Type", "application/json")
.withBody("<response>SUCCESS</response>")));
MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders
.post(apiContextPath)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(gson.toJson(offerParams)))
.andExpect(status().isOk()).andReturn();
wireMockServer.stop();
Sorry can't paste whole code due to security reasons.
It looks like you're trying to use the JUnit 4 rule with JUnit 5, meaning the WireMock server won't be started.
Try the JUnit Jupiter extension instead: https://wiremock.org/docs/junit-jupiter/

Alternative to REST when passing objects between servers

I have a spring-mvc project as a frontend project. My datasources are accessed by a second javaee project. This backend grands access to all data my frontend requires, by providing REST services. The REST-Service provides objects, by returning XML. This XML will then get marshaled by my frontend.
So when my frontend project requires current data, I create an HttpUrlConnection, then I call the REST-Service of my backend.
E.g. I want to get a collection of all movie objects:
URL url = new URL(URLSAFE.REST_ALL_MOVIES);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/xml");
connection.getResponseCode();
InputStream is = connection.getInputStream();
Source sauce = new StreamSource(is);
JAXBContext jaxbContext = JAXBContext.newInstance(Movies.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<Movies> e = unmarshaller.unmarshal(sauce, Movies.class);
Movies m = e.getValue();
this.MOVIELIST = m;
connection.disconnect();
After I added some remote ejb lookups for logging services, I came up with the idea to use rmi for passing objects. However I learned I cant cast the object to my frontend and that there is a big difference between a local object and a object you access by rmi.
But what would be a good attempt for passing objects between servers? I need to pass objects to the frontend because I got to use them with JSP.
I would suggest to take a look at this Spring.io guide. Usage of RestTemplate can remove a lot of boilerplate you have in example, and map REST resources onto POJOs. XML shouldn't be any barrier, because Spring should significantly help you abstract it.

how to handle db connectivity of couchdb with gwt?

I am new to couchdb and I want to learn about how to connect the couchdb in our gwt server side program. till now, I tried to work on its gui to create database add documents and add fields to it.but i am not able to use it in program. what exactly the way to do it..
I tried some code but didn't got it.
In your GWT you should have something like this in your server. Besides it you should have your DAO for your Entities (erktorp takes place here) and your mechanism for connecting GWT's client with the server (for example RequestFactory).
//Object of your own related with couch db management
CouchDbAccess couchDbAccess = null;
#Inject
public CouchDbManagement(String ddbbUrl, String ddbbName) throws IOException {
HttpClient httpClient;
Builder b;
try {
b = new StdHttpClient.Builder().url(ddbbUrl);
} catch (Exception e) {
e.printStackTrace();
ddbbUrl = "http://admin:sa#localhost:5984";
b = new StdHttpClient.Builder();
}
b.socketTimeout(60000);
String user = getUserFrom(ddbbUrl);
String pass = getPassFrom(ddbbUrl);
b.username(user).password(pass);
httpClient = b.build();
CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
if (initialize && dbInstance.getAllDatabases().contains(ddbbName)) {
dbInstance.deleteDatabase(ddbbName);
dbInstance = new StdCouchDbInstance(httpClient);
}
//If you want Lucene, here is the place
db.createDatabaseIfNotExists();
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
URI dbURI = URI.prototype(DbPath.fromString(ddbbName).getPath());
RestTemplate restTemplate = new RestTemplate(dbInstance.getConnection());
couchDbAccess = new CouchDbAccess(db, dbURI, restTemplate);
}
Couchdb has a restful interface to it's api. Everything is available via url's like
http://localhost:5984/db_name/doc_name
In fact the entire http api is documented in the wiki. Now I am not familiar with gwt but every framework has http libraries and you can use those libraries to make calls to couchdb http endpoints.
A quick google search gave me this resource which may guide you on how to create http requests through gwt.

Send localized email in GWT [duplicate]

I have an interface that extends the com.google.gwt.i18n.client.Messages class, which I use for retrieving i18n messages in my GWT application. It looks like this:
public interface MyMessages extends com.google.gwt.i18n.client.Messages {
#DefaultMessage("Hello world")
#Key("message1")
String message1();
#DefaultMessage("Hello again")
#Key("message2")
String message2();
//...
}
Normally, I create an instance of it using GWT.create() like so:
private MyMessages messages = GWT.create(MyMessages.class);
However, this does not work with server-side code, only client-side code (it throws an error saying that GWT.create() is only usable in client-side code).
The answer to a similar question points to a separate library that you can download which will let you access the i18n messages on the server, but I don't want to download any extra libraries (this seems like a simple problem, there must be a simple solution).
In summary: How can I access my i18n messages in server-side code? Thanks.
On the server side you can use the standard Java localization tools like ResourceBundle.
Look here for a tutorial how to use it.
// Create a ResourceBundle out of your property files
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle", currentLocale);
// Get localized value
String value = labels.getString(key);
The GWT specific way of creating an interface out of your property files and providing implementations via deferred binding can not be used on sever side Java.
If you are fearless and willing to spend the time, you can implement a code generation step to read your property files and generate implementation classes for your message interface. That's exactly what the Google GWT compiler does behind the scene.
I agree with Michael.. I was having this problem of trying to "localize" messages generated on the server.... but I decided to instead just throw an Exception on the server (because it is an error message which should only happen exceptionally) which contains the message code, which the client code can then look up and show the correct localized message to the user.
There's a great library for GWT internationalization gwt-dmesg. It allows you to 'share' .properties files between clent and server. However, project looks to be abandoned by author and you must recompile it manually for use with GWT versio >= 2.1.0.
GWT.create() can only be used in client-side code.
The good thing to do is that you provide your own I18NProvider class/interface, from which then you can extend to server side I18N factory and client side I18N factory read the same resource bundle.
After that you can simply use it all over your system, unify your code.
Hope that helps.
Following vanje's answer, and considering the encoding used for the properties files (which can be troublesome as ResourceBundle uses by default "ISO-8859-1", here is the solution I came up with:
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
public class MyResourceBundle {
// feature variables
private ResourceBundle bundle;
private String fileEncoding;
public MyResourceBundle(Locale locale, String fileEncoding){
this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
this.fileEncoding = fileEncoding;
}
public MyResourceBundle(Locale locale){
this(locale, "UTF-8");
}
public String getString(String key){
String value = bundle.getString(key);
try {
return new String(value.getBytes("ISO-8859-1"), fileEncoding);
} catch (UnsupportedEncodingException e) {
return value;
}
}
}
The way to use this would be very similar than the regular ResourceBundle usage:
private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)
Or you can use the alternate constructor which uses UTF-8 by default:
private MyResourceBundle labels = new MyResourceBundle("es");

Jena API with REST webservice using Jersey

I am using Jena API to get RDF data from Allegrograph Server. I have written a REST webservice using Jersey jar to get this data.
My java code for the webservice is as shown below:
#GET
#Path("/JENA")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String getData() throws RepositoryException {
AGGraphMaker maker = new AGGraphMaker(conn);
AGGraph graph = maker.getGraph();
AGModel model = new AGModel(graph);
AGQuery agQuery = AGQueryFactory.create(query);
QueryExecution qe = AGQueryExecutionFactory.create(agQuery, model);
String result = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
ResultSet rs = qe.execSelect();
While(rs.hasNext()){
byteArrayOutputStream = new ByteArrayOutputStream();
if("JSON".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsJSON(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
System.out.println("Result is "+result);
} else if("XML".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsXML(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}else if("CSV".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsCSV(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
I get no results for the SPARQL query when I deploy this web service on Tomcat server and test it using REST client app on Chrome and firefox.
But the same code(absolutely no difference in webservice code and this main method code) if I write in a plain java class and run its main method, i am getting 36 results. I am not sure what the issue is.
Please help me in this regard.
You need to separate the concerns:
Move the service logic - the bit that actually queries Allegro graph - to a separate class so that it's properly encapsulated. The API for the class should reflect its responsibilities in your application, not the way that it happens to be working at the moment.
Write JUnit tests for the service class. This is important - it gives you confidence that your service is performing its job correctly, and keeps on doing so as you develop your application.
Write your Jersey method to invoke any service object that conforms to the API of your service class.
Write one or more HTTPUnit (or similar) tests to invoke your REST API. Ideally, you'll use a mock or test double instead of the actual service. What you want to test is whether the HTTP request reaches the right method, and that method delegates to the service object with the right arguments. You're then testing (and debugging!) a smaller number of concerns.
It's much better to work with small units of functionality with a clear idea of what their responsibilities are. And you should definitely learn to work with tests - it's a big win in the medium term, even if it means a bit more learning up front!