Search in sources :

Example 16 with DefaultPrettyPrinter

use of com.fasterxml.jackson.core.util.DefaultPrettyPrinter in project swagger-core by swagger-api.

the class SwaggerMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().info("Skipping OpenAPI specification resolution");
        return;
    }
    getLog().info("Resolving OpenAPI specification..");
    if (project != null) {
        String pEnc = project.getProperties().getProperty("project.build.sourceEncoding");
        if (StringUtils.isNotBlank(pEnc)) {
            projectEncoding = pEnc;
        }
    }
    if (StringUtils.isBlank(encoding)) {
        encoding = projectEncoding;
    }
    // read swagger configuration if one was provided
    Optional<SwaggerConfiguration> swaggerConfiguration = readStructuredDataFromFile(configurationFilePath, SwaggerConfiguration.class, "configurationFilePath");
    // read openApi config, if one was provided
    Optional<OpenAPI> openAPIInput = readStructuredDataFromFile(openapiFilePath, OpenAPI.class, "openapiFilePath");
    config = mergeConfig(openAPIInput.orElse(null), swaggerConfiguration.orElse(new SwaggerConfiguration()));
    setDefaultsIfMissing(config);
    try {
        GenericOpenApiContextBuilder builder = new JaxrsOpenApiContextBuilder().openApiConfiguration(config);
        if (StringUtils.isNotBlank(contextId)) {
            builder.ctxId(contextId);
        }
        OpenApiContext context = builder.buildContext(true);
        OpenAPI openAPI = context.read();
        if (StringUtils.isNotBlank(config.getFilterClass())) {
            try {
                OpenAPISpecFilter filterImpl = (OpenAPISpecFilter) this.getClass().getClassLoader().loadClass(config.getFilterClass()).newInstance();
                SpecFilter f = new SpecFilter();
                openAPI = f.filter(openAPI, filterImpl, new HashMap<>(), new HashMap<>(), new HashMap<>());
            } catch (Exception e) {
                getLog().error("Error applying filter to API specification", e);
                throw new MojoExecutionException("Error applying filter to API specification: " + e.getMessage(), e);
            }
        }
        String openapiJson = null;
        String openapiYaml = null;
        if (Format.JSON.equals(outputFormat) || Format.JSONANDYAML.equals(outputFormat)) {
            if (config.isPrettyPrint() != null && config.isPrettyPrint()) {
                openapiJson = context.getOutputJsonMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiJson = context.getOutputJsonMapper().writeValueAsString(openAPI);
            }
        }
        if (Format.YAML.equals(outputFormat) || Format.JSONANDYAML.equals(outputFormat)) {
            if (config.isPrettyPrint() != null && config.isPrettyPrint()) {
                openapiYaml = context.getOutputYamlMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiYaml = context.getOutputYamlMapper().writeValueAsString(openAPI);
            }
        }
        Path path = Paths.get(outputPath, "temp");
        final File parentFile = path.toFile().getParentFile();
        if (parentFile != null) {
            parentFile.mkdirs();
        }
        if (openapiJson != null) {
            path = Paths.get(outputPath, outputFileName + ".json");
            Files.write(path, openapiJson.getBytes(Charset.forName(encoding)));
            getLog().info("JSON output: " + path.toFile().getCanonicalPath());
        }
        if (openapiYaml != null) {
            path = Paths.get(outputPath, outputFileName + ".yaml");
            Files.write(path, openapiYaml.getBytes(Charset.forName(encoding)));
            getLog().info("YAML output: " + path.toFile().getCanonicalPath());
        }
    } catch (OpenApiConfigurationException e) {
        getLog().error("Error resolving API specification", e);
        throw new MojoFailureException(e.getMessage(), e);
    } catch (IOException e) {
        getLog().error("Error writing API specification", e);
        throw new MojoExecutionException("Failed to write API definition", e);
    } catch (Exception e) {
        getLog().error("Error resolving API specification", e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) Path(java.nio.file.Path) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) GenericOpenApiContextBuilder(io.swagger.v3.oas.integration.GenericOpenApiContextBuilder) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) JaxrsOpenApiContextBuilder(io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder) OpenAPI(io.swagger.v3.oas.models.OpenAPI) File(java.io.File) SpecFilter(io.swagger.v3.core.filter.SpecFilter) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext)

Example 17 with DefaultPrettyPrinter

use of com.fasterxml.jackson.core.util.DefaultPrettyPrinter in project swagger-core by swagger-api.

the class SwaggerLoader method resolve.

public Map<String, String> resolve() throws Exception {
    Set<String> ignoredRoutesSet = null;
    if (StringUtils.isNotBlank(ignoredRoutes)) {
        ignoredRoutesSet = new HashSet<>(Arrays.asList(ignoredRoutes.split(",")));
    }
    Set<String> resourceClassesSet = null;
    if (StringUtils.isNotBlank(resourceClasses)) {
        resourceClassesSet = new HashSet<>(Arrays.asList(resourceClasses.split(",")));
    }
    Set<String> resourcePackagesSet = null;
    if (StringUtils.isNotBlank(resourcePackages)) {
        resourcePackagesSet = new HashSet<>(Arrays.asList(resourcePackages.split(",")));
    }
    LinkedHashSet<String> modelConverterSet = null;
    if (StringUtils.isNotBlank(modelConverterClasses)) {
        modelConverterSet = new LinkedHashSet<>(Arrays.asList(modelConverterClasses.split(",")));
    }
    OpenAPI openAPIInput = null;
    if (StringUtils.isNotBlank(openapiAsString)) {
        try {
            openAPIInput = Json.mapper().readValue(openapiAsString, OpenAPI.class);
        } catch (Exception e) {
            try {
                openAPIInput = Yaml.mapper().readValue(openapiAsString, OpenAPI.class);
            } catch (Exception e1) {
                throw new Exception("Error reading/deserializing openapi input: " + e.getMessage(), e);
            }
        }
    }
    SwaggerConfiguration config = new SwaggerConfiguration().filterClass(filterClass).ignoredRoutes(ignoredRoutesSet).prettyPrint(prettyPrint).readAllResources(readAllResources).openAPI(openAPIInput).readerClass(readerClass).scannerClass(scannerClass).resourceClasses(resourceClassesSet).resourcePackages(resourcePackagesSet).objectMapperProcessorClass(objectMapperProcessorClass).modelConverterClasses(modelConverterSet).sortOutput(sortOutput).alwaysResolveAppPath(alwaysResolveAppPath);
    try {
        GenericOpenApiContextBuilder builder = new JaxrsOpenApiContextBuilder().openApiConfiguration(config);
        if (StringUtils.isNotBlank(contextId)) {
            builder.ctxId(contextId);
        }
        OpenApiContext context = builder.buildContext(true);
        OpenAPI openAPI = context.read();
        if (StringUtils.isNotBlank(filterClass)) {
            try {
                OpenAPISpecFilter filterImpl = (OpenAPISpecFilter) this.getClass().getClassLoader().loadClass(filterClass).newInstance();
                SpecFilter f = new SpecFilter();
                openAPI = f.filter(openAPI, filterImpl, new HashMap<>(), new HashMap<>(), new HashMap<>());
            } catch (Exception e) {
                throw new Exception("Error applying filter to API specification: " + e.getMessage(), e);
            }
        }
        String openapiJson = null;
        String openapiYaml = null;
        if ("JSON".equals(outputFormat) || "JSONANDYAML".equals(outputFormat)) {
            if (prettyPrint != null && prettyPrint) {
                openapiJson = context.getOutputJsonMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiJson = context.getOutputJsonMapper().writeValueAsString(openAPI);
            }
        }
        if ("YAML".equals(outputFormat) || "JSONANDYAML".equals(outputFormat)) {
            if (prettyPrint != null && prettyPrint) {
                openapiYaml = context.getOutputYamlMapper().writer(new DefaultPrettyPrinter()).writeValueAsString(openAPI);
            } else {
                openapiYaml = context.getOutputYamlMapper().writeValueAsString(openAPI);
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("JSON", openapiJson);
        map.put("YAML", openapiYaml);
        return map;
    } catch (OpenApiConfigurationException e) {
        throw new Exception("Error resolving API specification: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new Exception("Error resolving API specification: " + e.getMessage(), e);
    }
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) HashMap(java.util.HashMap) GenericOpenApiContextBuilder(io.swagger.v3.oas.integration.GenericOpenApiContextBuilder) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) OpenApiConfigurationException(io.swagger.v3.oas.integration.OpenApiConfigurationException) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SpecFilter(io.swagger.v3.core.filter.SpecFilter) OpenAPISpecFilter(io.swagger.v3.core.filter.OpenAPISpecFilter) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext)

Example 18 with DefaultPrettyPrinter

use of com.fasterxml.jackson.core.util.DefaultPrettyPrinter in project CzechIdMng by bcvsolutions.

the class AbstractReleaseManager method getPrettyPrinter.

/**
 * IdM configured json {@link PrettyPrinter} - the same format as npm is needed.
 *
 * @return configured printer
 * @since 10.3.0
 */
protected PrettyPrinter getPrettyPrinter() {
    if (prettyPrinter == null) {
        // 
        // Prevent to append leading value space.
        DefaultPrettyPrinter defaultPrettyPrinter = new DefaultPrettyPrinter() {

            private static final long serialVersionUID = 1L;

            /**
             * Prevent to append leading value space.
             */
            @Override
            public DefaultPrettyPrinter withSeparators(Separators separators) {
                _separators = separators;
                _objectFieldValueSeparatorWithSpaces = separators.getObjectFieldValueSeparator() + " ";
                return this;
            }
        };
        // 
        // array value on new line
        defaultPrettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
        // 
        prettyPrinter = defaultPrettyPrinter;
    }
    // 
    return prettyPrinter;
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) Separators(com.fasterxml.jackson.core.util.Separators)

Example 19 with DefaultPrettyPrinter

use of com.fasterxml.jackson.core.util.DefaultPrettyPrinter in project ambry by linkedin.

the class ServiceIdAccountGenTool method generateAccounts.

/**
 * Generate a list of accounts for the provided service IDs and output them as a JSON array to the provided file path.
 * @param serviceIds the list of service IDs to create accounts for.
 * @param outputFile the file path to write the account JSON array to.
 * @param startingAccountId the account ID to assign to the first account generated. This will be incremented by one
 *                          for each additional account.
 * @throws JSONException
 * @throws IOException
 */
private static void generateAccounts(List<String> serviceIds, String outputFile, short startingAccountId) throws JSONException, IOException {
    Collection<Account> accounts = new ArrayList<>();
    short curAccountId = startingAccountId;
    for (String serviceId : serviceIds) {
        Container defaultPublicContainer = new ContainerBuilder(Container.DEFAULT_PUBLIC_CONTAINER).setParentAccountId(curAccountId).build();
        Container defaultPrivateContainer = new ContainerBuilder(Container.DEFAULT_PRIVATE_CONTAINER).setParentAccountId(curAccountId).build();
        Account account = new AccountBuilder(curAccountId, serviceId, Account.AccountStatus.ACTIVE).containers(Arrays.asList(defaultPublicContainer, defaultPrivateContainer)).build();
        accounts.add(account);
        curAccountId++;
    }
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) {
        new ObjectMapper().writer(new DefaultPrettyPrinter()).writeValue(writer, accounts);
    }
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) ArrayList(java.util.ArrayList) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) BufferedWriter(java.io.BufferedWriter)

Example 20 with DefaultPrettyPrinter

use of com.fasterxml.jackson.core.util.DefaultPrettyPrinter in project ambry by linkedin.

the class AccountContainerTest method testAccountAndContainerSerDe.

@Test
public void testAccountAndContainerSerDe() throws IOException {
    assumeTrue(Container.getCurrentJsonVersion() == JSON_VERSION_2);
    // Make sure the JSONObject string can be deserialized to jackson object
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try (Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
        refAccountJson.write(writer);
    }
    Account deserialized = objectMapper.readValue(outputStream.toByteArray(), Account.class);
    Account fromJson = accountFromJson(refAccountJson);
    assertTrue(deserialized.equals(fromJson));
    // Make sure jackson string can be deserialized to JSONObject object
    String serialized = objectMapper.writer(new DefaultPrettyPrinter()).writeValueAsString(deserialized);
    JSONObject jsonObject = new JSONObject(serialized);
    fromJson = accountFromJson(jsonObject);
    assertTrue(deserialized.equals(fromJson));
    @JsonIgnoreProperties({ "containers" })
    abstract class AccountMixIn {
    }
    ObjectMapper newObjectMapper = new ObjectMapper();
    newObjectMapper.addMixIn(Account.class, AccountMixIn.class);
    serialized = newObjectMapper.writeValueAsString(deserialized);
    assertFalse(serialized.contains("containers"));
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) Account(com.github.ambry.account.Account) JSONObject(org.json.JSONObject) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) Test(org.junit.Test)

Aggregations

DefaultPrettyPrinter (com.fasterxml.jackson.core.util.DefaultPrettyPrinter)42 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)10 IOException (java.io.IOException)9 File (java.io.File)7 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)6 DefaultIndenter (com.fasterxml.jackson.core.util.DefaultIndenter)6 OpenApiContext (io.swagger.v3.oas.integration.api.OpenApiContext)6 OpenAPI (io.swagger.v3.oas.models.OpenAPI)6 SwaggerConfiguration (io.swagger.v3.oas.integration.SwaggerConfiguration)4 PrettyPrinter (com.fasterxml.jackson.core.PrettyPrinter)3 JsonFactory (com.fasterxml.jackson.core.json.JsonFactory)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)3 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)3 OpenAPISpecFilter (io.swagger.v3.core.filter.OpenAPISpecFilter)3 SpecFilter (io.swagger.v3.core.filter.SpecFilter)3 OpenApiConfigurationException (io.swagger.v3.oas.integration.OpenApiConfigurationException)3 BufferedWriter (java.io.BufferedWriter)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3