Webiyo

This page was generated using Webiyo. See its source code and unit tests.

org/webiyo/examples/viewjava/SourceView.java

package org.webiyo.examples.viewjava;

import org.webiyo.web.HtmlWriter;
import org.webiyo.web.Link;
import org.webiyo.web.Location;
import org.webiyo.web.Renderable;

import java.io.IOException;

import static org.webiyo.web.Att.cssClass;
import static org.webiyo.xml.dtds.Html.A;
import static org.webiyo.xml.dtds.Html.SPAN;
import static org.webiyo.xml.dtds.Html.PRE;
import static org.webiyo.xml.dtds.Html.H2;
import static org.webiyo.xml.dtds.Html.DIV;

public class SourceView implements Renderable {

    private final Source source;
    private final SourceIndex sourceIndex;

    public SourceView(Source source, SourceIndex sourceIndex) {
        this.source = source;
        this.sourceIndex = sourceIndex;
    }

    public void render(HtmlWriter out) throws IOException {
        out.startTag(DIV, cssClass("java-file"));
        out.text(H2, source.getFile().getPath());

        out.startTag(PRE);

        for (Token token : source.getTokens()) {
            renderToken(out, token);
        }

        out.endTag(PRE);

        out.endTag(DIV);
    }

    private void renderToken(HtmlWriter out, Token token) throws IOException {
        Link sourceLink = getSourceLink(token);
        if (sourceLink != null) {
            out.startTag(A, sourceLink);
            renderTokenWithColor(token, out);
            out.endTag(A);
        } else {
            renderTokenWithColor(token, out);
        }
    }

    private Link getSourceLink(Token token) {
        String javaClass = source.getFullClassNameFor(token.getText());
        if (javaClass == null || javaClass.equals(source.getClassName())) return null;

        Location thisPage = ViewJavaLocations.getSourcePageLocation(source.getFile());

        SourceFile otherSourceFile = sourceIndex.getSourceFile(javaClass);
        if (otherSourceFile == null) return null;
        Location otherPage = ViewJavaLocations.getSourcePageLocation(otherSourceFile);
        return otherPage.toRelativeLink(thisPage);
    }

    private void renderTokenWithColor(Token token, HtmlWriter out) throws IOException {
        String cssClass = token.getType().getCssClass();
        if (cssClass != null) {
            out.startTag(SPAN, cssClass(cssClass));
            out.text(token.getText());
            out.endTag(SPAN);
        } else {
            out.text(token.getText());
        }
    }

}
SourceForge