001package io.avaje.http.generator.core;
002
003import javax.lang.model.element.TypeElement;
004import javax.tools.JavaFileObject;
005import java.io.IOException;
006import java.io.Writer;
007
008/**
009 * Common controller writer.
010 */
011public abstract class BaseControllerWriter {
012
013  protected final ControllerReader reader;
014  protected final ProcessingContext ctx;
015  protected final String originName;
016  protected final String shortName;
017  protected final String fullName;
018  protected final String packageName;
019  protected Append writer;
020
021  public BaseControllerWriter(ControllerReader reader, ProcessingContext ctx) throws IOException {
022    this.reader = reader;
023    this.ctx = ctx;
024    TypeElement origin = reader.getBeanType();
025    this.originName = origin.getQualifiedName().toString();
026    this.shortName = origin.getSimpleName().toString();
027    this.fullName = originName + "$route";
028    this.packageName = initPackageName(originName);
029
030    initWriter();
031  }
032
033  protected boolean isRequestScoped() {
034    return reader.isRequestScoped();
035  }
036
037  protected String initPackageName(String originName) {
038    int dp = originName.lastIndexOf('.');
039    return dp > -1 ? originName.substring(0, dp) : null;
040  }
041
042  protected void initWriter() throws IOException {
043    writer = new Append(createFileWriter());
044  }
045
046  protected Writer createFileWriter() throws IOException {
047    JavaFileObject jfo = ctx.createWriter(fullName, reader.getBeanType());
048    return jfo.openWriter();
049  }
050
051  protected void writePackage() {
052    if (packageName != null) {
053      writer.append("package %s;", packageName).eol().eol();
054    }
055  }
056
057  protected void writeImports() {
058    writer.append(Constants.IMPORT_PATH_TYPE_CONVERT).eol();
059    for (String type : reader.getStaticImportTypes()) {
060      writer.append("import static %s;", type).eol();
061    }
062    writer.eol();
063    for (String type : reader.getImportTypes()) {
064      writer.append("import %s;", type).eol();
065    }
066    writer.eol();
067  }
068
069  protected void writeClassEnd() {
070    writer.append("}").eol();
071    writer.close();
072  }
073}