Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix various issues reported by SonarCloud reports #2229

Merged
merged 14 commits into from
Mar 4, 2019
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Telstra](https://dev.telstra.com)
- [TUI InfoTec GmbH](http://www.tui-infotec.com/)
- [unblu inc.](https://www.unblu.com/)
- [Veamly](https://www.veamly.com/)
- [Xero](https://www.xero.com/)
- [Zalando](https://www.zalando.com)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,18 @@ public class ZipUtil {
public void compressFiles(List<File> listFiles, String destZipFile)
throws IOException {

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile));

for (File file : listFiles) {
if (file.isDirectory()) {
addFolderToZip(file, file.getName(), zos);
} else {
addFileToZip(file, zos);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile))) {

for (File file : listFiles) {
if (file.isDirectory()) {
addFolderToZip(file, file.getName(), zos);
} else {
addFileToZip(file, zos);
}
}
}

zos.flush();
zos.close();
zos.flush();
}
}

/**
Expand All @@ -84,15 +84,12 @@ private void addFolderToZip(File folder, String parentFolder, ZipOutputStream zo

zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName()));

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

long bytesRead = 0;
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;

while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
bytesRead += read;
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
byte[] bytesIn = new byte[BUFFER_SIZE];
int read;
while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
}
}

zos.closeEntry();
Expand All @@ -112,13 +109,12 @@ private static void addFileToZip(File file, ZipOutputStream zos) throws FileNotF
IOException {
zos.putNextEntry(new ZipEntry(file.getName()));

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;

while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
byte[] bytesIn = new byte[BUFFER_SIZE];
int read;
while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
}
}

zos.closeEntry();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ public File writeToFile(String filename, String contents) throws IOException {
File parent = new File(output.getParent());
parent.mkdirs();
}
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(output), "UTF-8"));

out.write(contents);
out.close();
try (Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(output), "UTF-8"))) {
out.write(contents);
}
return output;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1251,23 +1251,7 @@ public String toExampleValue(Schema schema) {
return schema.getExample().toString();
}

if (ModelUtils.isBooleanSchema(schema)) {
return "null";
} else if (ModelUtils.isDateSchema(schema)) {
return "null";
} else if (ModelUtils.isDateTimeSchema(schema)) {
return "null";
} else if (ModelUtils.isNumberSchema(schema)) {
return "null";
} else if (ModelUtils.isIntegerSchema(schema)) {
return "null";
} else if (ModelUtils.isStringSchema(schema)) {
return "null";
} else if (ModelUtils.isObjectSchema(schema)) {
return "null";
} else {
return "null";
}
return getPropertyDefaultValue(schema);
}

/**
Expand All @@ -1282,6 +1266,16 @@ public String toDefaultValue(Schema schema) {
return schema.getDefault().toString();
}

return getPropertyDefaultValue(schema);
}

/**
* Return property value depending on property type
* @param schema property type
* @return property value
*/
private String getPropertyDefaultValue(Schema schema) {
//NOSONAR
if (ModelUtils.isBooleanSchema(schema)) {
return "null";
} else if (ModelUtils.isDateSchema(schema)) {
Expand Down Expand Up @@ -4500,6 +4494,7 @@ public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
if (body == null) {
LOGGER.error("body in fromRequestBody cannot be null!");
throw new RuntimeException("body in fromRequestBody cannot be null!");
}
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
codegenParameter.baseName = "UNKNOWN_BASE_NAME";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.openapitools.codegen;

import java.util.Optional;
import java.util.Set;

public class SpecValidationException extends RuntimeException {
Expand Down Expand Up @@ -105,28 +106,28 @@ public void setWarnings(Set<String> warnings) {
@Override
public String getMessage() {
int errorCount = 0;
if (errors != null) {
errorCount = errors.size();
}
if (errors != null) errorCount = errors.size();
int warningCount = 0;
if (warnings != null) {
warningCount = warnings.size();
}
if (warnings != null) warningCount = warnings.size();

StringBuilder sb = new StringBuilder();
sb.append(System.lineSeparator())
.append("Errors: ")
.append(System.lineSeparator());
errors.forEach(msg ->
sb.append("\t-").append(msg).append(System.lineSeparator())
);

if (!warnings.isEmpty()) {
Optional.ofNullable(errors).ifPresent(_errors -> {
for (String msg : errors) {
sb.append("\t-").append(msg).append(System.lineSeparator());
}
});

Optional.ofNullable(warnings).filter(warnings -> !warnings.isEmpty()).ifPresent(_errors -> {
sb.append("Warnings: ").append(System.lineSeparator());
warnings.forEach(msg ->
sb.append("\t-").append(msg).append(System.lineSeparator())
);
}
for (String msg : errors) {
sb.append("\t-").append(msg).append(System.lineSeparator());
}
});

return super.getMessage() + " | " +
"Error count: " + errorCount + ", Warning count: " + warningCount + sb.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,21 +254,21 @@ private Object resolvePropertyToExample(String propertyName, String mediaType, S
} else if (ModelUtils.isDateTimeSchema(property)) {
return "2000-01-23T04:56:07.000+00:00";
} else if (ModelUtils.isNumberSchema(property)) {
Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue();
Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue();
Double min = getPropertyValue(property.getMinimum());
Double max = getPropertyValue(property.getMaximum());
if (ModelUtils.isFloatSchema(property)) { // float
return (float) randomNumber(min, max);
} else if (ModelUtils.isDoubleSchema(property)) { // decimal/double
return new BigDecimal(randomNumber(min, max));
return BigDecimal.valueOf(randomNumber(min, max));
} else { // no format defined
return randomNumber(min, max);
}
} else if (ModelUtils.isFileSchema(property)) {
return ""; // TODO

} else if (ModelUtils.isIntegerSchema(property)) {
Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue();
Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue();
Double min = getPropertyValue(property.getMinimum());
Double max = getPropertyValue(property.getMaximum());
if (ModelUtils.isLongSchema(property)) {
return (long) randomNumber(min, max);
}
Expand Down Expand Up @@ -319,6 +319,10 @@ private Object resolvePropertyToExample(String propertyName, String mediaType, S
return "";
}

private Double getPropertyValue(BigDecimal propertyValue) {
return propertyValue == null ? null : propertyValue.doubleValue();
}

private double randomNumber(Double min, Double max) {
if (min != null && max != null) {
double range = max - min;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand All @@ -38,6 +39,8 @@
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);

protected final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);

private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public ScalaLagomServerCodegen() {
importMapping.put("DateTime", "org.joda.time.DateTime");
importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer");

typeMapping = new HashMap<String, String>();
typeMapping = new HashMap<>();
typeMapping.put("Integer", "Int");
typeMapping.put("enum", "NSString");
typeMapping.put("array", "Seq");
Expand All @@ -91,7 +91,6 @@ public ScalaLagomServerCodegen() {
typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short");
typeMapping.put("char", "Char");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "File");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@
public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class);

private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.*;

public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);

public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.Map;

public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);

public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@
import static org.openapitools.codegen.utils.StringUtils.camelize;

public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";

public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@

public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptJqueryClientCodegen.class);
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);

public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);

public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.Map;

public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);

public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
public class DefaultCodegenTest {

@Test
public void testHasBodyParameter() throws Exception {
public void testHasBodyParameter() {
final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet");
Operation pingOperation = new Operation()
.responses(
Expand All @@ -61,6 +61,13 @@ public void testHasBodyParameter() throws Exception {
Assert.assertEquals(codegen.hasBodyParameter(openAPI, createOperation), true);
}

@Test(expectedExceptions = RuntimeException.class)
public void testParameterEmptyDescription() {
DefaultCodegen codegen = new DefaultCodegen();

codegen.fromRequestBody(null, new HashSet<>(), null);
}

@Test
public void testGetConsumesInfoAndGetProducesInfo() throws Exception {
final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.openapitools.codegen;

import org.testng.Assert;
import org.testng.annotations.Test;

public class SpecValidationExceptionTest {

@Test
public void shouldGetDefaultMessage() {
SpecValidationException specValidationException = new SpecValidationException();

String expectedResult = new StringBuffer("null | Error count: 0, Warning count: 0")
.append(System.lineSeparator()).append("Errors: ")
.append(System.lineSeparator()).toString();

Assert.assertEquals(specValidationException.getMessage(), expectedResult);
}
}