Swagger Parser does not get all the paths from swagger.json - java

Duplicate paths are not allowed by the Swagger 1.2 Specification:
In the apis array, there MUST be only one API Object per path.
The parser simply ignores the duplicates. and I have a swagger.json file and I want to extract all the paths and their methods from this file. I tried to use Json Parser but I have no idea how to use it. How can I do so?
Here is my code :
import java.util.Map;
import java.util.Map.Entry;
import org.json.simple.parser.JSONParser;
import io.swagger.models.HttpMethod;
import io.swagger.models.Operation;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.util.Iterator;
#SuppressWarnings("unused")
public class JSONReadExample {
#SuppressWarnings({ "unchecked", "deprecation" })
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:\\Users\\eya\\Desktop\\nodes.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray apis = (JSONArray) jsonObject.get("apis");
Iterator<JSONObject> iterator = apis.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
and it shows me only the whole path ! I don't know to extract the opération and the description ...

Related

How to load all the examples in to the #ExampleObject without specifying the ref so its visible in SwaggerUI?

I am developing a simple application where I would like to read the files from a remote URL and add them to the #ExampleObject. I am able to achieve this using CustomClass SchemaFileReader implements OASFilter but the only problem is that I need to manually specify the name of the file in the ref such as #ExampleObject(name = "Example1", ref = "Example1.json").
Since I am reading the URL there can be many files and I do not know the name of all the files so I need an approach where I can add the #ExampleObject dynamically directly without specifying ref. Rather it should read all the data from the examples. Can someone please specify some logic on how to achieve this?
I have posted my complete code on GitHub: https://github.com/Aravinda93/code-with-quarkus.
As of now, I have added manually 2 files to my #ExampleObject by specifying the ref but I need a dynamic approach to add all the 3 files present in the resourses/jsonfiles without providing the ref for all the files individually.
To run the application, please follow the following steps:
Open the terminal for the project and run mvn compile quarkus:dev
Press d in the command line this should open the Swagger-UI.
Select swagger-ui from SmallRye OpenAPI
Expand api/generate and there we will see only 2 files under examples. I need an approach to get all 3 field without specifying the ref for all of them.
After trying some things, finally, this worked for me. Posting here as it can be useful to someone in the future:
Following is my RestControllerResponse:
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;
#Path("/api")
public class RestControllerResponse {
#Path("/generate")
#POST
#Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#RequestBody(description = "Testing Example without ref",
content = #Content())
public String generator(final Map<String, Object> input) throws Exception {
return "Hello From Generator Method";
}
}
Following is my SchemaFileReader which has the capability to read all files and respective subfolder with files and get the file contents and add to examples, pass the required URL to the getFolderData method:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.models.Components;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.examples.Example;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class SchemaFileReader implements OASFilter {
private final ObjectMapper objectMapper = new ObjectMapper();
private final CloseableHttpClient httpClient = HttpClients.createDefault();
#Override
public void filterOpenAPI(OpenAPI openAPI) {
Components defaultComponents = OASFactory.createComponents();
if (openAPI.getComponents() == null) {
openAPI.setComponents(defaultComponents);
}
try {
//generateExamples().forEach(openAPI.getComponents()::addExample);
generateExamples().entrySet().forEach(ex -> openAPI.getPaths().getPathItem("/api/generate").getPOST().getRequestBody().getContent().getMediaType(MediaType.APPLICATION_JSON).addExample(ex.getKey(), ex.getValue()));
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String, Example> generateExamples() throws Exception {
final Map<String, Example> examples = new LinkedHashMap<>();
getFolderData(examples, "PLACE YOUR URL HERE");
//getExamples(examples);
return examples;
}
//If user has provided the folder then recursively loop over it to get the files and their contents
private void getFolderData(final Map<String, Example> examples, final String inputURL) throws IOException {
//Make the request to provided folder path and get the folder/files from it.
final CloseableHttpResponse folderResponse = httpClient.execute(new HttpGet(inputURL));
final String responseBody = EntityUtils.toString(folderResponse.getEntity(), StandardCharsets.UTF_8);
//If the folder API request provides valid response and contains the list of files or folders then loop over it else its plain/text with direct contents
if (folderResponse.getStatusLine().getStatusCode() == 200 && ContentType.get(folderResponse.getEntity()).toString().equalsIgnoreCase("application/json; charset=utf-8")) {
final JSONArray jsonArray = new JSONArray(responseBody);
jsonArray.forEach(item -> {
final JSONObject obj = (JSONObject) item;
if (obj.getString("type").equalsIgnoreCase("file")) {
//Make request to each file in the GitHub folder and obtain its contents
try {
final CloseableHttpResponse fileResponse = httpClient.execute(new HttpGet(obj.getString("download_url")));
//If the response code is 200 then add the contents to Example
if (fileResponse.getStatusLine().getStatusCode() == 200) {
final String fileResponseBody = EntityUtils.toString(fileResponse.getEntity(), StandardCharsets.UTF_8);
if (obj.getString("download_url").contains(".json")) {
examples.put(obj.getString("name"), OASFactory.createExample().value(objectMapper.readValue(fileResponseBody, ObjectNode.class)));
} else if (obj.getString("download_url").contains(".xml")) {
examples.put(obj.getString("name"), OASFactory.createExample().value(fileResponseBody));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
getFolderData(examples, obj.getString("url"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else if (folderResponse.getStatusLine().getStatusCode() == 200 && ContentType.get(folderResponse.getEntity()).toString().equalsIgnoreCase("text/plain; charset=utf-8")) {
//if direct file provided then add its content
examples.put(inputURL.substring(inputURL.lastIndexOf("/")), OASFactory.createExample().value(objectMapper.readValue(responseBody, ObjectNode.class)));
}
}
}

how to convert arbitrary JSON to XML using BaseX?

How is arbitrary JSON converted to arbitrary XML using BaseX?
I'm looking at JsonParser from BaseX for this specific solution.
In this case, I have tweets using Twitter4J:
package twitterBaseX;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import main.LoadProps;
import org.basex.core.BaseXException;
import twitter4j.JSONException;
import twitter4j.JSONObject;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterObjectFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterOps {
private static final Logger log = Logger.getLogger(TwitterOps.class.getName());
public TwitterOps() {
}
private TwitterFactory configTwitterFactory() throws IOException {
LoadProps loadTwitterProps = new LoadProps("twitter");
Properties properties = loadTwitterProps.loadProperties();
log.fine(properties.toString());
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true)
.setJSONStoreEnabled(true)
.setOAuthConsumerKey(properties.getProperty("oAuthConsumerKey"))
.setOAuthConsumerSecret(properties.getProperty("oAuthConsumerSecret"))
.setOAuthAccessToken(properties.getProperty("oAuthAccessToken"))
.setOAuthAccessTokenSecret(properties.getProperty("oAuthAccessTokenSecret"));
return new TwitterFactory(configurationBuilder.build());
}
public List<JSONObject> getTweets() throws TwitterException, IOException, JSONException {
Twitter twitter = configTwitterFactory().getInstance();
Query query = new Query("lizardbill");
QueryResult result = twitter.search(query);
String string = null;
JSONObject tweet = null;
List<JSONObject> tweets = new ArrayList<>();
for (Status status : result.getTweets()) {
tweet = jsonOps(status);
tweets.add(tweet);
}
return tweets;
}
private JSONObject jsonOps(Status status) throws JSONException, BaseXException {
String string = TwitterObjectFactory.getRawJSON(status);
JSONObject json = new JSONObject(string);
String language = json.getString("lang");
log.fine(language);
return json;
}
}
The JSONObject from Twitter4J cannot just get jammed into XML?
There are a number of online converters which purport to accomplish this, and, which, at least at first glance, seem quite adequate.
see also:
Converting JSON to XML in Java
Java implementation of JSON to XML conversion
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc for more information

marshal Object to CSV

I'm trying to marshal an Object into a csv String. I have created a method that can convert any object into a csv String but I keep getting the exception:
java.lang.NoSuchMethodError: org.codehaus.jackson.map.ObjectMapper.writer(Lorg/codehaus/jackson/FormatSchema;)Lorg/codehaus/jackson/map/ObjectWriter;
Marshal method:
public static final synchronized String marshal(final Object object, final CsvSchema csvSchema) throws IOException {
String CSV_FILTER_NAME = "csvFilter";
HashSet<String> columnNames = new HashSet<>();
for (CsvSchema.Column column : csvSchema) {
columnNames.add(column.getName());
}
SimpleBeanPropertyFilter csvReponseFilter = new SimpleBeanPropertyFilter.FilterExceptFilter(columnNames);
FilterProvider filterProvider = new SimpleFilterProvider().addFilter(CSV_FILTER_NAME, csvReponseFilter);
CsvMapper csvMapper = new CsvMapper();
csvMapper.setFilters(filterProvider);
csvMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
#Override
public Object findFilterId(AnnotatedClass annotatedClass) {
return CSV_FILTER_NAME;
}
});
ObjectWriter objectWriter = csvMapper.writer(csvSchema);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
objectWriter.writeValue(byteArrayOutputStream, csvSchema);
return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
}
Main method:
public static void main(String args[]) {
CsvSchema csvSchema = CsvSchema.builder()
.addColumn("name")
.addColumn("age")
.addColumn("height")
.addColumn("weight")
.setUseHeader(true)
.build()
.withLineSeparator("\n");
Person person = new Person("Tim", "32", "184", "100");
try {
System.out.println(CsvUtilities.marshal(person, csvSchema));
} catch (IOException ex) {
Logger.getLogger(CsvUtilities.class.getName()).log(Level.SEVERE, null, ex);
}
}
What is causing this exception?
EDIT Here's all my imports:
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.introspect.AnnotatedClass;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.map.ser.FilterProvider;
import org.codehaus.jackson.map.ser.impl.SimpleBeanPropertyFilter;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
See the jars in your class path. It could be that there are two or different version of jackson jar which does not have this method. Maybe an older version been laoded in by the Class loader.
Also inspect your dependencies which you have added to the project.

property function extension sparql

I want to write a property function extension sparql with arq jena, how can I write?
Request:
SELECT *
WHERE {?Person f:Next(name) ?x.}
my function code:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.jena.atlas.logging.Log;
import org.apache.jena.graph.Node;
import org.apache.jena.query.QueryBuildException;
import org.apache.jena.query.QueryException;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.sparql.engine.ExecutionContext;
import org.apache.jena.sparql.engine.QueryIterator;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.engine.iterator.QueryIterNullIterator;
import org.apache.jena.sparql.pfunction.PFuncSimple;
import org.apache.jena.sparql.pfunction.PFuncSimpleAndList;
import org.apache.jena.sparql.pfunction.PropFuncArg;
import org.apache.jena.sparql.pfunction.PropertyFunction;
import org.apache.jena.sparql.pfunction.PropertyFunctionFactory;
import org.apache.jena.sparql.util.IterLib;
public class Next implements PropertyFunctionFactory {
#Override
public PropertyFunction create(final String uri)
{
return new PFuncSimple()
{
#Override
public QueryIterator execEvaluated(final Binding parent, final Node subject, final Node predicate, final Node object, final ExecutionContext execCxt)
{
Model model = ModelFactory.createDefaultModel();
InputStream is = null;
try {
is = new BufferedInputStream(
new FileInputStream( "C:\\\\fichier rdf/journal.webscience.org-vivo.rdf"));
} catch (FileNotFoundException ex) {
Logger.getLogger(haschild.class.getName()).log(Level.SEVERE, null, ex);
}
model.read(new InputStreamReader(is), "");
StmtIterator iter = model.listStatements();
extract the sebject , predicate and object from rdf:
for (;iter.hasNext();) {
Statement stmt = iter.nextStatement();
Resource sub = stmt.getSubject();
Property pred = stmt.getPredicate();
RDFNode obj = stmt.getObject();
comparison the suject and predicate of the rdf with subject and predicate of the request
if ((sub.toString().equals(subject.toString()))|| (pred.toString().equals(predicate.toString())))
return new QueryIterPlainWrapper ((Iterator<Binding>) obj,execCxt);
}
return null;
}
};
}
}
and how i can register my function
Property functions look in syntax like regular properties. There isn't a special syntax.
?Person :somePropertyFunction ?x .
The property function has access to the subject and object of the triple pattern. There is also help for when subject or object are an RDF list.
Usually the arguments go as the object or object list and results are as a subject or subject list.
You shouldn't need to use .toString.
You can't cast obj to an Iterator<Binding>.
Take a look at some existing property functions. splitIRI is a simple one. concat might be useful to look at - it takes a list of argument (object position) and returns a subject (variable).

Freebase searchAPI return types

Is it possible to return the type of an entities (e.g Location)
just like how the freebase search works? I am using freebase search sample codes (I'll provide them below) to generate the search results but even using the wildcard, it does not extract the entity types, here are some of the sample results.
SAMPLE RESULTS
["\/en\/bukit_panjang","Bukit Panjang",284.883636,"\/m\/04fxxf","en"]
["\/en\/bukit_panjang_mrt_station",{"id":"\/metropolitan_transit\/transit_stop","name":"Transit Stop"},"Bukit Panjang LRT\/MRT Station",250.857147,"\/m\/0661mk1","en"]
["\/en\/bukit_panjang_plaza",{"id":"\/business\/shopping_center","name":"Shopping center"},"Bukit Panjang Plaza",229.566818,"\/m\/02q_h6s","en"]
SEARCH SAMPLE CODES
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.jayway.jsonpath.JsonPath;
import java.io.FileInputStream;
import java.util.Properties;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SearchSample {
public static Properties properties = new Properties();
public static void main(String[] args) {
try {
properties.load(new FileInputStream("freebase.properties"));
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
url.put("query", "Bukit Panjang");
//url.put("filter", "(any type:/people/person domain:location/citytown/)");
url.put("filter", "(any part_of:singapore)");
url.put("limit", "10");
url.put("indent", "true");
url.put("key", properties.get("API_KEY"));
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject)parser.parse(httpResponse.parseAsString());
JSONArray results = (JSONArray)response.get("result");
for (Object result : results) {
System.out.println(JsonPath.read(result,"$.*").toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Use the output parameter to tailor the output, as described on this page:
https://developers.google.com/freebase/v1/search-output
e.g.
https://www.googleapis.com/freebase/v1/search?indent=true&filter=%28all+name%7Bfull%7D%3A%22Bukit+Panjang%22+part_of:singapore%29&output=%28type%29
(although you may want to consider using the notable_type or notable_for instead of raw type, depending on what your goal is)

Categories

Resources