Java Code Examples for io.swagger.util.Json#pretty()

The following examples show how to use io.swagger.util.Json#pretty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 6 votes vote down vote up
public ResponseContext reviewByContent(RequestContext request, JsonNode inputSpec) {
    if(inputSpec == null) {
        return new ResponseContext()
                .status(Response.Status.BAD_REQUEST)
                .entity( "No specification supplied in either the url or request body.  Try again?" );
    }
    String inputAsString = Json.pretty(inputSpec);

    ValidationResponse validationResponse = null;
    try {
        validationResponse = debugByContent(request ,inputAsString);
    }catch (Exception e){
        return new ResponseContext().status(Response.Status.INTERNAL_SERVER_ERROR).entity( "Failed to process specification" );
    }

    return new ResponseContext()
            .entity(validationResponse);
    //return processDebugValidationResponse(validationResponse);
}
 
Example 2
Source File: ValidatorController.java    From validator-badge with Apache License 2.0 6 votes vote down vote up
public ResponseContext validateByContent(RequestContext request, JsonNode inputSpec) {
    if(inputSpec == null) {
        return new ResponseContext()
                .status(Response.Status.BAD_REQUEST)
                .entity( "No specification supplied in either the url or request body.  Try again?" );
    }
    String inputAsString = Json.pretty(inputSpec);

    ValidationResponse validationResponse = null;
    try {
        validationResponse = debugByContent(request ,inputAsString);
    }catch (Exception e){
        return new ResponseContext().status(Response.Status.INTERNAL_SERVER_ERROR).entity( "Failed to process URL" );
    }

    return processValidationResponse(validationResponse);
}
 
Example 3
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the v2 or v3 open API definition in yaml or json format into json format of the respective format.
 * v2/YAML -> v2/JSON
 * v3/YAML -> v3/JSON
 *
 * @param openAPIContent open API as a string content
 * @return openAPI definition as a JSON String
 */
public static String getOpenAPIAsJson(OpenAPI openAPI, String openAPIContent, Path openAPIPath) {
    String jsonOpenAPI = Json.pretty(openAPI);
    String openAPIVersion;
    Path fileName = openAPIPath.getFileName();

    if (fileName == null) {
        throw new CLIRuntimeException("Error: Couldn't resolve OpenAPI file name.");
    } else if (fileName.toString().endsWith("json")) {
        openAPIVersion = findSwaggerVersion(openAPIContent, false);
    } else {
        openAPIVersion = findSwaggerVersion(jsonOpenAPI, false);
    }

    switch (openAPIVersion) {
        case "2":
            Swagger swagger = new SwaggerParser().parse(openAPIContent);
            return Json.pretty(swagger);
        case "3":
            return jsonOpenAPI;

        default:
            throw new CLIRuntimeException("Error: Swagger version is not identified");
    }
}
 
Example 4
Source File: JavaVertXServerGenerator.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    super.preprocessSwagger(swagger);

    // add full swagger definition in a mustache parameter
    String swaggerDef = Json.pretty(swagger);
    this.additionalProperties.put("fullSwagger", swaggerDef);

    // add server port from the swagger file, 8080 by default
    String host = swagger.getHost();
    String port = extractPortFromHost(host);
    this.additionalProperties.put("serverPort", port);

    // retrieve api version from swagger file, 1.0.0-SNAPSHOT by default
    if (swagger.getInfo() != null && swagger.getInfo().getVersion() != null)
        artifactVersion = apiVersion = swagger.getInfo().getVersion();
    else
        artifactVersion = apiVersion;

    // manage operation & custom serviceId
    Map<String, Path> paths = swagger.getPaths();
    if (paths != null) {
        for (Entry<String, Path> entry : paths.entrySet()) {
            manageOperationNames(entry.getValue(), entry.getKey());
        }
    }
}
 
Example 5
Source File: SwaggerToOpenApiConversionFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException {
    if (Boolean.TRUE == reqCtx.getProperty(OPEN_API_PROPERTY)) {
        final Object entity = respCtx.getEntity();
        // Right before 1.5.18, the entity was always a String but became a model object
        // (io.swagger.models.Swagger) after. For now, let us serialize it to JSON manually.
        String swaggerJson = entity instanceof String ? (String)entity : Json.pretty(entity);
        String openApiJson = SwaggerToOpenApiConversionUtils.getOpenApiFromSwaggerJson(
                createMessageContext(), swaggerJson, openApiConfig);
        respCtx.setEntity(openApiJson);
    }
}
 
Example 6
Source File: SequenceGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void populateParametersFromOperation(Operation operation, Map<String, Model> definitions,
        Map<String, String> parameterJsonPathMapping, Map<String, String> queryParameters) {

    List<Parameter> parameters = operation.getParameters();
    for (Parameter parameter : parameters) {
        String name = parameter.getName();
        if (parameter instanceof BodyParameter) {
            Model schema = ((BodyParameter) parameter).getSchema();
            if (schema instanceof RefModel) {
                String $ref = ((RefModel) schema).get$ref();
                if (StringUtils.isNotBlank($ref)) {
                    String defName = $ref.substring("#/definitions/".length());
                    Model model = definitions.get(defName);
                    Example example = ExampleBuilder.fromModel(defName, model, definitions, new HashSet<String>());

                    String jsonExample = Json.pretty(example);
                    try {
                        org.json.JSONObject json = new org.json.JSONObject(jsonExample);
                        SequenceUtils.listJson(json, parameterJsonPathMapping);
                    } catch (JSONException e) {
                        log.error("Error occurred while generating json mapping for the definition: " + defName, e);
                    }
                }
            }
        }
        if (parameter instanceof QueryParameter) {
            String type = ((QueryParameter) parameter).getType();
            queryParameters.put(name, type);
        }
    }
}
 
Example 7
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public String getOASDefinitionWithTierContentAwareProperty(String oasDefinition,
        List<String> contentAwareTiersList, String apiLevelTier) throws APIManagementException {
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    Swagger swagger = parseAttemptForV2.getSwagger();
    // check if API Level tier is content aware. if so, we set a extension as a global property
    if (contentAwareTiersList.contains(apiLevelTier)) {
        swagger.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
        // no need to check resource levels since both cannot exist at the same time.
        log.debug("API Level policy is content aware..");
        return Json.pretty(swagger);
    }
    // if api level tier exists, skip checking for resource level tiers since both cannot exist at the same time.
    if (apiLevelTier != null) {
        log.debug("API Level policy is not content aware..");
        return oasDefinition;
    } else {
        log.debug("API Level policy does not exist. Checking for resource level");
        for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
            String path = entry.getKey();
            List<Operation> operations = swagger.getPaths().get(path).getOperations();
            for (Operation op : operations) {
                if (contentAwareTiersList
                        .contains(op.getVendorExtensions().get(APIConstants.SWAGGER_X_THROTTLING_TIER))) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "API resource Level policy is content aware for operation " + op.getOperationId());
                    }
                    op.setVendorExtension(APIConstants.SWAGGER_X_THROTTLING_BANDWIDTH, true);
                }
            }
        }
        return Json.pretty(swagger);
    }

}
 
Example 8
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method  generates Sample/Mock payloads of Schema Examples for operations in the swagger definition
 * @param model model
 * @param definitions definitions
 * @return Example Json
 */
private String getSchemaExample(Model model, Map<String, Model> definitions, HashSet<String> strings) {
    Example example = ExampleBuilder.fromModel("Model", model, definitions, new HashSet<String>());
    SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
    Json.mapper().registerModule(simpleModule);
    return Json.pretty(example);
}
 
Example 9
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private String getTypeDeclarationFromComposedSchema(
        ComposedSchema composedSchema, String optionalSuffix) {
    if (composedSchema.getAllOf() != null
            && composedSchema.getAllOf().size() == 1) {
        return getTypeDeclaration(composedSchema.getAllOf().get(0))
                + optionalSuffix;
    } else {
        String unknownComposedSchema = Json.pretty(composedSchema);
        getLogger().debug("Unknown ComposedSchema: {}",
                unknownComposedSchema);
        return "any";
    }
}
 
Example 10
Source File: ArgWrapperJavaType.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] _args) throws IOException {
  Map<String, Object> map = new HashMap<>();
  map.put("date", new Date());
  map.put("num", 1L);

  ArgWrapperJavaType argWrapperJavaType = new ArgWrapperJavaType();
  argWrapperJavaType.addProperty("date", Date.class);
  argWrapperJavaType.addProperty("num", Long.class);

  String json = Json.pretty(map);

  Map<String, Object> args = argWrapperJavaType.readValue(Json.mapper(), json);
  System.out.println(args);
}
 
Example 11
Source File: InlineModelResolver.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
public String matchGenerated(Model model) {
    if (this.skipMatches) {
        return null;
    }
    String json = Json.pretty(model);
    if (generatedSignature.containsKey(json)) {
        return generatedSignature.get(json);
    }
    return null;
}
 
Example 12
Source File: SwaggerGenerator.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void processSwagger(Swagger swagger) {
    String swaggerString = Json.pretty(swagger);

    try {
        String outputFile = outputFolder + File.separator + "swagger.json";
        FileUtils.writeStringToFile(new File(outputFile), swaggerString);
        LOGGER.debug("wrote file to " + outputFile);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example 13
Source File: JavaJAXRSSpecServerCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    //copy input swagger to output folder
    try {
        String swaggerJson = Json.pretty(swagger);
        FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e.getCause());
    }
    super.preprocessSwagger(swagger);

}
 
Example 14
Source File: JavaVertXServerCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    super.preprocessSwagger(swagger);

    // add full swagger definition in a mustache parameter
    String swaggerDef = Json.pretty(swagger);
    this.additionalProperties.put("fullSwagger", swaggerDef);

    // add server port from the swagger file, 8080 by default
    String host = swagger.getHost();
    String port = extractPortFromHost(host);
    this.additionalProperties.put("serverPort", port);

    // retrieve api version from swagger file, 1.0.0-SNAPSHOT by default
    if (swagger.getInfo() != null && swagger.getInfo().getVersion() != null) {
        artifactVersion = apiVersion = swagger.getInfo().getVersion();
    } else {
        artifactVersion = apiVersion;
    }

    /*
     * manage operation & custom serviceId because operationId field is not
     * required and may be empty
     */
    Map<String, Path> paths = swagger.getPaths();
    if (paths != null) {
        for (Entry<String, Path> entry : paths.entrySet()) {
            manageOperationNames(entry.getValue(), entry.getKey());
        }
    }
    this.additionalProperties.remove("gson");
}
 
Example 15
Source File: UpdateManager.java    From cellery-distribution with Apache License 2.0 5 votes vote down vote up
/**
 * Creates Swagger file for the API given by controller
 *
 * @param api API sent by controller
 */
private static void createSwagger(API api) {
    Swagger swagger = new Swagger();
    swagger.setInfo(createSwaggerInfo(api));
    swagger.basePath("/" + api.getContext());
    swagger.setPaths(createAPIResources(api));
    String swaggerString = Json.pretty(swagger);
    writeSwagger(swaggerString, removeSpecialChars(api.getBackend() + api.getContext()));
}
 
Example 16
Source File: SwaggerUtils.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Create a swagger definition from data-service resource details.
 *
 * @param axisResourceMap AxisResourceMap containing resource details.
 * @param dataServiceName Name of the data service.
 * @param transports      Transports supported from the data-service.
 * @param serverConfig    Server config details.
 * @param isJSON          result format JSON or YAML.
 * @return Swagger definition as string.
 * @throws AxisFault Error occurred while fetching the host address.
 */
private static String createSwaggerFromDefinition(AxisResourceMap axisResourceMap, String dataServiceName,
                                                  List<String> transports, MIServerConfig serverConfig,
                                                  boolean isJSON)
        throws AxisFault {

    Swagger swaggerDoc = new Swagger();
    addSwaggerInfoSection(dataServiceName, transports, serverConfig, swaggerDoc);

    Map<String, Path> paths = new HashMap<>();

    for (Map.Entry<String, AxisResource> entry : axisResourceMap.getResources().entrySet()) {
        Path path = new Path();
        for (String method : entry.getValue().getMethods()) {
            Operation operation = new Operation();
            List<AxisResourceParameter> parameterList = entry.getValue().getResourceParameterList(method);
            generatePathAndQueryParameters(method, operation, parameterList);
            // Adding a sample request payload for methods except GET.
            generateSampleRequestPayload(method, operation, parameterList);
            Response response = new Response();
            response.description("this is the default response");
            operation.addResponse("default", response);
            switch (method) {
                case "GET":
                    path.get(operation);
                    break;
                case "POST":
                    path.post(operation);
                    break;
                case "DELETE":
                    path.delete(operation);
                    break;
                case "PUT":
                    path.put(operation);
                    break;
                default:
                    throw new AxisFault("Invalid method \"" + method + "\" detected in the data-service");
            }
        }
        String contextPath = entry.getKey().startsWith("/") ? entry.getKey() : "/" + entry.getKey();
        paths.put(contextPath, path);
    }
    swaggerDoc.setPaths(paths);
    if (isJSON) return Json.pretty(swaggerDoc);
    try {
        return Yaml.pretty().writeValueAsString(swaggerDoc);
    } catch (JsonProcessingException e) {
        logger.error("Error occurred while creating the YAML configuration", e);
        return null;
    }
}
 
Example 17
Source File: DefaultCodegen.java    From TypeScript-Microservices with MIT License 4 votes vote down vote up
/**
 * Convert Swagger Response object to Codegen Response object
 *
 * @param responseCode HTTP response code
 * @param response Swagger Response object
 * @return Codegen Response object
 */
public CodegenResponse fromResponse(String responseCode, Response response) {
    CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE);
    if ("default".equals(responseCode)) {
        r.code = "0";
    } else {
        r.code = responseCode;
    }
    r.message = escapeText(response.getDescription());
    r.schema = response.getSchema();
    r.examples = toExamples(response.getExamples());
    r.jsonSchema = Json.pretty(response);
    r.vendorExtensions = response.getVendorExtensions();
    addHeaders(response, r.headers);
    r.hasHeaders = !r.headers.isEmpty();

    if (r.schema != null) {
        Property responseProperty = response.getSchema();
        responseProperty.setRequired(true);
        CodegenProperty cm = fromProperty("response", responseProperty);

        if (responseProperty instanceof ArrayProperty) {
            ArrayProperty ap = (ArrayProperty) responseProperty;
            CodegenProperty innerProperty = fromProperty("response", ap.getItems());
            r.baseType = innerProperty.baseType;
        } else {
            if (cm.complexType != null) {
                r.baseType = cm.complexType;
            } else {
                r.baseType = cm.baseType;
            }
        }
        r.dataType = cm.datatype;

        if (Boolean.TRUE.equals(cm.isString) && Boolean.TRUE.equals(cm.isUuid)) {
            r.isUuid = true;
        } else if (Boolean.TRUE.equals(cm.isByteArray)) {
            r.isByteArray = true;
        } else if (Boolean.TRUE.equals(cm.isString)) {
            r.isString = true;
        } else if (Boolean.TRUE.equals(cm.isBoolean)) {
            r.isBoolean = true;
        } else if (Boolean.TRUE.equals(cm.isLong)) {
            r.isLong = true;
            r.isNumeric = true;
        } else if (Boolean.TRUE.equals(cm.isInteger)) {
            r.isInteger = true;
            r.isNumeric = true;
        } else if (Boolean.TRUE.equals(cm.isNumber)) {
            r.isNumber = true;
            r.isNumeric = true;
        } else if (Boolean.TRUE.equals(cm.isDouble)) {
            r.isDouble = true;
            r.isNumeric = true;
        } else if (Boolean.TRUE.equals(cm.isFloat)) {
            r.isFloat = true;
            r.isNumeric = true;
        } else if (Boolean.TRUE.equals(cm.isBinary)) {
            r.isBinary = true;
        } else if (Boolean.TRUE.equals(cm.isFile)) {
            r.isFile = true;
        } else if (Boolean.TRUE.equals(cm.isDate)) {
            r.isDate = true;
        } else if (Boolean.TRUE.equals(cm.isDateTime)) {
            r.isDateTime = true;
        } else {
            LOGGER.debug("Property type is not primitive: " + cm.datatype);
        }

        if (cm.isContainer) {
            r.simpleType = false;
            r.containerType = cm.containerType;
            r.isMapContainer = "map".equals(cm.containerType);
            r.isListContainer = "list".equalsIgnoreCase(cm.containerType) || "array".equalsIgnoreCase(cm.containerType);
        } else {
            r.simpleType = true;
        }
        r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType));
    }
    if (r.baseType == null) {
        r.isMapContainer = false;
        r.isListContainer = false;
        r.primitiveType = true;
        r.simpleType = true;
    }
    return r;
}
 
Example 18
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method  generates Sample/Mock payloads for Swagger (2.0) definitions
 *
 * @param swaggerDef Swagger Definition
 * @return Swagger Json
 */
@Override
public Map<String, Object> generateExample(String swaggerDef) {
    // create APIResourceMediationPolicy List = policyList
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
    Swagger swagger = parseAttemptForV2.getSwagger();
    //return map
    Map<String, Object> returnMap = new HashMap<>();
    //List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
        int responseCode = 0;
        int minResponseCode = 0;
        String path = entry.getKey();
        //initializing apiResourceMediationPolicyObject
        APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
        //setting path for apiResourceMediationPolicyObject
        apiResourceMediationPolicyObject.setPath(path);
        Map<String, Model> definitions = swagger.getDefinitions();
        //operation map to get verb
        Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
        List<Operation> operations = swagger.getPaths().get(path).getOperations();
        for (Operation op : operations) {
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            //for each HTTP method get the verb
            for (Map.Entry<HttpMethod, Operation> HTTPMethodMap : operationMap.entrySet()) {
                //add verb to apiResourceMediationPolicyObject
                apiResourceMediationPolicyObject.setVerb(String.valueOf(HTTPMethodMap.getKey()));
            }
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            //for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                if (op.getResponses().get(responseEntry).getExamples() != null) {
                    Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
                    Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        String jsonExample = Json.pretty(applicationJson);
                        genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                        respCodeInitialized = true;
                        hasJsonPayload = true;
                    }
                    if (applicationXml != null) {
                        String xmlExample = applicationXml.toString();
                        genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                        hasXmlPayload = true;
                    }
                } else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
                    Model model = op.getResponses().get(responseEntry).getResponseSchema();
                    String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
                    genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
                    hasJsonPayload = true;
                } else if (op.getResponses().get(responseEntry).getExamples() == null
                        && op.getResponses().get(responseEntry).getResponseSchema() == null) {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            //inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            //gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
            //sets script to each resource in the swagger
            op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
        }
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}