001/*
002 * (C) Copyright 2006-2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.runtime.test.runner;
020
021import java.io.IOException;
022import java.lang.reflect.Field;
023import java.net.ServerSocket;
024
025import org.apache.logging.log4j.LogManager;
026import org.apache.logging.log4j.Logger;
027import org.nuxeo.runtime.server.ServerComponent;
028
029import sun.net.www.http.HttpClient;
030
031/**
032 * Runs an embedded servlet container.
033 * <p>
034 * Note that at initialization the feature disables the {@code retryPostProp} property of
035 * {@link sun.net.www.http.HttpClient}, the underlying HTTP client used by {@link com.sun.jersey.api.client.Client}.
036 * <p>
037 * This is to prevent the JDK's default behavior kept for backward compatibility: an unsuccessful HTTP POST request is
038 * automatically resent to the server, unsuccessful in this case meaning the server did not send a valid HTTP response
039 * or an {@code IOException} occurred. Yet in the tests using the Jersey client to make calls to Nuxeo we don't want
040 * this as it can hide errors occurring in the HTTP communication that should prevent an appropriate response from being
041 * sent by the server.
042 */
043@Deploy("org.nuxeo.runtime.server")
044@Features(RuntimeFeature.class)
045public class ServletContainerFeature implements RunnerFeature {
046
047    private static final Logger log = LogManager.getLogger(ServletContainerFeature.class);
048
049    protected static final int RETRIES = 1000;
050
051    protected int port;
052
053    @SuppressWarnings("deprecation")
054    @Override
055    public void initialize(FeaturesRunner runner) throws Exception {
056        disableSunHttpClientRetryPostProp();
057
058        ServletContainer conf = runner.getConfig(ServletContainer.class);
059        int port = conf == null ? 0 : conf.port();
060        if (port <= 0) {
061            port = findFreePort();
062        }
063        this.port = port;
064        System.setProperty(ServerComponent.PORT_SYSTEM_PROP, String.valueOf(port));
065    }
066
067    protected int findFreePort() {
068        for (int i = 0; i < RETRIES; i++) {
069            try (ServerSocket socket = new ServerSocket(0)) {
070                socket.setReuseAddress(true);
071                return socket.getLocalPort();
072            } catch (IOException e) {
073                log.trace("Failed to allocate port", e);
074            }
075        }
076        throw new RuntimeException("Unable to find free port after " + RETRIES + " retries");
077    }
078
079    /**
080     * Returns the port allocated for this servlet container.
081     *
082     * @since 10.10
083     */
084    public int getPort() {
085        return port;
086    }
087
088    /**
089     * Prevents the JDK's default behavior of resending an unsuccessful HTTP POST request automatically to the server by
090     * disabling the the {@code retryPostProp} property of {@link sun.net.www.http.HttpClient}.
091     * <p>
092     * This can also be achieved by setting the {@code sun.net.http.retryPost} system property to {@code false}.
093     *
094     * @since 9.3
095     */
096    public static void disableSunHttpClientRetryPostProp()
097            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
098        Field field = HttpClient.class.getDeclaredField("retryPostProp");
099        field.setAccessible(true);
100        field.setBoolean(null, false);
101    }
102
103}