Search in sources :

Example 61 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method getScopes.

@Override
public Map<String, Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(resourceConfigsJSON);
    if (swagger.getVendorExtensions() != null) {
        String basePath = swagger.getBasePath();
        String nameSpace = getNamespaceFromBasePath(basePath);
        if (nameSpace == null) {
            return new HashMap<>();
        }
        String securityHeaderScopes = null;
        // read security header from deployment.yaml
        if (localConfigMap.containsKey(nameSpace)) {
            if (localConfigMap.get(nameSpace).containsKey(APIMgtConstants.SWAGGER_X_WSO2_SCOPES)) {
                securityHeaderScopes = localConfigMap.get(nameSpace).get(APIMgtConstants.SWAGGER_X_WSO2_SCOPES).toString();
            }
        } else {
            // rest api resource to scope mapping configurations have not been loaded.hence, populating
            populateConfigMapForScopes(swagger, nameSpace);
        }
        if (securityHeaderScopes == null || StringUtils.isEmpty(securityHeaderScopes)) {
            // security header is not found in deployment.yaml.hence, reading from swagger
            securityHeaderScopes = new Gson().toJson(swagger.getVendorExtensions().get(APIMgtConstants.SWAGGER_X_WSO2_SECURITY));
            localConfigMap.get(nameSpace).put(APIMgtConstants.SWAGGER_X_WSO2_SCOPES, securityHeaderScopes);
        }
        try {
            JSONObject scopesJson = (JSONObject) new JSONParser().parse(securityHeaderScopes);
            return extractScopesFromJson(scopesJson);
        } catch (ParseException e) {
            String msg = "invalid json : " + securityHeaderScopes;
            log.error(msg, e);
            throw new APIManagementException(msg, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("vendor extensions are not found in provided swagger json. resourceConfigsJSON = " + resourceConfigsJSON);
        }
        return new HashMap<>();
    }
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Swagger(io.swagger.models.Swagger) Gson(com.google.gson.Gson) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 62 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class APIPublisherImpl method updateDocumentation.

/**
 * Updates a given documentation
 *
 * @param apiId        UUID of the API.
 * @param documentInfo Documentation
 * @return UUID of the updated document.
 * @throws APIManagementException if failed to update docs
 */
@Override
public String updateDocumentation(String apiId, DocumentInfo documentInfo) throws APIManagementException {
    try {
        LocalDateTime localDateTime = LocalDateTime.now();
        DocumentInfo document;
        DocumentInfo.Builder docBuilder = new DocumentInfo.Builder(documentInfo);
        docBuilder.updatedBy(getUsername());
        docBuilder.lastUpdatedTime(localDateTime);
        if (StringUtils.isEmpty(docBuilder.getId())) {
            docBuilder = docBuilder.id(UUID.randomUUID().toString());
        }
        if (documentInfo.getPermission() != null && !("").equals(documentInfo.getPermission())) {
            HashMap roleNamePermissionList;
            roleNamePermissionList = APIUtils.getAPIPermissionArray(documentInfo.getPermission());
            docBuilder.permissionMap(roleNamePermissionList);
        }
        document = docBuilder.build();
        if (getApiDAO().isDocumentExist(apiId, document)) {
            getApiDAO().updateDocumentInfo(apiId, document, getUsername());
            return document.getId();
        } else {
            String msg = "Document " + document.getName() + " not found for the api " + apiId;
            log.error(msg);
            throw new APIManagementException(msg, ExceptionCodes.DOCUMENT_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Unable to update the documentation";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Unable to update the documentation due to json parse error";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.JSON_PARSE_ERROR);
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ParseException(org.json.simple.parser.ParseException) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 63 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class APIPublisherImpl method getAPIbyUUID.

@Override
public API getAPIbyUUID(String uuid) throws APIManagementException {
    API api = null;
    try {
        api = super.getAPIbyUUID(uuid);
        if (api != null) {
            api.setUserSpecificApiPermissions(getAPIPermissionsOfLoggedInUser(getUsername(), api));
            String permissionString = api.getApiPermission();
            if (!StringUtils.isEmpty(permissionString)) {
                api.setApiPermission(replaceGroupIdWithName(permissionString));
            }
            if (!getScopesForApi(uuid).isEmpty()) {
                String swagger = getApiSwaggerDefinition(uuid);
                List<String> globalScopes = new APIDefinitionFromSwagger20().getGlobalAssignedScopes(swagger);
                List<APIResource> apiResourceList = new APIDefinitionFromSwagger20().parseSwaggerAPIResources(new StringBuilder(swagger));
                api.setScopes(globalScopes);
                for (APIResource apiResource : apiResourceList) {
                    if (apiResource.getUriTemplate().getScopes().isEmpty()) {
                        UriTemplate retrievedUriTemplateFromApi = api.getUriTemplates().get(apiResource.getUriTemplate().getTemplateId());
                        if (retrievedUriTemplateFromApi != null) {
                            UriTemplate.UriTemplateBuilder uriTemplate = new UriTemplate.UriTemplateBuilder(retrievedUriTemplateFromApi);
                            uriTemplate.scopes(apiResource.getScope());
                            api.getUriTemplates().replace(apiResource.getUriTemplate().getTemplateId(), uriTemplate.build());
                        }
                    }
                }
            }
        }
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json string for API " + api.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.JSON_PARSE_ERROR);
    }
    return api;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIResource(org.wso2.carbon.apimgt.core.models.APIResource) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate)

Example 64 with ParseException

use of org.json.simple.parser.ParseException in project acidisland by tastybento.

the class IslandBlock method setSign.

/**
 * Sets this block's sign data
 * @param tileData
 */
public void setSign(Map<String, Tag> tileData) {
    signText = new ArrayList<String>();
    List<String> text = new ArrayList<String>();
    for (int i = 1; i < 5; i++) {
        String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue();
        // This value can actually be a string that says null sometimes.
        if (line.equalsIgnoreCase("null")) {
            line = "";
        }
        // System.out.println("DEBUG: line " + i + " = '"+ line + "' of length " + line.length());
        text.add(line);
    }
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {

        public List creatArrayContainer() {
            return new LinkedList();
        }

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }
    };
    // This just removes all the JSON formatting and provides the raw text
    for (int line = 0; line < 4; line++) {
        String lineText = "";
        if (!text.get(line).equals("\"\"") && !text.get(line).isEmpty()) {
            // Bukkit.getLogger().info("DEBUG: sign text = '" + text.get(line) + "'");
            if (text.get(line).startsWith("{")) {
                // JSON string
                try {
                    Map json = (Map) parser.parse(text.get(line), containerFactory);
                    List list = (List) json.get("extra");
                    // System.out.println("DEBUG1:" + JSONValue.toJSONString(list));
                    if (list != null) {
                        Iterator iter = list.iterator();
                        while (iter.hasNext()) {
                            Object next = iter.next();
                            String format = JSONValue.toJSONString(next);
                            // This doesn't see right, but appears to be the easiest way to identify this string as JSON...
                            if (format.startsWith("{")) {
                                // JSON string
                                Map jsonFormat = (Map) parser.parse(format, containerFactory);
                                Iterator formatIter = jsonFormat.entrySet().iterator();
                                while (formatIter.hasNext()) {
                                    Map.Entry entry = (Map.Entry) formatIter.next();
                                    // System.out.println("DEBUG3:" + entry.getKey() + "=>" + entry.getValue());
                                    String key = entry.getKey().toString();
                                    String value = entry.getValue().toString();
                                    if (key.equalsIgnoreCase("color")) {
                                        try {
                                            lineText += ChatColor.valueOf(value.toUpperCase());
                                        } catch (Exception noColor) {
                                            Bukkit.getLogger().warning("Unknown color " + value + " in sign when pasting schematic, skipping...");
                                        }
                                    } else if (key.equalsIgnoreCase("text")) {
                                        lineText += value;
                                    } else {
                                        // Formatting - usually the value is always true, but check just in case
                                        if (key.equalsIgnoreCase("obfuscated") && value.equalsIgnoreCase("true")) {
                                            lineText += ChatColor.MAGIC;
                                        } else if (key.equalsIgnoreCase("underlined") && value.equalsIgnoreCase("true")) {
                                            lineText += ChatColor.UNDERLINE;
                                        } else {
                                            // The rest of the formats
                                            try {
                                                lineText += ChatColor.valueOf(key.toUpperCase());
                                            } catch (Exception noFormat) {
                                                // Ignore
                                                // System.out.println("DEBUG3:" + key + "=>" + value);
                                                Bukkit.getLogger().warning("Unknown format " + value + " in sign when pasting schematic, skipping...");
                                            }
                                        }
                                    }
                                }
                            } else {
                                // any previous formatting
                                if (format.length() > 1) {
                                    lineText += ChatColor.RESET + format.substring(format.indexOf('"') + 1, format.lastIndexOf('"'));
                                }
                            }
                        }
                    } else {
                        // No extra tag
                        json = (Map) parser.parse(text.get(line), containerFactory);
                        String value = (String) json.get("text");
                        // System.out.println("DEBUG text only?:" + value);
                        lineText += value;
                    }
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                // This is unformatted text (not JSON). It is included in "".
                if (text.get(line).length() > 1) {
                    try {
                        lineText = text.get(line).substring(text.get(line).indexOf('"') + 1, text.get(line).lastIndexOf('"'));
                    } catch (Exception e) {
                        // There may not be those "'s, so just use the raw line
                        lineText = text.get(line);
                    }
                } else {
                    // just in case it isn't - show the raw line
                    lineText = text.get(line);
                }
            }
        // Bukkit.getLogger().info("Line " + line + " is " + lineText);
        }
        signText.add(lineText);
    }
}
Also used : StringTag(com.wasteofplastic.org.jnbt.StringTag) Entry(java.util.Map.Entry) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ParseException(org.json.simple.parser.ParseException) LinkedHashMap(java.util.LinkedHashMap) Entry(java.util.Map.Entry) Iterator(java.util.Iterator) ContainerFactory(org.json.simple.parser.ContainerFactory) JSONParser(org.json.simple.parser.JSONParser) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ParseException(org.json.simple.parser.ParseException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

ParseException (org.json.simple.parser.ParseException)64 JSONObject (org.json.simple.JSONObject)41 JSONParser (org.json.simple.parser.JSONParser)39 HashMap (java.util.HashMap)18 JSONArray (org.json.simple.JSONArray)18 IOException (java.io.IOException)16 ArrayList (java.util.ArrayList)10 Map (java.util.Map)10 List (java.util.List)7 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)7 InputStreamReader (java.io.InputStreamReader)6 File (java.io.File)5 MapLayer (au.org.emii.portal.menu.MapLayer)4 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)4 MapLayerMetadata (au.org.emii.portal.menu.MapLayerMetadata)3 BufferedReader (java.io.BufferedReader)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3 LocalDateTime (java.time.LocalDateTime)3