/*
 * Copyright 2016-2018 shardingsphere.io.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package io.shardingsphere.core.parsing.antlr.extractor.statement.type;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.antlr.v4.runtime.ParserRuleContext;

import io.shardingsphere.core.metadata.table.ShardingTableMetaData;
import io.shardingsphere.core.parsing.antlr.extractor.SQLStatementExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.statement.handler.ASTExtractHandler;
import io.shardingsphere.core.parsing.antlr.extractor.statement.handler.result.ExtractResult;
import io.shardingsphere.core.parsing.parser.sql.SQLStatement;

/**
 * Abstract SQL statement extractor.
 * 
 * @author duhongjun
 */
public abstract class AbstractSQLStatementExtractor implements SQLStatementExtractor {
    
    private final Collection<ASTExtractHandler> extractHandlers = new LinkedList<>();
    
    @Override
    public final SQLStatement extract(final ParserRuleContext rootNode, final ShardingTableMetaData shardingTableMetaData) {
        SQLStatement result = createStatement(shardingTableMetaData);
        List<ExtractResult> extractResults = new LinkedList<>();
        for (ASTExtractHandler each : extractHandlers) {
            ExtractResult extractResult = each.extract(rootNode);
            if (null != extractResult) {
                extractResults.add(extractResult);
            }
        }
        
        for (ExtractResult each : extractResults) {
            each.inject(result);
        }
        postExtract(result);
        return result;
    }
    
    protected abstract SQLStatement createStatement(ShardingTableMetaData shardingTableMetaData);
    
    protected void postExtract(final SQLStatement statement) {
    }
    
    protected final void addExtractHandler(final ASTExtractHandler handler) {
        extractHandlers.add(handler);
    }
}

@@ -811,24 +811,65 @@
 leContext;%0A%0A
+import com.google.common.base.Optional;%0A%0A
 import io.sh
@@ -1846,16 +1846,25 @@
         
+Optional%3C
 ExtractR
@@ -1868,16 +1868,17 @@
 ctResult
+%3E
  extract
@@ -1930,16 +1930,8 @@
 if (
-null != 
 extr
@@ -1939,16 +1939,28 @@
 ctResult
+.isPresent()
 ) %7B%0A    
@@ -1999,24 +1999,30 @@
 xtractResult
+.get()
 );%0A         
@@ -2040,17 +2040,8 @@
   %7D%0A
-        %0A
     
@@ -2109,14 +2109,12 @@
 ach.
-inject
+fill
 (res

use optional for checkstyle