Java Code Examples for com.blade.Blade

The following examples show how to use com.blade.Blade. These examples are extracted from open source projects. 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 Project: tale   Author: tfssweb   File: WebContext.java    License: MIT License 6 votes vote down vote up
@Override
public void preHandle(Blade blade) {
    Ioc ioc = blade.ioc();

    boolean devMode = true;
    if (blade.environment().hasKey("app.dev")) {
        devMode = blade.environment().getBoolean("app.dev", true);
    }
    if (blade.environment().hasKey("app.devMode")) {
        devMode = blade.environment().getBoolean("app.devMode", true);
    }
    SqliteJdbc.importSql(devMode);

    Sql2o sql2o = new Sql2o(SqliteJdbc.DB_SRC, null, null);
    Base.open(sql2o);
    Commons.setSiteService(ioc.getBean(SiteService.class));
}
 
Example #2
Source Project: tale   Author: tfssweb   File: ThemeController.java    License: MIT License 6 votes vote down vote up
@GetRoute(value = "")
public String index(Request request) {
    // 读取主题
    String         themesDir  = AttachController.CLASSPATH + "templates/themes";
    File[]         themesFile = new File(themesDir).listFiles();
    List<ThemeDto> themes     = new ArrayList<>(themesFile.length);
    for (File f : themesFile) {
        if (f.isDirectory()) {
            ThemeDto themeDto = new ThemeDto(f.getName());
            if (Files.exists(Paths.get(f.getPath() + "/setting.html"))) {
                themeDto.setHasSetting(true);
            }
            themes.add(themeDto);
            try {
                Blade.me().addStatics("/templates/themes/" + f.getName() + "/screenshot.png");
            } catch (Exception e) {
            }
        }
    }
    request.attribute("current_theme", Commons.site_theme());
    request.attribute("themes", themes);
    return "admin/themes";
}
 
Example #3
Source Project: tutorials   Author: eugenp   File: App.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {

        Blade.of()
            .get("/", ctx -> ctx.render("index.html"))
            .get("/basic-route-example", ctx -> ctx.text("GET called"))
            .post("/basic-route-example", ctx -> ctx.text("POST called"))
            .put("/basic-route-example", ctx -> ctx.text("PUT called"))
            .delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
            .addStatics("/custom-static")
            // .showFileList(true)
            .enableCors(true)
            .before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
            .on(EventType.SERVER_STARTED, e -> {
                String version = WebContext.blade()
                    .env("app.version")
                    .orElse("N/D");
                log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
            })
            .on(EventType.SESSION_CREATED, e -> {
                Session session = (Session) e.attribute("session");
                session.attribute("mySessionValue", "Baeldung");
            })
            .use(new BaeldungMiddleware())
            .start(App.class, args);
    }
 
Example #4
Source Project: blade   Author: lets-blade   File: HttpServerInitializer.java    License: Apache License 2.0 5 votes vote down vote up
public HttpServerInitializer(SslContext sslCtx, Blade blade, ScheduledExecutorService service) {
    this.sslCtx = sslCtx;
    this.blade = blade;
    this.useGZIP = blade.environment().getBoolean(Const.ENV_KEY_GZIP_ENABLE, false);
    this.isWebSocket = blade.routeMatcher().getWebSockets().size() > 0;
    this.httpServerHandler = new HttpServerHandler();

    service.scheduleWithFixedDelay(() -> date = DateKit.gmtDate(LocalDateTime.now()), 1000, 1000, TimeUnit.MILLISECONDS);
}
 
Example #5
Source Project: blade   Author: lets-blade   File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start(Blade blade) throws Exception {
    this.blade = blade;
    this.environment = blade.environment();
    this.processors = blade.processors();
    this.loaders = blade.loaders();

    long startMs = System.currentTimeMillis();

    int padSize = 16;
    log.info("{} {}{}", StringKit.padRight("app.env", padSize), getPrefixSymbol(), environment.get(ENV_KEY_APP_ENV, "default"));
    log.info("{} {}{}", StringKit.padRight("app.pid", padSize), getPrefixSymbol(), BladeKit.getPID());
    log.info("{} {}{}", StringKit.padRight("app.devMode", padSize), getPrefixSymbol(), blade.devMode());

    log.info("{} {}{}", StringKit.padRight("jdk.version", padSize), getPrefixSymbol(), System.getProperty("java.version"));
    log.info("{} {}{}", StringKit.padRight("user.dir", padSize), getPrefixSymbol(), System.getProperty("user.dir"));
    log.info("{} {}{}", StringKit.padRight("java.io.tmpdir", padSize), getPrefixSymbol(), System.getProperty("java.io.tmpdir"));
    log.info("{} {}{}", StringKit.padRight("user.timezone", padSize), getPrefixSymbol(), System.getProperty("user.timezone"));
    log.info("{} {}{}", StringKit.padRight("file.encoding", padSize), getPrefixSymbol(), System.getProperty("file.encoding"));
    log.info("{} {}{}", StringKit.padRight("app.classpath", padSize), getPrefixSymbol(), CLASSPATH);

    this.initConfig();

    String contextPath = environment.get(ENV_KEY_CONTEXT_PATH, "/");
    WebContext.init(blade, contextPath);

    this.initIoc();
    this.watchEnv();
    this.startServer(startMs);
    this.sessionCleaner();
    this.startTask();
    this.shutdownHook();
}
 
Example #6
Source Project: blade   Author: lets-blade   File: BladeTestRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Statement withBeforeClasses(final Statement statement) {
    final Statement junitStatement = super.withBeforeClasses(statement);
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            blade = Blade.me().start(mainCls).await();
            junitStatement.evaluate();
        }
    };
}
 
Example #7
Source Project: blade   Author: lets-blade   File: BasicAuthMiddlewareTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthSuccess() throws Exception {

    Request mockRequest = mockHttpRequest("GET");

    WebContext.init(Blade.of(), "/");

    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Basic YWRtaW46MTIzNDU2");

    when(mockRequest.parameters()).thenReturn(new HashMap<>());
    when(mockRequest.headers()).thenReturn(headers);

    Request  request  = new HttpRequest(mockRequest);
    Response response = mockHttpResponse(200);

    RouteContext context = new RouteContext(request, response);
    context.initRoute(Route.builder()
            .action(AuthHandler.class.getMethod("handle", RouteContext.class))
            .targetType(AuthHandler.class)
            .target(new AuthHandler()).build());

    WebContext.set(new WebContext(request, response, null));

    AuthOption authOption = AuthOption.builder().build();
    authOption.addUser("admin", "123456");

    BasicAuthMiddleware basicAuthMiddleware = new BasicAuthMiddleware(authOption);
    boolean             flag                = basicAuthMiddleware.before(context);
    assertTrue(flag);
}
 
Example #8
Source Project: blade   Author: lets-blade   File: BasicAuthMiddlewareTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthFail() throws Exception {
    Request mockRequest = mockHttpRequest("GET");

    WebContext.init(Blade.of(), "/");

    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Basic YmxhZGU6YmxhZGUyMg==");

    when(mockRequest.parameters()).thenReturn(new HashMap<>());
    when(mockRequest.headers()).thenReturn(headers);

    Request  request  = new HttpRequest(mockRequest);
    Response response = mockHttpResponse(200);

    RouteContext context = new RouteContext(request, response);

    context.initRoute(Route.builder()
            .action(AuthHandler.class.getMethod("handle", RouteContext.class))
            .targetType(AuthHandler.class)
            .target(new AuthHandler()).build());

    WebContext.set(new WebContext(request, response, null));

    AuthOption authOption = AuthOption.builder().build();
    authOption.addUser("admin", "123456");

    BasicAuthMiddleware basicAuthMiddleware = new BasicAuthMiddleware(authOption);
    boolean             flag                = basicAuthMiddleware.before(context);
    assertFalse(flag);
}
 
Example #9
Source Project: blade   Author: lets-blade   File: ExceptionHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    request = mock(Request.class);
    when(request.header("Accept")).thenReturn("text/html");
    response = mock(Response.class);

    WebContext.init(Blade.me(), "/");
    WebContext.set(new WebContext(request, response, null));
}
 
Example #10
Source Project: blade   Author: lets-blade   File: BeanProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBeanProcessor(){
    Blade blade = Blade.me();
    BeanProcessor beanProcessor = mock(BeanProcessor.class);
    beanProcessor.processor(blade);
    verify(beanProcessor).processor(blade);
}
 
Example #11
Source Project: FrameworkBenchmarks   Author: TechEmpower   File: Application.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
    Blade.of()
            .get("/json", ctx -> ctx.json(new Message()).contentType(JSON_CONTENT_TYPE)
                    .header(SERVER_HEADER, SERVER_VALUE))
            .get("/plaintext", ctx -> ctx.body(PLAINTEXT).contentType("text/plain")
                    .header(SERVER_HEADER, SERVER_VALUE))
            .get("/db", Application::db)
            .get("/queries", Application::queries)
            .get("/updates", Application::updates)
            .get("/fortunes", Application::fortunes)
            .disableSession()
            .start(Application.class, args);
}
 
Example #12
Source Project: FrameworkBenchmarks   Author: TechEmpower   File: Bootstrap.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void load(Blade blade) {
    try {
        JetbrickTemplateEngine templateEngine = new JetbrickTemplateEngine();
        blade.templateEngine(templateEngine);

        HikariConfig config = new HikariConfig();

        String url                   = blade.env("jdbc.url", "");
        String username              = blade.env("jdbc.username", "");
        String password              = blade.env("jdbc.password", "");
        String cachePrepStmts        = blade.env("datasource.cachePrepStmts", "true");
        String prepStmtCacheSize     = blade.env("datasource.prepStmtCacheSize", "250");
        String prepStmtCacheSqlLimit = blade.env("datasource.prepStmtCacheSqlLimit", "2048");

        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.addDataSourceProperty("cachePrepStmts", cachePrepStmts);
        config.addDataSourceProperty("prepStmtCacheSize", prepStmtCacheSize);
        config.addDataSourceProperty("prepStmtCacheSqlLimit", prepStmtCacheSqlLimit);

        HikariDataSource ds = new HikariDataSource(config);
        Anima.open(ds);
    } catch (Exception e) {
        System.out.println("Connection database fail");
    }
}
 
Example #13
Source Project: tutorials   Author: eugenp   File: LoadConfig.java    License: MIT License 5 votes vote down vote up
@Override
public void load(Blade blade) {
    String version = WebContext.blade()
        .env("app.version")
        .orElse("N/D");
    String authors = WebContext.blade()
        .env("app.authors", "Unknown authors");

    log.info("[LoadConfig] loaded 'app.version' (" + version + ") and 'app.authors' (" + authors + ") in a configuration bean");
}
 
Example #14
Source Project: tools-journey   Author: shoukai   File: Hello.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Blade.me()
            .get("/hello", ((request, response) -> response.text("Hello World.")))
            .start(Hello.class, args);
}
 
Example #15
Source Project: tale   Author: tfssweb   File: WebContext.java    License: MIT License 4 votes vote down vote up
@Override
public void processor(Blade blade) {
    JetbrickTemplateEngine templateEngine = new JetbrickTemplateEngine();

    List<String> macros = new ArrayList<>(8);
    macros.add(File.separatorChar + "comm" + File.separatorChar + "macros.html");
    // 扫描主题下面的所有自定义宏
    String themeDir = AttachController.CLASSPATH + "templates" + File.separatorChar + "themes";
    File[] dir      = new File(themeDir).listFiles();
    for (File f : dir) {
        if (f.isDirectory() && Files.exists(Paths.get(f.getPath() + File.separatorChar + "macros.html"))) {
            String macroName = File.separatorChar + "themes" + File.separatorChar + f.getName() + File.separatorChar + "macros.html";
            macros.add(macroName);
        }
    }
    StringBuffer sbuf = new StringBuffer();
    macros.forEach(s -> sbuf.append(',').append(s));
    templateEngine.addConfig("jetx.import.macros", sbuf.substring(1));

    GlobalResolver resolver = templateEngine.getGlobalResolver();
    resolver.registerFunctions(Commons.class);
    resolver.registerFunctions(Theme.class);
    resolver.registerFunctions(AdminCommons.class);
    resolver.registerTags(JetTag.class);

    JetGlobalContext context = templateEngine.getGlobalContext();
    context.set("version", environment.get("app.version", "v1.0"));
    context.set("enableCdn", environment.getBoolean("app.enableCdn", false));

    blade.templateEngine(templateEngine);

    TaleConst.ENABLED_CDN = environment.getBoolean("app.enableCdn", false);
    TaleConst.MAX_FILE_SIZE = environment.getInt("app.max-file-size", 20480);

    TaleConst.AES_SALT = environment.get("app.salt", "012c456789abcdef");
    TaleConst.OPTIONS.addAll(optionsService.getOptions());
    String ips = TaleConst.OPTIONS.get(Types.BLOCK_IPS, "");
    if (StringKit.isNotBlank(ips)) {
        TaleConst.BLOCK_IPS.addAll(Arrays.asList(ips.split(",")));
    }
    if (Files.exists(Paths.get(AttachController.CLASSPATH + "install.lock"))) {
        TaleConst.INSTALLED = Boolean.TRUE;
    }

    BaseController.THEME = "themes/" + Commons.site_option("site_theme");

    TaleConst.BCONF = environment;
}
 
Example #16
Source Project: tale   Author: tfssweb   File: TaleLoader.java    License: MIT License 4 votes vote down vote up
public static void init(Blade blade) {
    TaleLoader.blade = blade;
    loadPlugins();
    loadThemes();
}
 
Example #17
Source Project: tale   Author: tfssweb   File: Application.java    License: MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Blade blade = Blade.me();
    TaleLoader.init(blade);
    blade.use(new ValidatorMiddleware(), new CsrfMiddleware()).start(Application.class, args);
}
 
Example #18
Source Project: blade   Author: lets-blade   File: SessionHandler.java    License: Apache License 2.0 4 votes vote down vote up
public SessionHandler(Blade blade) {
    this.blade = blade;
    this.sessionManager = blade.sessionManager();
    this.timeout = blade.environment().getInt(ENV_KEY_SESSION_TIMEOUT, 1800);
}
 
Example #19
Source Project: blade   Author: lets-blade   File: WebSocketHandlerWrapper.java    License: Apache License 2.0 4 votes vote down vote up
public static WebSocketHandlerWrapper init(Blade blade) {
    return new WebSocketHandlerWrapper(blade);
}
 
Example #20
Source Project: blade   Author: lets-blade   File: WebSocketHandlerWrapper.java    License: Apache License 2.0 4 votes vote down vote up
private WebSocketHandlerWrapper(Blade blade) {
    this.blade = blade;
}
 
Example #21
Source Project: blade   Author: lets-blade   File: WebSocketHandler.java    License: Apache License 2.0 4 votes vote down vote up
public WebSocketHandler(Blade blade) {
    this.blade = blade;
}
 
Example #22
Source Project: blade   Author: lets-blade   File: StaticFileHandler.java    License: Apache License 2.0 4 votes vote down vote up
public StaticFileHandler(Blade blade) {
    this.showFileList = blade.environment().getBoolean(Const.ENV_KEY_STATIC_LIST, false);
    this.httpCacheSeconds = blade.environment().getLong(Const.ENV_KEY_HTTP_CACHE_TIMEOUT, 86400 * 30);
}
 
Example #23
Source Project: blade   Author: lets-blade   File: ValueDefineTest.java    License: Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
    app = Blade.me();
    app.scanPackages("com.blade.model","com.blade.ioc");
    app.listen(10087).start().await();
}
 
Example #24
Source Project: blade   Author: lets-blade   File: ServerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateServer() throws Exception {
    Server server = new NettyServer();
    server.start(Blade.me().listen(10086));
    server.stop();
}
 
Example #25
Source Project: blade   Author: lets-blade   File: ServerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testStart() throws Exception {
    NettyServer nettyServer = new NettyServer();
    nettyServer.start(Blade.of().listen(10087));
    nettyServer.stop();
}
 
Example #26
Source Project: blade   Author: lets-blade   File: EventManagerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testManager() {
    EventManager eventManager = new EventManager();
    eventManager.addEventListener(EventType.SERVER_STARTED, b -> System.out.println("server started"));
    eventManager.fireEvent(EventType.SERVER_STARTED, new Event().attribute("blade", Blade.of()));
}
 
Example #27
Source Project: blade   Author: lets-blade   File: PkgNpeTest.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Blade.of()
            .start();
}
 
Example #28
Source Project: blade   Author: lets-blade   File: BladeLoader.java    License: Apache License 2.0 2 votes vote down vote up
default void preLoad(Blade blade) {

    }
 
Example #29
Source Project: blade   Author: lets-blade   File: WebContext.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Initializes the project when it starts
 *
 * @param blade       Blade instance
 * @param contextPath context path
 */
public static void init(Blade blade, String contextPath) {
    WebContext.blade = blade;
    WebContext.contextPath = contextPath;
    WebContext.sessionKey = blade.environment().get(ENV_KEY_SESSION_KEY, DEFAULT_SESSION_KEY);
}
 
Example #30
Source Project: blade   Author: lets-blade   File: WebContext.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Get blade instance
 *
 * @return return Blade
 */
public static Blade blade() {
    return blade;
}