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    
015    package org.apache.tapestry5.internal.plastic;
016    
017    import org.apache.tapestry5.internal.plastic.asm.Label;
018    import org.apache.tapestry5.plastic.InstructionBuilder;
019    import org.apache.tapestry5.plastic.InstructionBuilderCallback;
020    import org.apache.tapestry5.plastic.TryCatchBlock;
021    import org.apache.tapestry5.plastic.TryCatchCallback;
022    
023    public 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        public void addTry(InstructionBuilderCallback callback)
041        {
042            state.visitor.visitLabel(startLabel);
043    
044            callback.doBuild(builder);
045    
046            state.visitor.visitLabel(endLabel);
047        }
048    
049        public void addCatch(String exceptionClassName, InstructionBuilderCallback callback)
050        {
051            assert exceptionClassName != null;
052    
053            doCatch(state.nameCache.toInternalName(exceptionClassName), callback);
054        }
055    
056        private void doCatch(String exceptionInternalName, InstructionBuilderCallback callback)
057        {
058            check();
059    
060            Label handler = state.newLabel();
061    
062            callback.doBuild(builder);
063    
064            state.visitor.visitTryCatchBlock(startLabel, endLabel, handler, exceptionInternalName);
065        }
066    
067        public void addFinally(InstructionBuilderCallback callback)
068        {
069            doCatch(null, callback);
070        }
071    
072        void doCallback(TryCatchCallback callback)
073        {
074            assert callback != null;
075    
076            callback.doBlock(this);
077    
078            lock();
079        }
080    
081    }