All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.yoojia.halo.PublicAssets Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.github.yoojia.halo;

import com.github.yoojia.halo.supports.*;
import com.github.yoojia.halo.utils.SystemTime;
import com.google.common.collect.Lists;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author YOOJIA.CHEN ([email protected])
 */
public final class PublicAssets extends HaloModule {

    private static final String DIR = "/resources";

    private final List mAssertsMapper = Lists.newArrayList();

    private Context mContext;

    @Override
    public void init(Context context, Config pluginConfig) {
        mLogger.debug("Init...");
        mContext = context;
        final long start = System.nanoTime();
        final List list = pluginConfig.getTypedList("uriMapping");
        for (String prefix : list) {
            prefix = prefix.endsWith("/*") ? prefix : (prefix + "/*");
            mLogger.trace("Config: AccessLevel=Public, Dir={}", prefix);
            mAssertsMapper.add(Mapper.format(prefix));
        }
        SystemTime.log(start, "PublicAssets.init");
    }

    @Override
    public void onService(HaloRequest request, HaloResponse response, KernelChain chain) throws Exception {
        final Mapper mapper = find(request);
        if(mapper == null){
            chain.onService(request, response, chain);
            return;
        }
        final long start = System.nanoTime();
        try{
            final Path local = mContext.resolve(Paths.get(DIR,request.uri));
            mLogger.trace("Mapped Uri: {} to Resource: {}", request.uri, local);
            response.setStatusCode(StatusCode.OK);
            if (Files.exists(local)){
                response.setContentType(request.servletContext.getMimeType(local.toString()));
                AssetsTransferAdapter.use(local).dispatch(request, response);
            }else{
                response.setStatusCode(StatusCode.NOT_FOUND);
                mLogger.trace("Resource NOT FOUND: {}", local);
            }
        }finally {
            SystemTime.log(start, String.format("PublicAssets.send(:%s)", request.uri));
        }
    }

    private Mapper find(HaloRequest request){
        for (Mapper mapper : mAssertsMapper) {
            if (mapper.isMatched(request.resources)) {
                return mapper;
            }
        }
        return null;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy