com.networknt.config.Config Java Examples

The following examples show how to use com.networknt.config.Config. 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: Oauth2ClientGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Deque<String> clientNameDeque = exchange.getQueryParameters().get("clientName");
    String clientName = clientNameDeque == null? "%" : clientNameDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("clientName", clientName);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ClientComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<Client> values = clients.values(pagingPredicate);

    List results = new ArrayList();
    for (Client value : values) {
        Client c = Client.copyClient(value);
        c.setClientSecret(null);
        results.add(c);
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(results));
    processAudit(exchange);
}
 
Example #2
Source File: LoggersGetHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    List<LoggerInfo> loggersList = new ArrayList<LoggerInfo>();
    LoggerConfig config = (LoggerConfig) Config.getInstance().getJsonObjectConfig(CONFIG_NAME, LoggerConfig.class);

    if (config.isEnabled()) {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
            if (log.getLevel() != null) {
                LoggerInfo loggerInfo = new LoggerInfo();
                loggerInfo.setName(log.getName());
                loggerInfo.setLevel(log.getLevel().toString());
                loggersList.add(loggerInfo);
            }
        }
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
        exchange.getResponseSender().send(mapper.writeValueAsString(loggersList));
    } else {
        logger.error("Logging is disabled in logging.yml");
        setExchangeStatus(exchange, STATUS_LOGGER_INFO_DISABLED);
    }
}
 
Example #3
Source File: SanitizerHandlerTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeNode() throws Exception {
    String data = "{\"s1\":\"<script>alert('test1')</script>\",\"s2\":[\"abc\",\"<script>alert('test2')</script>\"],\"s3\":{\"s4\":\"def\",\"s5\":\"<script>alert('test5')</script>\"},\"s6\":[{\"s7\":\"<script>alert('test7')</script>\"},{\"s8\":\"ghi\"}],\"s9\":[[\"<script>alert('test9')</script>\"],[\"jkl\"]]}";
    HashMap<String, Object> jsonMap = Config.getInstance().getMapper().readValue(data,new TypeReference<HashMap<String, Object>>(){});
    SanitizerHandler handler = new SanitizerHandler();
    handler.encoding.encodeNode(jsonMap);
    Assert.assertEquals(jsonMap.get("s1"), "<script>alert(\\'test1\\')</script>");
    ArrayList l2 = (ArrayList)jsonMap.get("s2");
    String s2 = (String)l2.get(1);
    Assert.assertEquals(s2, "<script>alert(\\'test2\\')</script>");
    HashMap<String, Object> m3 = (HashMap<String,Object>)jsonMap.get("s3");
    String s5 = (String)m3.get("s5");
    Assert.assertEquals(s5, "<script>alert(\\'test5\\')</script>");
    ArrayList l6 = (ArrayList)jsonMap.get("s6");
    HashMap<String,Object> m7 = (HashMap<String, Object>)l6.get(0);
    String s7 = (String)m7.get("s7");
    Assert.assertEquals(s7, "<script>alert(\\'test7\\')</script>");
    ArrayList l9 = (ArrayList)jsonMap.get("s9");
    ArrayList l = (ArrayList)l9.get(0);
    String s9 = (String)l.get(0);
    Assert.assertEquals(s9, "<script>alert(\\'test9\\')</script>");
}
 
Example #4
Source File: JwtVerifierTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadCertificate() {
    Map<String, Object> config = Config.getInstance().getJsonMapConfig(CONFIG_NAME);
    Map<String, Object> jwtConfig = (Map<String, Object>)config.get(JwtIssuer.JWT_CONFIG);
    Map<String, Object> keyMap = (Map<String, Object>) jwtConfig.get(JwtVerifier.JWT_CERTIFICATE);
    Map<String, X509Certificate> certMap = new HashMap<>();
    JwtVerifier jwtVerifier = new JwtVerifier(config);
    for(String kid: keyMap.keySet()) {
        X509Certificate cert = null;
        try {
            cert = jwtVerifier.readCertificate((String)keyMap.get(kid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        certMap.put(kid, cert);
    }
    Assert.assertEquals(2, certMap.size());
}
 
Example #5
Source File: ConsulRegistry.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * update service cache of the serviceName.
 * update local cache when service list changed,
 * if need notify, notify service
 *
 * @param serviceName
 * @param serviceUrls
 * @param needNotify
 */
private void updateServiceCache(String serviceName, ConcurrentHashMap<String, List<URL>> serviceUrls, boolean needNotify) {
    if (serviceUrls != null && !serviceUrls.isEmpty()) {
        List<URL> cachedUrls = serviceCache.get(serviceName);
        List<URL> newUrls = serviceUrls.get(serviceName);
        try {
            logger.trace("serviceUrls = {}", Config.getInstance().getMapper().writeValueAsString(serviceUrls));
        } catch(Exception e) {
        }
        boolean change = true;
        if (ConsulUtils.isSame(newUrls, cachedUrls)) {
            change = false;
        } else {
            serviceCache.put(serviceName, newUrls);
        }
        if (change && needNotify) {
            notifyExecutor.execute(new NotifyService(serviceName, newUrls));
            logger.info("light service notify-service: " + serviceName);
            StringBuilder sb = new StringBuilder();
            for (URL url : newUrls) {
                sb.append(url.getUri()).append(";");
            }
            logger.info("consul notify urls:" + sb.toString());
        }
    }
}
 
Example #6
Source File: TlsUtil.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public static KeyStore loadTrustStore(final String name, final char[] password) {
    try (InputStream stream = Config.getInstance().getInputStreamFromFile(name)) {
        if (stream == null) {
            String message = "Unable to load truststore '" + name + "', please provide the truststore matching the configuration in client.yml/server.yml to enable TLS connection.";
            if (logger.isErrorEnabled()) {
                logger.error(message);
            }
            throw new RuntimeException(message);
        }
        KeyStore loadedKeystore = KeyStore.getInstance("JKS");
        loadedKeystore.load(stream, password);
        return loadedKeystore;
    } catch (Exception e) {
        logger.error("Unable to load truststore " + name, e);
        throw new RuntimeException("Unable to load truststore " + name, e);
    }
}
 
Example #7
Source File: Oauth2RefreshTokenGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
    Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
    String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());
    if(logger.isDebugEnabled()) logger.debug("userId = " + userId + " page = " + page + " pageSize = " + pageSize);
    LikePredicate likePredicate = new LikePredicate("userId", userId);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new RefreshTokenComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<RefreshToken> values = tokens.values(pagingPredicate);

    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
    processAudit(exchange);
}
 
Example #8
Source File: StatusSerializerTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    config = Config.getInstance();

    // write a config file into the user home directory.
    List<String> implementationList = new ArrayList<>();
    implementationList.add("com.networknt.status.ErrorRootStatusSerializer");
    Map<String, List<String>> implementationMap = new HashMap<>();
    implementationMap.put("com.networknt.status.StatusSerializer", implementationList);
    List<Map<String, List<String>>> interfaceList = new ArrayList<>();
    interfaceList.add(implementationMap);
    Map<String, Object> singletons = new HashMap<>();
    singletons.put("singletons", interfaceList);
    config.getMapper().writeValue(new File(homeDir + "/service.json"), singletons);

    // Add home directory to the classpath of the system class loader.
    AppURLClassLoader classLoader = new AppURLClassLoader(new URL[0], ClassLoader.getSystemClassLoader());
    classLoader.addURL(new File(homeDir).toURI().toURL());
    config.setClassLoader(classLoader);
}
 
Example #9
Source File: Server.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Locate the Config Loader class, instantiate it and then call init() method on it.
 * Uses DefaultConfigLoader if startup.yml is missing or configLoaderClass is missing in startup.yml
 */
static public void loadConfigs(){
    IConfigLoader configLoader;
    Map<String, Object> startupConfig = Config.getInstance().getJsonMapConfig(STARTUP_CONFIG_NAME);
    if(startupConfig ==null || startupConfig.get(CONFIG_LOADER_CLASS) ==null){
        configLoader = new DefaultConfigLoader();
    }else{
        try {
            Class clazz = Class.forName((String) startupConfig.get(CONFIG_LOADER_CLASS));
            configLoader = (IConfigLoader) clazz.getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("configLoaderClass mentioned in startup.yml could not be found or constructed", e);
        }
    }
    configLoader.init();
}
 
Example #10
Source File: ForwardRequestHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String responseBody = null;
    if(exchange.getAttachment(BodyHandler.REQUEST_BODY) != null) {
        responseBody = Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY));
    }

    List<HttpString> headerNames = exchange.getRequestHeaders().getHeaderNames().stream()
            .filter( s -> s.toString().startsWith("todo"))
            .collect(Collectors.toList());
    for(HttpString headerName : headerNames) {
        String headerValue = exchange.getRequestHeaders().get(headerName).getFirst();
        exchange.getResponseHeaders().put(headerName, headerValue);
    }
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ContentType.APPLICATION_JSON.value());
    exchange.getResponseSender().send(responseBody);
}
 
Example #11
Source File: Oauth2RefreshTokenRefreshTokenGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String refreshToken = exchange.getQueryParameters().get("refreshToken").getFirst();
    if(logger.isDebugEnabled()) logger.debug("refreshToken = " + refreshToken);
    IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
    RefreshToken token = tokens.get(refreshToken);

    if(token == null) {
        setExchangeStatus(exchange, REFRESH_TOKEN_NOT_FOUND, refreshToken);
    } else {
        exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(token));
    }
    processAudit(exchange);
}
 
Example #12
Source File: Oauth2UserPutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    User user = Config.getInstance().getMapper().convertValue(body, User.class);
    String userId = user.getUserId();
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User u = users.get(userId);
    if(u == null) {
        setExchangeStatus(exchange, USER_NOT_FOUND, userId);
    } else {
        // as password is not in the return value, chances are password is not in the user object
        user.setPassword(u.getPassword());
        users.set(userId, user);
    }
    processAudit(exchange);
}
 
Example #13
Source File: JwtHelperTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadCertificate() {
    Map<String, Object> securityConfig = Config.getInstance().getJsonMapConfig(JwtHelper.SECURITY_CONFIG);
    Map<String, Object> jwtConfig = (Map<String, Object>)securityConfig.get(JwtIssuer.JWT_CONFIG);
    Map<String, Object> keyMap = (Map<String, Object>) jwtConfig.get(JwtHelper.JWT_CERTIFICATE);
    Map<String, X509Certificate> certMap = new HashMap<>();
    for(String kid: keyMap.keySet()) {
        X509Certificate cert = null;
        try {
            cert = JwtHelper.readCertificate((String)keyMap.get(kid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        certMap.put(kid, cert);
    }
    Assert.assertEquals(2, certMap.size());
}
 
Example #14
Source File: Oauth2UserUserIdGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String userId = exchange.getQueryParameters().get("userId").getFirst();

    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User user = users.get(userId);

    if(user == null) {
        setExchangeStatus(exchange, USER_NOT_FOUND, userId);
        processAudit(exchange);
        return;
    }
    // remove password here
    user.setPassword(null);
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(user));
    processAudit(exchange);
}
 
Example #15
Source File: Oauth2UserGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
    String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("userId", userId);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new UserComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<User> values = users.values(pagingPredicate);

    for (User value : values) {
        value.setPassword(null);
    }
    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
    processAudit(exchange);
}
 
Example #16
Source File: Oauth2ServiceGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");

    Deque<String> serviceIdDeque = exchange.getQueryParameters().get("serviceId");
    String serviceId = serviceIdDeque == null? "%" : serviceIdDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("serviceId", serviceId);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ServiceComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<Service> values = services.values(pagingPredicate);

    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
    processAudit(exchange);
}
 
Example #17
Source File: Oauth2ServiceServiceIdGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();

    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    Service service = services.get(serviceId);

    if(service == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(service));
    processAudit(exchange);
}
 
Example #18
Source File: ServerInfoDisabledTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void tearDown() throws Exception {
    if(server != null) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {

        }
        server.stop();
        logger.info("The server is stopped.");
    }
    // Remove the test.json from home directory
    File configFile = new File(homeDir + "/info.yml");
    configFile.delete();
    // this is very important as it impacts subsequent test case if it is not cleared.
    Config.getInstance().clear();
}
 
Example #19
Source File: Oauth2ServicePutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Service service = Config.getInstance().getMapper().convertValue(body, Service.class);

    String serviceId = service.getServiceId();

    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
    } else {
        services.set(serviceId, service);
    }
    processAudit(exchange);
}
 
Example #20
Source File: Oauth2ServiceServiceIdEndpointGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");

    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
    List<ServiceEndpoint> values = serviceEndpoints.get(serviceId);

    if(values == null || values.size() == 0) {
        setExchangeStatus(exchange, SERVICE_ENDPOINT_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
    processAudit(exchange);
}
 
Example #21
Source File: Oauth2ServiceServiceIdEndpointPostHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    List<Map<String, Object>> body = (List)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
    if(logger.isDebugEnabled()) logger.debug("post serviceEndpoints for serviceId " + serviceId);

    // ensure that the serviceId exists
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }

    IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
    List<ServiceEndpoint> list = new ArrayList<>();
    for(Map<String, Object> m: body) {
        list.add(Config.getInstance().getMapper().convertValue(m, ServiceEndpoint.class));
    }
    serviceEndpoints.set(serviceId, list);
    processAudit(exchange);
}
 
Example #22
Source File: Oauth2ClientClientIdGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String clientId = exchange.getQueryParameters().get("clientId").getFirst();

    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);

    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
        return;
    }
    Client c = Client.copyClient(client);
    c.setClientSecret(null);
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(c));
    processAudit(exchange);
}
 
Example #23
Source File: ServerInfoGetHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    ServerInfoConfig config = (ServerInfoConfig)Config.getInstance().getJsonObjectConfig(CONFIG_NAME, ServerInfoConfig.class);
    if(config.isEnableServerInfo()) {
        Map<String, Object> infoMap = new LinkedHashMap<>();
        infoMap.put("deployment", getDeployment());
        infoMap.put("environment", getEnvironment(exchange));
        infoMap.put("security", getSecurity());
        infoMap.put("specification", Config.getInstance().getJsonMapConfigNoCache("swagger"));
        infoMap.put("component", ModuleRegistry.getRegistry());
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(infoMap));
    } else {
        setExchangeStatus(exchange, STATUS_SERVER_INFO_DISABLED);
    }
}
 
Example #24
Source File: Mask.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public static String maskJson(DocumentContext ctx, String key) {
    Map<String, Object> jsonConfig = (Map<String, Object>) config.get(MASK_TYPE_JSON);
    if (jsonConfig != null) {
        Map<String, Object> patternMap = (Map<String, Object>) jsonConfig.get(key);
        if (patternMap != null) {
            JsonNode configNode = Config.getInstance().getMapper().valueToTree(patternMap);
            Iterator<Map.Entry<String, JsonNode>> iterator = configNode.fields();
            while (iterator.hasNext()) {
                Map.Entry<String, JsonNode> entry = iterator.next();
                applyMask(entry, ctx);
            }
            return ctx.jsonString();
        } else {
            logger.warn("mask.json doesn't contain the key {} ", Encode.forJava(key));
        }
    }
    return ctx.jsonString();
}
 
Example #25
Source File: Server.java    From light-4j with Apache License 2.0 6 votes vote down vote up
protected static void mergeStatusConfig() {
    Map<String, Object> appStatusConfig = Config.getInstance().getJsonMapConfigNoCache(STATUS_CONFIG_NAME[1]);
    if (appStatusConfig == null) {
        return;
    }
    Map<String, Object> statusConfig = Config.getInstance().getJsonMapConfig(STATUS_CONFIG_NAME[0]);
    // clone the default status config key set
    Set<String> duplicatedStatusSet = new HashSet<>(statusConfig.keySet());
    duplicatedStatusSet.retainAll(appStatusConfig.keySet());
    if (!duplicatedStatusSet.isEmpty()) {
        logger.error("The status code(s): " + duplicatedStatusSet.toString() + " is already in use by light-4j and cannot be overwritten," +
                " please change to another status code in app-status.yml if necessary.");
        throw new RuntimeException("The status code(s): " + duplicatedStatusSet.toString() + " in status.yml and app-status.yml are duplicated.");
    }
    statusConfig.putAll(appStatusConfig);
}
 
Example #26
Source File: Oauth2ProviderPutHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    Provider provider = Config.getInstance().getMapper().convertValue(body, Provider.class);

    String provider_id = provider.getProviderId() ;

    IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers");
    if(providers.get(provider_id) == null) {
        setExchangeStatus(exchange, PROVIDER_ID_INVALID);
    } else {
        providers.set(provider_id, provider);
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(provider));
    }
    processAudit(exchange);
    
}
 
Example #27
Source File: BodyHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Method used to parse the body into a Map or a List and attach it into exchange
 *
 * @param exchange exchange to be attached
 * @param string   unparsed request body
 * @throws IOException
 */
private void attachJsonBody(final HttpServerExchange exchange, String string) throws IOException {
    Object body;
    if (string != null) {
        string = string.trim();
        if (string.startsWith("{")) {
            body = Config.getInstance().getMapper().readValue(string, new TypeReference<Map<String, Object>>() {
            });
        } else if (string.startsWith("[")) {
            body = Config.getInstance().getMapper().readValue(string, new TypeReference<List<Object>>() {
            });
        } else {
            // error here. The content type in head doesn't match the body.
            setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, "application/json");
            return;
        }
        exchange.putAttachment(REQUEST_BODY, body);
    }
}
 
Example #28
Source File: Oauth2ProviderGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers");


    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(providers));
    processAudit(exchange);
}
 
Example #29
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullValue() throws IOException {
    String json = "{\"selection\": {\"id\": null}}";
    Map<String, Object> map = Config.getInstance().getMapper().readValue(json, new TypeReference<Map<String, Object>>() {
    });
    Map<String, Object> selectionMap = (Map<String, Object>)map.get("selection");
    Assert.assertNull(selectionMap.get("id"));

}
 
Example #30
Source File: VirtualHostHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public VirtualHostHandler() {
    VirtualHostConfig config = (VirtualHostConfig)Config.getInstance().getJsonObjectConfig(VirtualHostConfig.CONFIG_NAME, VirtualHostConfig.class);
    virtualHostHandler = new NameVirtualHostHandler();
    for(VirtualHost host: config.hosts) {
        virtualHostHandler.addHost(host.domain, new PathHandler().addPrefixPath(host.getPath(), new ResourceHandler((new PathResourceManager(Paths.get(host.getBase()), host.getTransferMinSize()))).setDirectoryListingEnabled(host.isDirectoryListingEnabled())));
    }
}