com.blade.mvc.Const Java Examples

The following examples show how to use com.blade.mvc.Const. 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: FileChangeDetector.java    From blade with Apache License 2.0 6 votes vote down vote up
public static Path getDestPath(Path src, Environment env){
    String templateDir = env.get(Const.ENV_KEY_TEMPLATE_PATH,"/templates");
    Optional<String> staticDir =  env.get(Const.ENV_KEY_STATIC_DIRS);
    List<String> templateOrStaticDirKeyword = new ArrayList<>();
    templateOrStaticDirKeyword.add(templateDir);
    if(staticDir.isPresent()){
        templateOrStaticDirKeyword.addAll(Arrays.asList(staticDir.get().split(",")));
    }else{
        templateOrStaticDirKeyword.addAll(Const.DEFAULT_STATICS);
    }

    List result = templateOrStaticDirKeyword.stream().filter(dir -> src.toString().indexOf(dir)!=-1).collect(Collectors.toList());
    if(result.size()!=1){
        log.info("Cannot get dest dir");
        return  null;
    }
    String key = (String)result.get(0);
    log.info(Const.CLASSPATH + src.toString().substring(src.toString().indexOf(key)));
    return Paths.get(Const.CLASSPATH + src.toString().substring(src.toString().indexOf(key)));
}
 
Example #2
Source File: StaticFileHandler.java    From blade with Apache License 2.0 6 votes vote down vote up
private static String sanitizeUri(String uri) {
    if (uri.isEmpty() || uri.charAt(0) != HttpConst.CHAR_SLASH) {
        return null;
    }
    // Convert file separators.
    uri = uri.replace(HttpConst.CHAR_SLASH, File.separatorChar);
    // Simplistic dumb security check.
    // You will have to do something serious in the production environment.
    if (uri.contains(File.separator + HttpConst.CHAR_POINT) ||
            uri.contains('.' + File.separator) ||
            uri.charAt(0) == '.' || uri.charAt(uri.length() - 1) == '.' ||
            INSECURE_URI.matcher(uri).matches()) {
        return null;
    }
    // Maven resources path
    String path = Const.CLASSPATH + File.separator + uri.substring(1);
    return path.replace("//", "/");
}
 
Example #3
Source File: SqliteJdbc.java    From tale with MIT License 5 votes vote down vote up
/**
 * 测试连接并导入数据库
 */
public static void importSql(boolean devMode) {
    try {

        DB_PATH = Const.CLASSPATH + File.separatorChar + DB_NAME;
        DB_SRC = "jdbc:sqlite://" + DB_PATH;

        if (devMode) {
            DB_PATH = System.getProperty("user.dir") + "/" + DB_NAME;
            DB_SRC = "jdbc:sqlite://" + DB_PATH;
        }

        log.info("blade dev mode: {}", devMode);
        log.info("load sqlite database path [{}]", DB_PATH);
        log.info("load sqlite database src [{}]", DB_SRC);

        Connection con       = DriverManager.getConnection(DB_SRC);
        Statement  statement = con.createStatement();
        ResultSet  rs        = statement.executeQuery("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='t_options'");
        int        count     = rs.getInt(1);
        if (count == 0) {
            String            cp  = SqliteJdbc.class.getClassLoader().getResource("").getPath();
            InputStreamReader isr = new InputStreamReader(new FileInputStream(cp + "schema.sql"), "UTF-8");

            String sql = new BufferedReader(isr).lines().collect(Collectors.joining("\n"));
            int    r   = statement.executeUpdate(sql);
            log.info("initialize import database - {}", r);
        }
        rs.close();
        statement.close();
        con.close();
        log.info("database path is: {}", DB_PATH);
    } catch (Exception e) {
        log.error("initialize database fail", e);
    }
}
 
Example #4
Source File: TemplateController.java    From tale with MIT License 5 votes vote down vote up
@Route(value = "", method = HttpMethod.GET)
public String index(Request request) {
    String themePath = Const.CLASSPATH + File.separatorChar + "templates" + File.separatorChar + "themes" + File.separatorChar + Commons.site_theme();
    try {
        List<String> files = Files.list(Paths.get(themePath))
                .map(path -> path.getFileName().toString())
                .filter(path -> path.endsWith(".html"))
                .collect(Collectors.toList());

        List<String> partial = Files.list(Paths.get(themePath + File.separatorChar + "partial"))
                .map(path -> path.getFileName().toString())
                .filter(path -> path.endsWith(".html"))
                .map(fileName -> "partial/" + fileName)
                .collect(Collectors.toList());

        List<String> statics = Files.list(Paths.get(themePath + File.separatorChar + "static"))
                .map(path -> path.getFileName().toString())
                .filter(path -> path.endsWith(".js") || path.endsWith(".css"))
                .map(fileName -> "static/" + fileName)
                .collect(Collectors.toList());

        files.addAll(partial);
        files.addAll(statics);

        request.attribute("tpls", files);
    } catch (IOException e) {
        log.error("找不到模板路径");
    }
    return "admin/tpl_list";
}
 
Example #5
Source File: TemplateController.java    From tale with MIT License 5 votes vote down vote up
@GetRoute("content")
public void getContent(@Param String fileName, Response response) {
    try {
        String themePath = Const.CLASSPATH + File.separatorChar + "templates" + File.separatorChar + "themes" + File.separatorChar + Commons.site_theme();
        String filePath  = themePath + File.separatorChar + fileName;
        String content   = Files.readAllLines(Paths.get(filePath)).stream().collect(Collectors.joining("\n"));
        response.text(content);
    } catch (IOException e) {
        log.error("获取模板文件失败", e);
    }
}
 
Example #6
Source File: OutputStreamWrapper.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    try {
        this.flush();
        FileChannel file       = new FileInputStream(this.file).getChannel();
        long        fileLength = file.size();

        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        httpResponse.headers().set(HttpConst.CONTENT_LENGTH, fileLength);
        httpResponse.headers().set(HttpConst.DATE, DateKit.gmtDate());
        httpResponse.headers().set(HttpConst.SERVER, "blade/" + Const.VERSION);

        boolean keepAlive = WebContext.request().keepAlive();
        if (keepAlive) {
            httpResponse.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE);
        }

        // Write the initial line and the header.
        ctx.write(httpResponse);
        ctx.write(new DefaultFileRegion(file, 0, fileLength), ctx.newProgressivePromise());
        // Write the end marker.
        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } finally {
        if(null != outputStream){
            outputStream.close();
        }
    }
}
 
Example #7
Source File: HttpServerInitializer.java    From blade with 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 #8
Source File: StaticFileHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private boolean isHttp304(ChannelHandlerContext ctx, Request request, long size, long lastModified) {
    String ifModifiedSince = request.header(HttpConst.IF_MODIFIED_SINCE);

    if (StringKit.isNotEmpty(ifModifiedSince) && httpCacheSeconds > 0) {

        Date ifModifiedSinceDate = format(ifModifiedSince, Const.HTTP_DATE_FORMAT);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        if (ifModifiedSinceDateSeconds == lastModified / 1000) {

            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);

            String contentType = StringKit.mimeType(request.uri());
            if (null != contentType) {
                response.headers().set(HttpConst.CONTENT_TYPE, contentType);
            }

            response.headers().set(HttpConst.DATE, DateKit.gmtDate());
            response.headers().set(HttpConst.CONTENT_LENGTH, size);
            if (request.keepAlive()) {
                response.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE);
            }
            // Close the connection as soon as the error message is sent.
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            return true;
        }
    }
    return false;
}
 
Example #9
Source File: StaticFileHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    var response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));

    response.headers().set(HttpConst.CONTENT_TYPE, Const.CONTENT_TYPE_TEXT);
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #10
Source File: NettyServer.java    From blade with Apache License 2.0 5 votes vote down vote up
/**
 * print blade start banner text
 */
private void printBanner() {
    if (null != blade.bannerText()) {
        System.out.println(blade.bannerText());
    } else {
        String text = Const.BANNER_TEXT + NEW_LINE +
                StringKit.padLeft(" :: Blade :: (v", Const.BANNER_PADDING - 9) + Const.VERSION + ") " + NEW_LINE;
        System.out.println(Ansi.Magenta.format(text));
    }
}
 
Example #11
Source File: EnvironmentWatcher.java    From blade with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    if (Const.CLASSPATH.endsWith(".jar")) {
        return;
    }

    final Path path = Paths.get(Const.CLASSPATH);
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {

        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        // start an infinite loop
        while (true) {
            final WatchKey key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                final WatchEvent.Kind<?> kind = watchEvent.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }
                // get the filename for the event
                final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                final String           filename       = watchEventPath.context().toString();
                // print it out
                if (log.isDebugEnabled()) {
                    log.debug("⬢ {} -> {}", kind, filename);
                }
                if (kind == StandardWatchEventKinds.ENTRY_DELETE &&
                        filename.startsWith(".app") && filename.endsWith(".properties.swp")) {
                    // reload env
                    log.info("⬢ Reload environment");

                    Environment environment = Environment.of("classpath:" + filename.substring(1, filename.length() - 4));
                    WebContext.blade().environment(environment);
                    // notify
                    WebContext.blade().eventManager().fireEvent(EventType.ENVIRONMENT_CHANGED, new Event().attribute("environment", environment));
                }
            }
            // reset the keyf
            boolean valid = key.reset();
            // exit loop if the key is not valid (if the directory was
            // deleted, for
            if (!valid) {
                break;
            }
        }
    } catch (IOException | InterruptedException ex) {
        log.error("Environment watch error", ex);
    }
}
 
Example #12
Source File: BladeKit.java    From blade with Apache License 2.0 4 votes vote down vote up
public static boolean runtimeIsJAR() {
    return Const.CLASSPATH.endsWith(".jar");
}
 
Example #13
Source File: StaticFileHandler.java    From blade with 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 #14
Source File: StaticFileHandler.java    From blade with Apache License 2.0 4 votes vote down vote up
private File getGradleResourcesDirectory() {
    return new File(new File(Const.class.getResource("/").getPath()).getParent() + "/resources");
}
 
Example #15
Source File: EnvironmentTest.java    From blade with Apache License 2.0 4 votes vote down vote up
@Test
public void testNoEnvByFileString() {
    String path = Const.CLASSPATH + "/application.properties";
    Environment.of("file:" + path);
}