Best practices for building containers
This page lists online resources covering key concepts about how to build containers which are more efficient and secured
<!-- swagger ui -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.10</version>
</dependency>
http://localhost:8080/swagger-ui/index.html
{
"openapi":"3.0.1",
"info":{
"title":"OpenAPI definition",
"version":"v0"
},
"servers":[
{
"url":"http://localhost:8080",
"description":"Generated server url"
}
],
"paths":{
"/blogapi/v2/blogs":{
"get":{
"tags":[
"blog-controller-v-2"
],
"operationId":"getBlogStories",
"responses":{
"200":{
"description":"OK",
"content":{
"application/json":{
"schema":{
"type":"array",
"items":{
"$ref":"#/components/schemas/BlogStory"
}
}
}
}
}
}
},
"post":{
"tags":[
"blog-controller-v-2"
],
"operationId":"addBlogStory",
"requestBody":{
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/BlogStory"
}
}
},
"required":true
},
"responses":{
"200":{
"description":"OK",
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/BlogStory"
}
}
}
}
}
}
},
"/blogapi/v1/categories":{
"get":{
"tags":[
"category-controller"
],
"operationId":"getBlogCats",
"responses":{
"200":{
"description":"OK",
"content":{
"application/json":{
"schema":{
"type":"array",
"items":{
"$ref":"#/components/schemas/BlogCategory"
}
}
}
}
}
}
},
"post":{
"tags":[
"category-controller"
],
"operationId":"addCats",
"requestBody":{
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/BlogCategory"
}
}
},
"required":true
},
"responses":{
"200":{
"description":"OK",
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/BlogCategory"
}
}
}
}
}
}
},
"/blogapi/v2/blogs/{id}":{
"get":{
"tags":[
"blog-controller-v-2"
],
"operationId":"getBlogStory",
"parameters":[
{
"name":"id",
"in":"path",
"required":true,
"schema":{
"type":"string"
}
}
],
"responses":{
"200":{
"description":"OK",
"content":{
"application/json":{
"schema":{
"$ref":"#/components/schemas/BlogStory"
}
}
}
}
}
}
}
},
"components":{
"schemas":{
"BlogStory":{
"type":"object",
"properties":{
"id":{
"type":"string"
},
"name":{
"type":"string"
},
"summary":{
"type":"string"
},
"description":{
"type":"string"
},
"category":{
"type":"string"
}
}
},
"BlogCategory":{
"type":"object",
"properties":{
"id":{
"type":"string"
},
"name":{
"type":"string"
}
}
}
}
}
}
@Entity
@Table (name = "dish_table")
public class Dish {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Long id;
@NotNull
@Size(min=2, message="Name should have atleast 5 characters")
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "lowprice")
private Double lowPrice;
@Column(name = "highprice")
private Double highPrice;
public Dish () {}
//Getter and Setters
}
@Repository
public interface DishRepository extends JpaRepository {
public Page findByName(String name, Pageable pageable);
}
@RestController
@RequestMapping("api/v2")
public class DishControllerPaginatedV2 {
private static final int pageSize = 2;
@Autowired
DishRepository repo;
@GetMapping(value="/dishes",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity> getDish3(@RequestParam (defaultValue = "0") int pageNo) throws Exception {
Sort sort = Sort.by("name");
Pageable pageReq = PageRequest.of(pageNo, pageSize, sort);
Page result = repo.findAll(pageReq);
return ResponseEntity.ok(result);
}
}
curl --request GET \
--url 'http://localhost:8080/api/v1/dishes3?pageNo=0' \
--header 'cache-control: no-cache'
{
"content": [
{
"id": 12,
"name": "Anchovies",
"description": "Anchovies",
"lowPrice": 1987,
"highPrice": 0
},
{
"id": 14,
"name": "Celery",
"description": "Celery",
"lowPrice": 2928,
"highPrice": 0
}
],
"pageable": {
"sort": {
"sorted": true,
"unsorted": false,
"empty": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 2,
"paged": true,
"unpaged": false
},
"last": false,
"totalPages": 7,
"totalElements": 14,
"size": 2,
"number": 0,
"sort": {
"sorted": true,
"unsorted": false,
"empty": false
},
"numberOfElements": 2,
"first": true,
"empty": false
}
public class JakartaRestfulApp extends Application {
private final Set> classes;
public JakartaRestfulApp() {
HashSet> c = new HashSet>();
c.add(MenuResource.class);
classes = Collections.unmodifiableSet(c);
}
@Override
public Set> getClasses() {
return classes;
}
}
@Path("/rest")
public class MenuResource {
MenuService service = MenuService.getInstance();
@GET
@Path("/menus")
@Produces("application/json")
public List
public class MenuService {
private static MenuService instance = new MenuService();
private static HashSet
public class Menu {
private Long id;
private String name;
public Menu() {
}
public Menu(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class JDKSEServer {
private static final Logger LOGGER = Logger.getLogger(JDKSEServer.class.getName());
/**
* Starts the JDK HTTP server serving the JAX-RS application.
*/
static HttpServer startServer() throws IOException {
ResourceConfig config = new ResourceConfig(MenuResource.class);
HttpServer server = JdkHttpServerFactory.createHttpServer(getBaseURI(), config);
return server;
}
public static void main(String[] args) {
try {
final HttpServer httpServer = startServer();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
LOGGER.info("Shutting down the application...");
httpServer.stop(0);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, null, e);
}
}));
LOGGER.info("Application started.%nStop the application using CTRL+C");
Thread.currentThread().join();
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
/**
* Gets base {@link URI}.
*/
public static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(8080).build();
}
}
public class TestMenuResource extends JerseyTest {
@BeforeEach
void init() throws Exception {
super.setUp();
}
@Override
protected Application configure() {
//to start a new container in s different port
forceSet(TestProperties.CONTAINER_PORT, "0");
return new ResourceConfig(MenuResource.class);
}
@Test
public void get_one() throws Exception {
Response response = target("/rest/menus/1").request().get();
System.out.println("sd " + response.getStatus());
assertEquals(response.getStatus(), 200);
assertEquals(response.readEntity(Menu.class).getName(), "Menu One");
}
protected TestContainerFactory getTestContainerFactory() {
return new JdkHttpServerTestContainerFactory();
}
}
TreeMap<Integer, String> map = new TreeMap<> ();
map.put(15, "banana");
map.put(16, "apple");
key = map.lowerKey(16);
test = map.lowerEntry(16);
System.out.println(key); //15
System.out.println(test); //banana
key = map.floorKey(16);
test = map.floorEntry(16);
System.out.println(key); //16
System.out.println(test); //apple
key = map.higherKey(14);
test = map.higherEntry(14);
System.out.println(key); //15
System.out.println(test); //banana
key = map.ceilingKey(16);
test = map.ceilingEntry(16);
System.out.println(key); //16
System.out.println(test.getValue()); //apple
public class MonotonicArray {
public boolean isMonotonic(int[] nums) {
int signal = -1; // -1 = not set, 0 = increasing, 1 = decreasing
// iterate over the array till the arry.length-1 from 0
for (int i = 0; i < nums.length - 1; i++) {
// if signal is not initialized and we see either increasing or decreasing array
// initialize it accordingly
if (signal == -1) {
if (nums[i] < nums[i + 1]) {
signal = 0; // increasing
} else if (nums[i] > nums[i + 1]) {
signal = 1; // decreasing
}
} else {
// once the signal is already initialized
// then check if for other elements it holds true or not
if (signal == 0 && nums[i] > nums[i + 1]) {
return false;
}
if (signal == 1 && nums[i] < nums[i + 1]) {
return false;
}
}
}
return true;
}
}
byte rollNums1[] = new byte[10];
short rollNums2[] = new short[10];
int rollNums3[] = new int[10];
long rollNums4[] = new long[10];
float rollNums5[] = new float[10];
double rollNums6[] = new double[10];
char rollNums7[] = new char[10];
boolean rollNums8[] = new boolean[10];
Integer rollNums9[] = new Integer[10];
byte rollNums1[] = new byte[10];
System.out.println("\nbyte array");
for (byte i : rollNums1) {
System.out.print(i + ", ");
}
short rollNums2[] = new short[10];
System.out.println("\nshort array");
for (short i : rollNums2) {
System.out.print(i + ", ");
}
int rollNums3[] = new int[10];
System.out.println("\nint array");
for (int i : rollNums3) {
System.out.print(i + ", ");
}
long rollNums4[] = new long[10];
System.out.println("\nlong array");
for (long i : rollNums4) {
System.out.print(i + ", ");
}
float rollNums5[] = new float[10];
System.out.println("\nfloat array");
for (float i : rollNums5) {
System.out.print(i + ", ");
}
double rollNums6[] = new double[10];
System.out.println("\ndouble array");
for (double i : rollNums6) {
System.out.print(i + ", ");
}
char rollNums7[] = new char[10];
System.out.println("\nchar array");
for (char i : rollNums7) {
System.out.print(i + ", ");
}
boolean rollNums8[] = new boolean[10];
System.out.println("\nboolean array");
for (boolean i : rollNums8) {
System.out.print(i + ", ");
}
Integer rollNums9[] = new Integer[10];
System.out.println("\nInteger array");
for (Integer i : rollNums9) {
System.out.print(i + ", ");
}
//initialize array of size 10 of type int
int rollNums[] = new int[10];
//iterate from 0 to the last index of the array and set values
for (int i = 0; i < rollNums.length; i++) {
rollNums[i] = i + 1;
}
int rollNums[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rollNums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rollNums[] = new int[10];
Arrays.setAll(rollNums, p -> p + 1);
int rollNums[] = new int[10];
Arrays.setAll(rollNums, new IntUnaryOperator () {
@Override
public int applyAsInt(int operand) {
return operand + 1;
}} );
int rollNums2[] = Arrays.copyOf(rollNums, rollNums.length);