/*
 * Copyright (c) 2014-2017 Globo.com - ATeam
 * All rights reserved.
 *
 * This source is subject to the Apache License, Version 2.0.
 * Please see the LICENSE file for more information.
 *
 * Authors: See AUTHORS file
 *
 * 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.
 */

package io.galeb.router.handlers.completionListeners;

import io.undertow.attribute.ResponseTimeAttribute;
import io.undertow.util.HeaderMap;
import io.undertow.util.StatusCodes;

import java.util.concurrent.TimeUnit;

import static io.galeb.router.ResponseCodeOnError.Header.X_GALEB_ERROR;

abstract class ProcessorLocalStatusCode {

    static final int NOT_MODIFIED = 0;

    private static final String UNKNOWN_TARGET  = "UNKNOWN";
    private static final int OFFSET_LOCAL_ERROR = 400;

    final ResponseTimeAttribute responseTimeAttribute = new ResponseTimeAttribute(TimeUnit.MILLISECONDS);

    int getFakeStatusCode(final String backend,
                          int statusCode,
                          long responseBytesSent,
                          Integer responseTime,
                          int maxRequestTime) {
        int statusLogged = NOT_MODIFIED;
        if (responseTime != null &&
                statusCode == StatusCodes.OK &&
                responseBytesSent <= 0 &&
                maxRequestTime > 0 &&
                responseTime > maxRequestTime) {

            statusLogged = StatusCodes.BAD_GATEWAY + OFFSET_LOCAL_ERROR;

        } else if (backend == null) {

            statusLogged = statusCode + OFFSET_LOCAL_ERROR;

        }

        return statusLogged;
    }

    String extractUpstreamField(final HeaderMap responseHeaders, String tempRealDest) {
        final String headerGalebError = responseHeaders != null ? responseHeaders.getFirst(X_GALEB_ERROR) : null;
        return tempRealDest != null ? tempRealDest : (headerGalebError != null ? headerGalebError : UNKNOWN_TARGET);
    }
}

@@ -1742,25 +1742,24 @@
  == null) %7B%0A
-%0A
             
@@ -1798,33 +1798,32 @@
 ET_LOCAL_ERROR;%0A
-%0A
         %7D%0A%0A     
@@ -1937,24 +1937,110 @@
 RealDest) %7B%0A
+        String upstreamField = tempRealDest;%0A        if (upstreamField == null) %7B%0A    
         fina
@@ -2153,54 +2153,28 @@
     
-return tempRealDest != null ? tempRealDest : (
+    upstreamField = 
 head
@@ -2229,17 +2229,56 @@
 N_TARGET
-)
+;%0A        %7D%0A        return upstreamField
 ;%0A    %7D%0A

Improve performance