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) 2019, 2021, Oracle and/or its affiliates. All rights reserved. 22 * Portions Copyright (c) 2020, Chris Fraire <cfraire@me.com>. 23 */ 24 package opengrok.auth.plugin.util; 25 26 import jakarta.servlet.http.HttpServletResponse; 27 import jakarta.ws.rs.client.Client; 28 import jakarta.ws.rs.client.ClientBuilder; 29 import jakarta.ws.rs.client.Entity; 30 import jakarta.ws.rs.core.MediaType; 31 import jakarta.ws.rs.core.Response; 32 33 import java.util.logging.Level; 34 import java.util.logging.Logger; 35 36 /** 37 * Simple RESTful client. 38 */ 39 public class RestfulClient { 40 private static final Logger LOGGER = Logger.getLogger(RestfulClient.class.getName()); 41 RestfulClient()42 private RestfulClient() { 43 // private to ensure static 44 } 45 46 /** 47 * Perform HTTP PUT request. 48 * @param uri URI 49 * @param input JSON string contents 50 * @return HTTP status or -1 51 */ postIt(String uri, String input)52 public static int postIt(String uri, String input) { 53 try { 54 Client client = ClientBuilder.newClient(); 55 56 LOGGER.log(Level.FINEST, "sending REST POST request to {0}: {1}", 57 new Object[]{uri, input}); 58 Response response = client.target(uri) 59 .request(MediaType.APPLICATION_JSON) 60 .post(Entity.entity(input, MediaType.APPLICATION_JSON)); 61 62 int status = response.getStatus(); 63 if (status != HttpServletResponse.SC_CREATED) { 64 LOGGER.log(Level.WARNING, "REST request failed: HTTP error code : {0}", status); 65 } 66 67 return status; 68 } catch (Exception e) { 69 LOGGER.log(Level.WARNING, "REST request failed", e); 70 return -1; 71 } 72 } 73 } 74