    001// Copyright 2011 The Apache Software Foundation
    002//
    003// Licensed under the Apache License, Version 2.0 (the "License");
    004// you may not use this file except in compliance with the License.
    005// You may obtain a copy of the License at
    006//
    007// http://www.apache.org/licenses/LICENSE-2.0
    008//
    009// Unless required by applicable law or agreed to in writing, software
    010// distributed under the License is distributed on an "AS IS" BASIS,
    011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    012// See the License for the specific language governing permissions and
    013// limitations under the License.
    014
    015package org.apache.tapestry5.internal.plastic;
    016
    017import org.apache.tapestry5.internal.plastic.asm.Label;
    018import org.apache.tapestry5.plastic.InstructionBuilder;
    019import org.apache.tapestry5.plastic.InstructionBuilderCallback;
    020import org.apache.tapestry5.plastic.TryCatchBlock;
    021import org.apache.tapestry5.plastic.TryCatchCallback;
    022
    023public class TryCatchBlockImpl extends Lockable implements TryCatchBlock
    024{
    025    private final InstructionBuilder builder;
    026
    027    private final InstructionBuilderState state;
    028
    029    private final Label startLabel, endLabel;
    030
    031    TryCatchBlockImpl(InstructionBuilder builder, InstructionBuilderState state)
    032    {
    033        this.builder = builder;
    034        this.state = state;
    035
    036        this.startLabel = new Label();
    037        this.endLabel = new Label();
    038    }
    039
    040    @Override
    041    public void addTry(InstructionBuilderCallback callback)
    042    {
    043        state.visitor.visitLabel(startLabel);
    044
    045        callback.doBuild(builder);
    046
    047        state.visitor.visitLabel(endLabel);
    048    }
    049
    050    @Override
    051    public void addCatch(String exceptionClassName, InstructionBuilderCallback callback)
    052    {
    053        assert exceptionClassName != null;
    054
    055        doCatch(state.nameCache.toInternalName(exceptionClassName), callback);
    056    }
    057
    058    private void doCatch(String exceptionInternalName, InstructionBuilderCallback callback)
    059    {
    060        check();
    061
    062        Label handler = state.newLabel();
    063
    064        callback.doBuild(builder);
    065
    066        state.visitor.visitTryCatchBlock(startLabel, endLabel, handler, exceptionInternalName);
    067    }
    068
    069    @Override
    070    public void addFinally(InstructionBuilderCallback callback)
    071    {
    072        doCatch(null, callback);
    073    }
    074
    075    void doCallback(TryCatchCallback callback)
    076    {
    077        assert callback != null;
    078
    079        callback.doBlock(this);
    080
    081        lock();
    082    }
    083
    084}