Search in sources :

Example 86 with JSONObject

use of net.minidev.json.JSONObject in project identity-test-integration by wso2-incubator.

the class IDTokenDecrypterServlet method doPost.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idToken = request.getParameter("idToken");
    String privateKeyString = request.getParameter("privateKeyString");
    ServletOutputStream out = response.getOutputStream();
    if (StringUtils.isBlank(privateKeyString)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        out.print("Client private key cannot be empty!");
    } else if (StringUtils.isBlank(idToken)) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        out.print("Error occurred while decrypting: Empty id token received!");
    } else {
        response.setContentType("application/json");
        EncryptedJWT encryptedJWT;
        try {
            encryptedJWT = decryptJWE(idToken, privateKeyString);
            JSONObject outJSON = new JSONObject();
            JSONObject claimsJSON = new JSONObject();
            // Get all claims set to a map and return a JSON object.
            Map<String, Object> allClaims = encryptedJWT.getJWTClaimsSet().getAllClaims();
            for (Map.Entry<String, Object> entry : allClaims.entrySet()) {
                claimsJSON.put(entry.getKey(), entry.getValue());
            }
            outJSON.put("claims", claimsJSON);
            // Get JWT header data.
            outJSON.put("header", encryptedJWT.getHeader().toJSONObject());
            out.print(outJSON.toString());
        } catch (NoSuchAlgorithmException | ParseException | JOSEException | IllegalArgumentException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            out.print("Error occurred while decrypting id token.");
        } catch (InvalidKeySpecException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            out.print("Invalid client private key.");
        }
    }
}
Also used : JSONObject(net.minidev.json.JSONObject) ServletOutputStream(javax.servlet.ServletOutputStream) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) Map(java.util.Map)

Example 87 with JSONObject

use of net.minidev.json.JSONObject in project ddf by codice.

the class CatalogServiceImplTest method testGetDocumentSourcesSuccess.

/**
 * Tests getting source information
 */
@Test
@SuppressWarnings({ "unchecked" })
public void testGetDocumentSourcesSuccess() throws Exception {
    final String localSourceId = "local";
    final String fed1SourceId = "fed1";
    final String fed2SourceId = "fed2";
    final String version = "4.0";
    final String jsonMimeTypeString = "application/json";
    Set<ContentType> contentTypes = new HashSet<>();
    contentTypes.add(new ContentTypeImpl("ct1", "v1"));
    contentTypes.add(new ContentTypeImpl("ct2", "v2"));
    contentTypes.add(new ContentTypeImpl("ct3", null));
    JSONArray contentTypesInJSON = new JSONArray();
    for (ContentType ct : contentTypes) {
        JSONObject ob = new JSONObject();
        ob.put("name", ct.getName());
        ob.put("version", ct.getVersion() != null ? ct.getVersion() : "");
        contentTypesInJSON.add(ob);
    }
    Set<SourceDescriptor> sourceDescriptors = new HashSet<>();
    SourceDescriptorImpl localDescriptor = new SourceDescriptorImpl(localSourceId, contentTypes, Collections.emptyList());
    localDescriptor.setVersion(version);
    localDescriptor.setAvailable(true);
    SourceDescriptorImpl fed1Descriptor = new SourceDescriptorImpl(fed1SourceId, contentTypes, Collections.emptyList());
    fed1Descriptor.setVersion(version);
    fed1Descriptor.setAvailable(true);
    SourceDescriptorImpl fed2Descriptor = new SourceDescriptorImpl(fed2SourceId, null, Collections.emptyList());
    fed2Descriptor.setAvailable(true);
    sourceDescriptors.add(localDescriptor);
    sourceDescriptors.add(fed1Descriptor);
    sourceDescriptors.add(fed2Descriptor);
    SourceInfoResponse sourceInfoResponse = new SourceInfoResponseImpl(null, null, sourceDescriptors);
    CatalogFramework framework = mock(CatalogFramework.class);
    when(framework.getSourceInfo(isA(SourceInfoRequestEnterprise.class))).thenReturn(sourceInfoResponse);
    CatalogServiceImpl catalogService = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry);
    BinaryContent content = catalogService.getSourcesInfo();
    assertEquals(jsonMimeTypeString, content.getMimeTypeValue());
    String responseMessage = IOUtils.toString(content.getInputStream());
    JSONArray srcList = (JSONArray) new JSONParser().parse(responseMessage);
    assertEquals(3, srcList.size());
    for (Object o : srcList) {
        JSONObject src = (JSONObject) o;
        assertEquals(true, src.get("available"));
        String id = (String) src.get("id");
        if (id.equals(localSourceId)) {
            assertThat((Iterable<Object>) src.get("contentTypes"), hasItems(contentTypesInJSON.toArray()));
            assertEquals(contentTypes.size(), ((JSONArray) src.get("contentTypes")).size());
            assertEquals(version, src.get("version"));
        } else if (id.equals(fed1SourceId)) {
            assertThat((Iterable<Object>) src.get("contentTypes"), hasItems(contentTypesInJSON.toArray()));
            assertEquals(contentTypes.size(), ((JSONArray) src.get("contentTypes")).size());
            assertEquals(version, src.get("version"));
        } else if (id.equals(fed2SourceId)) {
            assertEquals(0, ((JSONArray) src.get("contentTypes")).size());
            assertEquals("", src.get("version"));
        } else {
            fail("Invalid ID returned");
        }
    }
}
Also used : ContentTypeImpl(ddf.catalog.data.impl.ContentTypeImpl) SourceDescriptor(ddf.catalog.source.SourceDescriptor) ContentType(ddf.catalog.data.ContentType) SourceDescriptorImpl(ddf.catalog.source.impl.SourceDescriptorImpl) JSONArray(net.minidev.json.JSONArray) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) BinaryContent(ddf.catalog.data.BinaryContent) SourceInfoRequestEnterprise(ddf.catalog.operation.impl.SourceInfoRequestEnterprise) JSONObject(net.minidev.json.JSONObject) CatalogFramework(ddf.catalog.CatalogFramework) SourceInfoResponseImpl(ddf.catalog.operation.impl.SourceInfoResponseImpl) JSONParser(net.minidev.json.parser.JSONParser) JSONObject(net.minidev.json.JSONObject) SourceInfoResponse(ddf.catalog.operation.SourceInfoResponse) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 88 with JSONObject

use of net.minidev.json.JSONObject in project ddf by codice.

the class GeoNamesWebService method getCountryCode.

@Override
public Optional<String> getCountryCode(String locationWkt, int radius) {
    notNull(locationWkt, "argument locationWkt may not be null");
    Point wktCenterPoint = createPointFromWkt(locationWkt);
    String urlStr = String.format("%s://%s/countryCode?lat=%f&lng=%f&radius=%d&type=JSON&username=%s", GEONAMES_PROTOCOL, GEONAMES_API_ADDRESS, wktCenterPoint.getY(), wktCenterPoint.getX(), radius, USERNAME);
    Object result = webQuery(urlStr);
    if (result instanceof JSONObject) {
        JSONObject jsonResult = (JSONObject) result;
        Object countryCode = jsonResult.get(GEONAMES_COUNTRYCODE);
        if (countryCode != null) {
            String alpha2CountryCode = (String) countryCode;
            if (StringUtils.isNotEmpty(alpha2CountryCode)) {
                try {
                    String alpha3CountryCode = new Locale(Locale.ENGLISH.getLanguage(), alpha2CountryCode).getISO3Country();
                    return Optional.of(alpha3CountryCode);
                } catch (MissingResourceException e) {
                    LOGGER.debug("Failed to convert country code {} to alpha-3 format. Returning " + "empty value", alpha2CountryCode);
                }
            }
        }
    }
    return Optional.empty();
}
Also used : Locale(java.util.Locale) JSONObject(net.minidev.json.JSONObject) MissingResourceException(java.util.MissingResourceException) JSONObject(net.minidev.json.JSONObject) Point(org.locationtech.spatial4j.shape.Point)

Example 89 with JSONObject

use of net.minidev.json.JSONObject in project ddf by codice.

the class GeoNamesWebService method query.

@Override
public List<GeoEntry> query(String queryString, int maxResults) throws GeoEntryQueryException {
    String location = getUrlEncodedLocation(queryString);
    String urlStr = String.format("%s://%s/searchJSON?q=%s&username=%s&maxRows=%d", GEONAMES_PROTOCOL, GEONAMES_API_ADDRESS, location, USERNAME, limitMaxRows(maxResults));
    Object result = webQuery(urlStr);
    if (result != null) {
        if (result instanceof JSONObject) {
            JSONObject jsonResult = (JSONObject) result;
            JSONArray geoNames = (JSONArray) jsonResult.get(GEONAMES_KEY);
            if (geoNames != null) {
                return geoNames.stream().map(JSONObject.class::cast).map(obj -> new GeoEntry.Builder().name((String) obj.get(PLACENAME_KEY)).population((Long) obj.get(POPULATION_KEY)).featureCode((String) obj.get(ADMIN_CODE_KEY)).latitude(Double.valueOf((String) obj.get(LAT_KEY))).longitude(Double.valueOf((String) obj.get(LON_KEY))).build()).collect(toList());
            }
        }
    }
    return Collections.emptyList();
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) LoggerFactory(org.slf4j.LoggerFactory) Validate.notNull(org.apache.commons.lang.Validate.notNull) JSONParser(net.minidev.json.parser.JSONParser) MediaType(javax.ws.rs.core.MediaType) Locale(java.util.Locale) ParseException(net.minidev.json.parser.ParseException) GeoEntry(org.codice.ddf.spatial.geocoding.GeoEntry) GeoEntryQueryable(org.codice.ddf.spatial.geocoding.GeoEntryQueryable) NearbyLocation(org.codice.ddf.spatial.geocoding.context.NearbyLocation) GeoEntryQueryException(org.codice.ddf.spatial.geocoding.GeoEntryQueryException) JtsSpatialContextFactory(org.locationtech.spatial4j.context.jts.JtsSpatialContextFactory) Logger(org.slf4j.Logger) WebClient(org.apache.cxf.jaxrs.client.WebClient) MissingResourceException(java.util.MissingResourceException) Shape(org.locationtech.spatial4j.shape.Shape) StandardCharsets(java.nio.charset.StandardCharsets) Suggestion(org.codice.ddf.spatial.geocoding.Suggestion) PointImpl(org.locationtech.spatial4j.shape.impl.PointImpl) NearbyLocationImpl(org.codice.ddf.spatial.geocoding.context.impl.NearbyLocationImpl) Collectors.toList(java.util.stream.Collectors.toList) URLEncoder(java.net.URLEncoder) List(java.util.List) Point(org.locationtech.spatial4j.shape.Point) JSONArray(net.minidev.json.JSONArray) JSONObject(net.minidev.json.JSONObject) Optional(java.util.Optional) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) SpatialContext(org.locationtech.spatial4j.context.SpatialContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) JSONObject(net.minidev.json.JSONObject) JSONArray(net.minidev.json.JSONArray) JSONObject(net.minidev.json.JSONObject)

Example 90 with JSONObject

use of net.minidev.json.JSONObject in project ddf by codice.

the class LogoutServiceImplTest method testLogout.

@Test
public void testLogout() throws ParseException, SecurityServiceException {
    MockLogoutAction mockLogoutActionProvider = new MockLogoutAction();
    Action defaultLogoutAction = mockLogoutActionProvider.getAction(null);
    LogoutServiceImpl logoutServiceImpl = new LogoutServiceImpl();
    logoutServiceImpl.setSubjectOperations(new SubjectUtils());
    logoutServiceImpl.setHttpSessionFactory(sessionFactory);
    logoutServiceImpl.setSecurityManager(sm);
    logoutServiceImpl.setLogoutActionProviders(ImmutableList.of(mockLogoutActionProvider));
    String responseMessage = logoutServiceImpl.getActionProviders(null, null);
    JSONObject defaultActionProperty = (JSONObject) new JSONParser().parse(responseMessage);
    assertEquals(defaultActionProperty.get("description"), defaultLogoutAction.getDescription());
    assertEquals(defaultActionProperty.get("title"), defaultLogoutAction.getTitle());
    assertEquals(defaultActionProperty.get("url"), defaultLogoutAction.getUrl().toString());
}
Also used : Action(ddf.action.Action) SubjectUtils(ddf.security.service.impl.SubjectUtils) JSONObject(net.minidev.json.JSONObject) JSONParser(net.minidev.json.parser.JSONParser) Test(org.junit.Test)

Aggregations

JSONObject (net.minidev.json.JSONObject)257 JSONArray (net.minidev.json.JSONArray)51 Test (org.junit.Test)39 Test (org.testng.annotations.Test)38 JSONParser (net.minidev.json.parser.JSONParser)26 HashMap (java.util.HashMap)22 MockFlowFile (org.apache.nifi.util.MockFlowFile)16 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)14 ParseException (net.minidev.json.parser.ParseException)14 Test (org.junit.jupiter.api.Test)14 Map (java.util.Map)13 JSONConverterException (org.btrplace.json.JSONConverterException)13 SignedJWT (com.nimbusds.jwt.SignedJWT)12 Node (org.btrplace.model.Node)12 VM (org.btrplace.model.VM)12 JWSHeader (com.nimbusds.jose.JWSHeader)10 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)10 ArrayList (java.util.ArrayList)10 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)10 OpenAPI (io.swagger.v3.oas.models.OpenAPI)9