I am trying to achieve a very simple goal in soapui
I have created a mock rest service in soapui that I can return static content from if the last resource matches a file name. problem is:
I use Spring RESTTemplate to make a REST call ala:
http://www.sample.com/user/group/{1}/status
where {1} is the only variable (it will be a number like 1111 or 2323)
In the OnRequest script section I should be able to write something simple that allows me to extract this resource from the full url and then craft a return of a static file of the same name ie:
ref = value.at.specified.location.{1}.in.url
return file(ref.xml)
any help translating these 2 pseudo code lines to actual working code would be helpful
this works:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
path = groovyUtils.getProjectPath() + "/docroot/" + mockRequest.getPath().tokenize('/')[4] + ".xml";
try
{
mockRunner.returnFile(mockRequest.httpResponse, new File(path));
mockRequest.httpResponse.status = 201
}
catch (Exception e)
{
mockRequest.httpResponse.status = 403
}
return new com.eviware.soapui.impl.wsdl.mock.WsdlMockResult(mockRequest);
Related
I have a script groovy, this script for live fetching of docker image,
I want to add the authentication function with the private repository, but I am not familiar with groovy, who can help me, thanks
import groovy.json.JsonSlurper
// Set the URL we want to read from, it is MySQL from official Library for this example, limited to 20 results only.
docker_image_tags_url = "https://registry.adx.abc/v2/mysql/tags/list"
try {
// Set requirements for the HTTP GET request, you can add Content-Type headers and so on...
def http_client = new URL(docker_image_tags_url).openConnection() as HttpURLConnection
http_client.setRequestMethod('GET')
// Run the HTTP request
http_client.connect()
// Prepare a variable where we save parsed JSON as a HashMap, it's good for our use case, as we just need the 'name' of each tag.
def dockerhub_response = [:]
// Check if we got HTTP 200, otherwise exit
if (http_client.responseCode == 200) {
dockerhub_response = new JsonSlurper().parseText(http_client.inputStream.getText('UTF-8'))
} else {
println("HTTP response error")
System.exit(0)
}
// Prepare a List to collect the tag names into
def image_tag_list = []
// Iterate the HashMap of all Tags and grab only their "names" into our List
dockerhub_response.results.each { tag_metadata ->
image_tag_list.add(tag_metadata.name)
}
// The returned value MUST be a Groovy type of List or a related type (inherited from List)
// It is necessary for the Active Choice plugin to display results in a combo-box
return image_tag_list.sort()
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
println(e)
}
The problem has been resolved, thank you everyone for your help
// Import the JsonSlurper class to parse Dockerhub API response
import groovy.json.JsonSlurper
// Set the URL we want to read from, it is MySQL from official Library for this example, limited to 20 results only.
docker_image_tags_url = "https://registry.adx.vn/v2/form-be/tags/list"
try {
// Set requirements for the HTTP GET request, you can add Content-Type headers and so on...
def http_client = new URL(docker_image_tags_url).openConnection() as HttpURLConnection
http_client.setRequestMethod('GET')
String userCredentials = "your_user:your_passwd";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
http_client.setRequestProperty ("Authorization", basicAuth);
// Run the HTTP request
http_client.connect()
// Prepare a variable where we save parsed JSON as a HashMap, it's good for our use case, as we just need the 'name' of each tag.
def dockerhub_response = [:]
// Check if we got HTTP 200, otherwise exit
if (http_client.responseCode == 200) {
dockerhub_response = new JsonSlurper().parseText(http_client.inputStream.getText('UTF-8'))
} else {
println("HTTP response error")
System.exit(0)
}
// Prepare a List to collect the tag names into
def image_tag_list = []
// Iterate the HashMap of all Tags and grab only their "names" into our List
dockerhub_response.tags.each { tag_metadata ->
image_tag_list.add(tag_metadata)
}
// The returned value MUST be a Groovy type of List or a related type (inherited from List)
// It is necessary for the Active Choice plugin to display results in a combo-box
return image_tag_list.sort()
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
println(e)
}
here is the result
I need to read following elasticksearch metrics
Version
Up-time
No. of Jobs
Overall Health
No. of Nodes
Disk Available in %
JVM Heap Size
No. of Indices
Primary Shards
Replica Shards
in ASP.Net MVC application. My question :-
Is it possible to read all above metrics with one API call in elasticsearch?
I have written following method
private static string CheckESHealth()
{
string esurl = "http://localhost:9200/_cluster/health";
HttpClient httpClient = new HttpClient();
string strReturnVal = string.Empty;
try
{
var response = httpClient.GetAsync(new Uri(esurl)).Result;
if (response.IsSuccessStatusCode)
{
var esdata = response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(esdata))
{
JObject jobject = JObject.Parse(esdata);
//as a example i have taken only status.. but i need all paramters mention above
strReturnVal = jobject["status"].ToString();
}
}
else
{
strReturnVal = "Errored : Received status code : " + response.StatusCode;
}
}
catch (Exception ex)
{
strReturnVal = "Errored : " + ex.Message;
}
return strReturnVal;
}
in above example i am using :- GET _cluster/health command which give following result
enter image description here
but i am trying to read all above metrics in one API call
I didn't find a way to read above[in question] mentioned metrics in one query. so, i used following queries to get metrics.
http://localhost:9200/_cat/health?h=cluster,status,node.total,shards,pri,relo&format=json
http://localhost:9200/_cat/nodes?h=version,uptime,heap.percent&format=json
http://localhost:9200/_cat/allocation?h=disk.percent&format=json
I am newbie to web service. Due to requirement I have to send a file[most probably in txt format] to server through REST web service.
I am getting the exception like below.
MessageBodyWriter not found for media type=application/json, type=class gvjava.org.json.JSONObject, genericType=class gvjava.org.json.JSONObject.
Here is my web service method.
#Path("{c}")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String convert(#PathParam("c") JSONObject object) throws JSONException {
String result = "";
return "<ctofservice>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>";
}
Now client code is like below
JSONObject data_file = new JSONObject();
data_file.put("file_name", uploadFile.getName());
data_file.put("description", "Something about my file....");
data_file.put("file", uploadFile);
Client client = ClientBuilder.newClient();
webTarget = client.target(uploadURL).path("ctofservice").path("convert");
Response value = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(data_file,MediaType.APPLICATION_JSON_TYPE),
Response.class);
Please help me with this.
Thanks in advance.
------------------------------------------------------------------------
As suggested by peeskillet in the answer below, I tried to send file through multipart. Still I am facing exception of no octet stream found.
Below is my rest api
#Path("{c}")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response convert(#FormDataParam("file") FormDataContentDisposition file) {
String result = "";
Some operation with attached parameter ...
return Response.status(200).entity(result).build();
}
Here is my test client
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
uploadFile,MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(fileDataBodyPart);
Client client = Client.create();
WebResource webResource = client
.resource(uploadURL).path("ctofservice");
ClientResponse response = webResource.accept("application/json")
.post(ClientResponse.class,multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
And I am getting the exception below
I am not able to understand why I need to send data as MediaType.APPLICATION_OCTET_STREAM_TYPE ? As I have used multipart as media type before ...
I appreciate your help..
Without needing to configuring anything else, the easiest way to get around this is to just use a String instead of the actual JSONObject (i.e. just passing toString())
.post(Entity.json(data_file.toString()))
The problem with using JSONObject is that there is no provider that knows how to handle the conversion. You will have the same problem on the server side, where there is no provider to handle the conversion to JSONObject. So you will need to just do
#POST
public Response post(String json) {
JSONObject jsonObject = new JSONObject(json);
}
If you really want to be able to just use JSONObject without needing to use a String, then you should check out this post.
As an aside, this is not valid JSON (it's XML)
"<ctofservice>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>"
but you are saying that the endpoint returns JSON
This question relates to the Mendeley API.
http://dev.mendeley.com/
When using the implicit auth type: http://dev.mendeley.com/reference/topics/authorization_overview.html
I seem to only receive a subset of data for a given document. For example, the 'websites' field seems to not come through even when it is populated.
I am only experiencing this issue using the implicit auth type and not other auth types.
Are any other Mendeley API users experiencing this? It seems like a bug.
Certain fields get returned depending on the document view that you specify. This was implemented to be able to support the needs of multiple clients e.g. mobile clients require smaller datasets than larger web clients
Please read - http://dev.mendeley.com/methods/#document-views
You need to specify 'view=bib' on your endpoint call.
Here is a very crude worked example just using Java
#Test
public void testImplicitGrantFlow() {
String random = RandomStringUtils.random(5);
String query = String.format(
"?client_id=%s&redirect_uri=%s&response_type=token&scope=all&state=%s", IMPLICIT_GRANT_FLOW_CLIENT_ID, "http://localhost:5000/callback", random);
ClientResponse authorise = jerseyClient.resource(AUTH_URL + query)
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertThat(authorise.getStatus()).isEqualTo(200);
ClientResponse postFormDataResponse = jerseyClient.resource(AUTH_URL + query)
.entity("username=joyce.stack#mendeley.com&password=spuds", MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class);
assertThat(postFormDataResponse.getStatus()).isEqualTo(302);
String queryString = postFormDataResponse.getHeaders().get("Location").get(0);
Matcher matcher = ACCESS_TOKEN_REGEX.matcher(queryString);
matcher.find();
String accessToken = matcher.group(1);
matcher = STATE_REGEX.matcher(queryString);
matcher.find();
String state = matcher.group(1);
assertNotNull(accessToken);
assertThat(queryString).contains(accessToken);
assertNotNull(state);
assertThat(queryString).contains(state);
ClientResponse response = jerseyClient.resource(OAuthBaseClass.DOCUMENTS_URL)
.header("Authorization", "Bearer " + accessToken)
.get(ClientResponse.class);
assertThat(response.getStatus()).isEqualTo(200);
List<Document> documents = response.getEntity(new GenericType<List<Document>>() {
});
assertThat(documents.size()).isGreaterThan(0);
ListIterator<Document> documentListIterator = documents.listIterator();
while (documentListIterator.hasNext()) {
Document next = documentListIterator.next();
System.out.println(next.getTitle());
System.out.println(next.getWebsites());
}
}
I am trying to generate the OData Proxy for the service : http://services.odata.org/Northwind/Northwind.svc/$metadata
I am using System.Data.Services.Design.EntityClassGenerator for generating the OData proxy.
When I instantiate the EntityClassGenerator and call GenerateCode the output has no errors. But there is no code in the generated proxy code.
The same code works for my own service. But when I point it to any external service the EntityClassGenerator is not working.
Here is the code :
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(metadataEndpoint);
webRequest.Method = "GET";
webRequest.ContentType = "text/xml;encoding='utf-8";
webRequest.Proxy = (proxy != null) ? proxy : WebRequest.DefaultWebProxy;
using (WebResponse response = webRequest.GetResponse())
{
string xml = string.Empty;
XmlReaderSettings settings = new XmlReaderSettings();
using (TextReader reader = new StreamReader(response.GetResponseStream()))
{
xml = reader.ReadToEnd();
using (XmlTextReader sourceReader = new XmlTextReader(reader))
{
using (StringWriter targetWriter = new StringWriter())
{
// Generate the OData End point proxy.
EntityClassGenerator entityGenerator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode);
entityGenerator.OnPropertyGenerated += new EventHandler<PropertyGeneratedEventArgs>(entityGenerator_OnPropertyGenerated);
IList<System.Data.Metadata.Edm.EdmSchemaError> errors = entityGenerator.GenerateCode(sourceReader, targetWriter, namespacename);
entityGenerator.OnPropertyGenerated -= new EventHandler<PropertyGeneratedEventArgs>(entityGenerator_OnPropertyGenerated);
odataProxyCode = targetWriter.ToString();
}
}
}
}
I found the code in the question to be a useful starting point for doing exactly what the OP was asking. So even though the OP doesn't accept answers, I'll describe the changes I made to get it to work in case it is useful to someone else.
Removed the xml = reader.ReadToEnd(); call. I assume that was for debugging purposes to look at the response from the web request, but it had the result of "emptying" the reader object of the response. That meant that there was nothing left in the reader for the GenerateCode call.
The important one: Changed the use of EntityClassGenerator to System.Data.Services.Design.EntityClassGenerator. In the code below, I included the entire name space for clarity and specificity. Based on the code in the question, it appears the OP was probably using System.Data.Entity.Design.EntityClassGenerator. I used .NET Reflector to examine datasvcutil.exe, which is a command-line utility that can generate the proxy classes. I saw that it referenced the generator in that other name space.
For figuring out the problems, I dumped the errors from the GenerateCode call. One could examine them in the debugger, but some kind of automated checking of them would be needed regardless.
Here is what I ended up with:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.
Create("http://services.odata.org/Northwind/Northwind.svc/$metadata");
webRequest.Method = "GET";
webRequest.ContentType = "text/xml;encoding='utf-8";
webRequest.Proxy = WebRequest.DefaultWebProxy;
using (WebResponse response = webRequest.GetResponse())
{
using (TextReader reader = new StreamReader(response.GetResponseStream()))
{
using (XmlTextReader sourceReader = new XmlTextReader(reader))
{
using (StringWriter targetWriter = new StringWriter())
{
// Generate the OData End point proxy.
System.Data.Services.Design.EntityClassGenerator entityGenerator =
new System.Data.Services.Design.EntityClassGenerator(
System.Data.Services.Design.LanguageOption.GenerateCSharpCode);
IList<System.Data.Metadata.Edm.EdmSchemaError> errors =
entityGenerator.GenerateCode(sourceReader, targetWriter,
"My.Model.Entities");
foreach (System.Data.Metadata.Edm.EdmSchemaError error in errors)
Console.WriteLine("{0}: {1}", error.Severity.ToString(), error.Message);
string odataProxyCode = targetWriter.ToString();
}
}
}
}