package org.jano.zuss;
import fi.iki.elonen.NanoHTTPD;
import org.jano.JanoPlugin;
import org.jano.MimeType;
import org.jano.Reply;
import org.jano.resources.ResourceRef;
import org.jano.resources.ResourceSystem;
import org.zkoss.zuss.Locator;
import org.zkoss.zuss.Resolver;
import org.zkoss.zuss.impl.in.Parser;
import org.zkoss.zuss.impl.out.Translator;
import org.zkoss.zuss.metainfo.ZussDefinition;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Method;
public class ZussPlugin implements JanoPlugin {
private static final String ZUSS_EXTENSION = ".zuss";
@Override
public boolean canServe(String uri, NanoHTTPD.Method method) {
return uri.toLowerCase().endsWith(ZUSS_EXTENSION) && method == NanoHTTPD.Method.GET;
}
@Override
public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session, ResourceSystem resourceSystem) throws Exception {
String uri = session.getUri();
ResourceRef ref = resourceSystem.get(uri);
Locator locator = createLocator(ref.parent());
String initName = ref.name();
//parse file into definition
ZussDefinition definition = new Parser(locator.getResource(initName), locator, initName).parse();
//translate into CSS
StringWriter buffer = new StringWriter();
new Translator(definition, buffer, dummyResolver).translate();
//send result back
return Reply.with(NanoHTTPD.Response.Status.OK, MimeType.CSS, buffer.toString());
}
private Locator createLocator(final ResourceRef base) {
return new Locator() {
@Override
public Reader getResource(String name) throws IOException {
Reader reader = new InputStreamReader(base.child(name).inputStream());
return reader;
}
};
}
private final Resolver dummyResolver = new Resolver() {
@Override
public Object getVariable(String name) {
return null;
}
@Override
public Method getMethod(String name) {
return null;
}
};
}