001
002package ca.uhn.fhir.test.utilities;
003
004/*-
005 * #%L
006 * HAPI FHIR Test Utilities
007 * %%
008 * Copyright (C) 2014 - 2023 Smile CDR, Inc.
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * #L%
022 */
023
024import org.eclipse.jetty.server.Connector;
025import org.eclipse.jetty.server.Server;
026import org.eclipse.jetty.server.ServerConnector;
027import org.eclipse.jetty.server.handler.StatisticsHandler;
028import org.slf4j.Logger;
029import org.slf4j.LoggerFactory;
030
031import javax.annotation.Nonnull;
032import javax.annotation.Nullable;
033
034public class JettyUtil {
035    
036    /**
037     * Gets the local port for the given server. The server must be started.
038     */
039    public static int getPortForStartedServer(Server server) {
040        assert server.isStarted();
041        Connector[] connectors = server.getConnectors();
042        assert connectors.length == 1;
043        return ((ServerConnector) (connectors[0])).getLocalPort();
044    }
045    
046    /**
047     * Starts the given Jetty server, and configures it for graceful shutdown
048     */
049    public static void startServer(@Nonnull Server theServer) throws Exception {
050        //Needed for graceful shutdown, see https://github.com/eclipse/jetty.project/issues/2076#issuecomment-353717761
051        theServer.insertHandler(new StatisticsHandler());
052        theServer.start();
053    }
054    
055    /**
056     * Shut down the given Jetty server, and release held resources.
057     */
058    public static void closeServer(@Nullable Server theServer) throws Exception {
059        if (theServer != null) {
060                        theServer.stop();
061                        theServer.destroy();
062                }
063    }
064    
065}