How to use custom templates in Swagger - java

I have this JavaJaxRs dictionary with my templates:
/templates/JavaJaxRs
I edited some of them. And want to use them for my API generation (Code was inspired from this approach from https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java):
System.out.println("Generating API for: " + location);
DefaultGenerator generator = new DefaultGenerator();
Swagger swagger = new SwaggerParser().read(location);
CodegenConfig config = CodegenConfigLoader.forName(this.language);
config.setOutputDir(new File(this.apiGeneratedSrcPath).getPath());
if (null != templateDirectory) {
config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory);
}
if (null != modelPackage) {
config.additionalProperties().put(MODEL_PACKAGE_PARAM, modelPackage);
}
if (null != apiPackage) {
config.additionalProperties().put(API_PACKAGE_PARAM, apiPackage);
}
if (null != invokerPackage) {
config.additionalProperties().put(INVOKER_PACKAGE_PARAM, invokerPackage);
}
if (configOptions != null) {
for (CliOption langCliOption : config.cliOptions()) {
if (configOptions.containsKey(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(),
configOptions.get(langCliOption.getOpt()));
}
}
}
if (null != configurationFile) {
Config genConfig = ConfigParser.read(configurationFile);
if (null != genConfig) {
for (CliOption langCliOption : config.cliOptions()) {
if (genConfig.hasOption(langCliOption.getOpt())) {
config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt()));
}
}
} else {
throw new RuntimeException("Unable to read configuration file");
}
}
ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger);
input.setConfig(config);
generator.opts(input).generate();
Somehow i always get the code generated with the standard template file.
UPDATE:
When i remember correctly i had a conditional bug on:
if(null != templateDirectory)
config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory);
or somewhere else but with the right condition, code was working as intended.
I let the question stay here, maybe it will help some other users.

You can get the help options for the code generator like such:
java -jar swagger-codegen-cli.jar help generate
Which should tell you that you can override the template location with the -t parameter:
java -java swagger-codegen-cli.jar generate -l {language} -t path/to/templates

Regarding the above ava -java swagger-codegen-cli.jar generate -l {language} -t path/to/templates,
I've managed to make it work with current being-worked-on-release (2.2.0).
With 2.1.6 (current GA) it does not work.
I have posted the following on swagger-codegen at GitHub:
https://github.com/swagger-api/swagger-codegen/issues/3188
Did not get any attention though...

Related

Android unable to understand kotlin function

I am not very well versed with Kotlin and I am preferring Java over Kotlin while learning Android. But I am stuck at a piece of code which is as follows:
private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() } }
return if (mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}
The following function is called in onCreate method as var outputDirectory: File = getOutputDirectory();
Can you please help me convert the code into Java and in understanding it?
Thank you.
private File getOutputDirectory() {
File mediaDir = null;
if (getExternalMediaDirs().size > 0) {
mediaDir = new File(getExternalMediaDirs()[0], getResources().getString(R.string.app_name));
mediaDir.mkdirs();
}
return if (mediaDir != null && mediaDir.exists())
mediaDir
else
filesDir
}
Here is the process on how to convert Kotlin code to Java code.
https://www.geeksforgeeks.org/how-to-convert-kotlin-code-to-java-code-in-android-studio/
But I suggest you to learn Kotlin as it is faster and preferred for Android app development.

Fetching data from zookeeper znode

I tried to get the data from zookeeper's znode using Java API. Followed below link
https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
Program: ZKGetData.java
I'm getting results like this
"(clusterSecondarynn1node4.test.com �>(�>)"
How to get "node4.test.com" alone.
It is strongly recommended to use some layer against ZK, like Apache Curator, or ZkClient.
Here's an example
CuratorFramework zkClient = CuratorFrameworkFactory.builder().connectString("localhost:2181").build();
zkClient.start();
boolean isExist = zkClient.checkExists().forPath("/myNode") != null;
if (isExist) {
byte[] myNodeBytes = zkClient.getData().forPath("/myNode");
if (myNodeBytes != null && myNodeBytes.length > 0) {
System.out.println(new String(myNodeBytes));
}
}
else {
zkClient.create().withMode(CreateMode.PERSISTENT).forPath("/myNode", "foo".getBytes());
}

Java Jackson DeserializationFeature

I have problem with Jackson and DeserializationFeature. From WebService I get JSON field like:
"location":null,
OR
"location":{
"code":"YYYYYY",
"label":"XXXXXX"
},
When I try get code or label eg.
project.getLocation().getCode();
Java return NullPointerException.
My current code is written like eg. and its work fine.
if (project.getLocation() != null) {
location_code = project.getLocation().getCode();
location_label = project.getLocation().getLabel();
} else {
location_code = null;
location_label = null;
}
Which option of DeserializationFeature is right for this problem?
Not sure about DeserializationFuture option, but simple null check could do the job:
String code = null;
Location location = project.getLocation(); // maybe, some yours location type
if (location != null) {
code = location.getCode();
}

Fastest/shortest way to the root folders?

I'm using Google Drive SDK v2 on Android to get the list of root folders. Currently I see these required steps - which seem to load forever. Is there no faster way?
I tried to use the search with the q= parameter but I don't get it to work (FileList vs. Files.List) - different API levels?
FileList files = drive.files().list().setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false");
This is what I do currently:
About about = drive.about().get().execute();
if (about != null) {
ChildList childList = drive.children().list(about.getRootFolderId()).execute();
if (childList != null) {
List<ChildReference> listChildReference = childList.getItems();
for (ChildReference childReference : listChildReference) {
File file = drive.files().get(childReference.getId()).execute();
if (file != null) {
String fileExtension = file.getFileExtension();
String mimeType = file.getMimeType();
if (mimeType != null
&& mimeType.equals("application/vnd.google-apps.folder")
&& (fileExtension == null || fileExtension.equals(""))) {
Log.d(this.getClass().getName(), file.getTitle());
}
}
}
}
}
What's the fastest for an Android app?
Thanks in advance.
My personal opinion is avoid the Drive SDK and call the REST API directly. It's a fairly simple API, and the way the documentation is structured, you are forced to understand it anyway in order to use the SDK. You have the benefit that if something doesn't work, you can directly compare your app with what's happening on the wire and resolve any problems.
Found it:
#Override
protected ArrayList<File> doInBackground(final Void... voids) {
ArrayList<File> result = new ArrayList<File>();
Files.List request = null;
boolean ok = true;
do {
try {
request = drive
.files()
.list()
.setMaxResults(200)
.setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false");
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException exception) {
ok = false;
}
} while (ok && request.getPageToken() != null && request.getPageToken().length() > 0);
return result;
}

File Upload in fire fox

Iam not able to upload files in FireFox and safari but iam able to do it successfully in explorer.
When i tried to debug i found out that in case of IE the upload browser is giving the entire file as eg C:\Documents and Settings\jjayashree\My Documents\price.csv
but where as in FF and safari the upload widget is just giving the file name with no extension.
previously code was like this
if (fileName.contains("\")) {
index = fileName.lastIndexOf("\");
}
if (this.fileName != null && this.fileName.trim().length() > 0 && index >= 0) {
this.fileName = this.fileName.substring(index + 1, this.fileName.length());
int dotPosition = fileName.lastIndexOf('.');
String extension = fileName.substring(dotPosition + 1, fileName.length());
try {
if (profileType.equalsIgnoreCase("sampleProfile")) {
if (extension.equalsIgnoreCase("csv")) {
//fileNameTextBox.setText(this.fileName);
this.form.submit();
} else {
new CustomDialogBox(Nexus.INFO_MESSAGE, MessageConstants.SPECIFY_FILE_NAME_MSG).show();
}
}
} catch (Exception e) {
Window.alert("SPECIFY_VALID_FILE_NAME_MSG");
}
} else {
Window.alert("SPECIFY_A_FILE_MSG");
}
i changed it as
if (this.fileName != null && this.fileName.trim().length() > 0) {
this.fileName = this.fileName.substring(this.fileName.lastIndexOf("\") + 1, this.fileName.length());
}
i found it working but when the same is deployed in linux iam getting an error
I also hav a doubt becos in the doPost of servlet iam using fileName.replace("\", "/");
is this the problem. . How wil mozilla encounter this fileName.replace() wil it just see and find nothing can be replced and go or wil it throw any kind of Exception
Maybe try gwtupload? It simplifies file loading to one function call, and handles all the backend for you. It's a little complicated to get working but there's a tutorial on the site on how to do it.
http://code.google.com/p/gwtupload/

Categories

Resources