import{CodeBuilder as C}from"../../helpers/code-builder.js";import{HTTPSnippet as j}from"../../index.js";import{normalizeMimeType as l}from"../../../../utils.js";import{addIndentation as O,buildUrlExpression as S,printUrlVariablesDeclarations as T}from"../../helpers/code-helpers.js";import{Lang as x}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";import{buildJavaDeviceAuthorizationCodeSnippet as E}from"../../helpers/device-auth-snippets.js";const h=a=>!!(a.uriObj.query&&Object.keys(a.uriObj.query).length),b=a=>a.postData&&a.postData.mimeType===i.URL_ENCODED?"HttpRequest.BodyPublishers.ofString(form)":!a.postData?.params?.length&&a.postData?.text&&l(a.postData.mimeType)===i.MULTIPART?"body":a.postData?"HttpRequest.BodyPublishers.ofString(payload)":["POST","PUT","PATCH"].includes(a.method.toUpperCase())?'HttpRequest.BodyPublishers.ofString("some body text")':"",A=function(a,s,{target:y,client:g}){const n=Object.assign({indent:"  ",withWrapper:!0},s),t=new C({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:x.JAVA});if(n.withComments&&R(t,a),n.withImports&&B(t,a),n.withWrapper&&(t.push("public class App {"),t.push(1,"public static void main(String[] args) throws Exception {"),t.push(2,"var httpClient = HttpClient.newBuilder().build();"),t.blank()),a.securityOAuth2ExtraCalls?.length){const e=a.securityOAuth2ExtraCalls?.[0],p=new j(e).convert(y,g,{...n,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(p),t.blank(),t.push(2,"var oauth2Response = httpClient.send(oauth2Request, HttpResponse.BodyHandlers.ofString());"),e.flowType==="deviceAuthorization"?E(t,{tokenUrl:e.tokenUrl??"YOUR_TOKEN_URL",clientId:e.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,'var accessToken = new JSONObject(oauth2Response.body()).getString("access_token");'),t.blank())}if(a.postData)switch(l(a.postData.mimeType)){case i.URL_ENCODED:a.postData.params.length?(t.push(2,"HashMap<String, String> params = new HashMap<>();"),a.postData.params.forEach(e=>{t.push(2,'params.put("%s", "%s");',e.name,e.value)}),t.blank(),t.push(2,"var form = params.keySet().stream()"),t.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),t.push(3,'.collect(Collectors.joining("&"));'),t.blank()):a.postData.text&&(t.push(2,'var form = "%s";',a.postData.text),t.blank());break;case i.JSON:a.postData.jsonObj&&(t.push(2,`var payload = String.join("\\n"
      ${O(JSON.stringify(a.postData.jsonObj,null,1).replace(/"/g,'\\"').replace(/^/gm,', "').replace(/$/gm,'"'),{level:3,indent:n.indent,firstLine:!1})}`),t.push(2,");"),t.blank());break;case i.XML:a.postData.text&&(t.push(2,'var payload = String.join("\\n"'),a.postData.text.trim().split(`
`).forEach(e=>{const p=e.replace(/"/g,'\\"');t.push(3,`"${p}", `)}),t.push(2,");"),t.blank());break;case i.OCTET_STREAM:a.postData.text&&(t.push(2,'var payload = "%s";',a.postData.text),t.blank());break;case i.MULTIPART:if(a.postData.params&&a.postData.params.length>0)t.push(2,"var multipartBody = MultipartBodyPublisher.newBuilder();"),a.postData.params.forEach(e=>{e.fileName?t.push(2,'multipartBody.append("%s", Path.of("%s"));',e.name,e.fileName):t.push(2,'multipartBody.append("%s", "%s");',e.name,e.value)}),t.push(2,"var body = multipartBody.build();"),t.blank();else if(a.postData.text){const e=a.postData.text,p=e.match(/^--([^\r\n]+)/);if(p){const c=p[1],D=e.split(new RegExp(`--${c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(r=>r.trim().length>0);t.push(2,"var multipartBody = MultipartBodyPublisher.newBuilder();"),D.forEach(r=>{const o=r.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(o){const m=o[1],d=o[2],f=r.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),k=(f?f[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');d?t.push(2,'multipartBody.append("%s", Path.of("%s"));',m,d):t.push(2,'multipartBody.append("%s", "%s");',m,k)}}),t.push(2,"var body = multipartBody.build();"),t.blank()}else t.push(2,'var payload = "%s";',a.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"')),t.blank()}break}if(h(a)){t.push(2,"HashMap<String, String> params = new HashMap<>();");for(const[e,p]of Object.entries(a.uriObj.query))t.push(2,'params.put("%s", "%s");',e,p);t.blank(),t.push(2,"var query = params.keySet().stream()"),t.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),t.push(3,'.collect(Collectors.joining("&"));'),t.blank()}t.push(2,`var ${t.var("host")} = "%s";`,a.uriObj.protocol+"//"+a.uriObj.host),T(a,t,2);const v={...a,pathname:a.uriObj.pathname};t.push(2,`var ${t.var("pathname")} = %s;`,S(v,t)),t.push(2,`var ${t.var("request")} = HttpRequest.newBuilder()`),a.method.toUpperCase()==="PATCH"?t.push(3,'.method("PATCH", %s)',b(a)):t.push(3,".%s(%s)",a.method.toUpperCase(),b(a)),t.push(3,`.uri(URI.create(${t.var("host")} + ${t.var("pathname")} %s))`,h(a)?"+ '?' + query":""),a.securityOAuth2ExtraCalls?.length&&(a.allHeaders.Authorization='"Bearer " + accessToken');const u=Object.keys(a.allHeaders);if(u.length&&u.forEach(e=>{t.push(3,'.header("%s", %s)',e,e==="Authorization"&&a.securityOAuth2ExtraCalls?.length?a.allHeaders[e]:`"${a.allHeaders[e]}"`)}),a.basicAuth){const{username:e,password:p}=a.basicAuth;t.push(3,`.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("${e}:${p}").getBytes()))`)}return t.push(3,".build();"),n.withWrapper&&(t.blank(),t.push(2,"var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());"),t.blank(),t.push(2,"System.out.println(response.body());"),t.push(1,"}"),t.push("}")),t.join()},I={key:"httpclient",title:"HttpClient",link:"https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html",description:"HttpClient (Java SE 11 & JDK 11 )"};var N=A;function R(a,s){a.push("/**"),a.push(" * Requires JDK >= 11"),s.securityOAuth2ExtraCalls?.length&&(a.push(" *"),a.push(' * Requires package "org.json" >= 20201115'),a.push(" * See here for installation details:"),a.push(" *  https://search.maven.org/artifact/org.json/json")),a.push(" */"),a.blank()}function B(a,s){a.push("import java.net.*;"),a.push("import java.net.http.*;"),a.push("import java.util.*;"),(l(s.postData?.mimeType)===i.URL_ENCODED&&s.postData?.params||s.securityOAuth2ExtraCalls?.length||h(s))&&(a.push("import java.nio.charset.StandardCharsets;"),a.push("import java.util.stream.Collectors;")),s.securityOAuth2ExtraCalls?.length&&a.push("import org.json.JSONObject;"),!s.postData?.params?.length&&s.postData?.text&&l(s.postData.mimeType)===i.MULTIPART&&a.push("import java.nio.file.Path;"),a.blank()}export{N as default,I as info};
