1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * See LICENSE.txt included in this distribution for the specific 9 * language governing permissions and limitations under the License. 10 * 11 * When distributing Covered Code, include this CDDL HEADER in each 12 * file and include the License file at LICENSE.txt. 13 * If applicable, add the following below this CDDL HEADER, with the 14 * fields enclosed by brackets "[]" replaced with your own identifying 15 * information: Portions Copyright [yyyy] [name of copyright owner] 16 * 17 * CDDL HEADER END 18 */ 19 20 /* 21 * Copyright (c) 2020, Chris Fraire <cfraire@me.com>. 22 */ 23 package org.opengrok.web.api.v1.controller; 24 25 import org.glassfish.jersey.test.JerseyTest; 26 import org.glassfish.jersey.test.TestProperties; 27 import org.junit.jupiter.api.AfterEach; 28 import org.junit.jupiter.api.BeforeEach; 29 30 import java.util.Random; 31 32 /** 33 * Represents a subclass of {@link JerseyTest} customized for OpenGrok. 34 */ 35 public abstract class OGKJerseyTest extends JerseyTest { 36 37 private static final int BASE_DYNAMIC_OR_PRIVATE_PORT = 49152; 38 39 /** Random.nextInt() will be at most one less than this -- but OK. */ 40 private static final int DYNAMIC_OR_PRIVATE_PORT_RANGE = 16383; 41 42 private static final int MAX_PORT_TRIES = 20; 43 44 private final Random rand = new Random(); 45 46 /** 47 * Marshal a random high port through {@link TestProperties#CONTAINER_PORT} 48 * for use by {@link #getPort()}. 49 */ 50 @BeforeEach setUp()51 public void setUp() throws Exception { 52 53 int triesCount = 0; 54 while (true) { 55 int jerseyPort = BASE_DYNAMIC_OR_PRIVATE_PORT + 56 rand.nextInt(DYNAMIC_OR_PRIVATE_PORT_RANGE); 57 if (PortChecker.available(jerseyPort)) { 58 forceSet(TestProperties.CONTAINER_PORT, String.valueOf(jerseyPort)); 59 break; 60 } 61 if (++triesCount > MAX_PORT_TRIES) { 62 throw new RuntimeException("Could not find an available port after " + 63 MAX_PORT_TRIES + " tries"); 64 } 65 } 66 67 super.setUp(); 68 } 69 70 @AfterEach tearDown()71 public void tearDown() throws Exception { 72 super.tearDown(); 73 } 74 } 75