import{CodeBuilder as D}from"../../helpers/code-builder.js";import{HTTPSnippet as q}from"../../index.js";import{isEmptyObject as S,normalizeMimeType as O}from"../../../../utils.js";import{capitalizeFirst as N}from"../../../generator.js";import{Lang as k}from"../../helpers/constants.js";import{buildUrlExpression as T,printUrlVariablesDeclarations as L}from"../../helpers/code-helpers.js";import{MediaTypes as r}from"../../../../../constants.js";import{buildJava8DeviceAuthorizationCodeSnippet as U}from"../../helpers/device-auth-snippets.js";const M=function(t,i,{target:l,client:A}){const p=Object.assign({indent:"  ",withWrapper:!0},i),e=new D({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:k.JAVA8}),y=j(t.method);if(p.withComments&&P(e),p.withImports&&R(e,t),p.withWrapper&&(e.push("public class App {"),e.push(1,"public static void main(String[] args ) throws java.io.IOException {"),e.push(2,"HttpClient httpClient = HttpClientBuilder.create().build();"),e.blank()),t.securityOAuth2ExtraCalls?.length){const a=t.securityOAuth2ExtraCalls?.[0],s=new q(a).convert(l,A,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(s),e.push(2,"JSONObject %s = new JSONObject(EntityUtils.toString(httpClient.execute(%s).getEntity()));","oauth2Response","oauth2Request"),a.flowType==="deviceAuthorization"?U(e,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(e.push(2,'String accessToken = %s.getString("access_token");',"oauth2Response"),e.blank())}L(t,e,2);const C=T(t,e);e.push(2,`%s ${e.var("request")} = new %s(%s);`,y,y,C);const g=Object.keys(t.allHeaders);if(g.length&&!(t.postData&&t.postData.mimeType==r.MULTIPART)&&g.forEach(a=>{const s=a.toLowerCase()==="authorization";e.push(2,'%s.setHeader("%s", %s);',e.var("request"),a,t.securityOAuth2ExtraCalls?.length&&s?'"Bearer " + accessToken':`"${t.allHeaders[a]}"`)}),t.basicAuth){const{username:a,password:s}=t.basicAuth;e.push(2,`String encodedString = Base64.getEncoder().encodeToString("${a}:${s}".getBytes());`),e.push(2,'%s.setHeader("%s", "%s"+encodedString);',e.var("request"),"Authorization","Basic ")}if(t.postData)switch(O(t.postData.mimeType)){case r.URL_ENCODED:t.postData.params.length?(e.blank(),e.push(2,"List<NameValuePair> params = new ArrayList<NameValuePair>();"),t.postData.params.forEach(a=>{e.push(2,'params.add(new BasicNameValuePair("%s", "%s"));',a.name,a.value)}),e.push(2,"%s.setEntity(new UrlEncodedFormEntity(params));",e.var("request")),e.blank()):t.postData.text&&(e.blank(),e.push(2,'%s.setEntity(new StringEntity("%s"));',e.var("request"),t.postData.text),e.blank());break;case r.MULTIPART:if(t.postData.params&&t.postData.params.length>0)e.push(2,"MultipartEntity reqEntity = new MultipartEntity();"),t.postData.params.forEach(a=>{a.fileName?e.push(2,'reqEntity.addPart("%s", new FileBody(new File("%s")));',a.name,a.fileName):e.push(2,'reqEntity.addPart("%s", %s);',a.name,v(a.value)?`new StringBody("${a.value}")`:a.value)}),e.push(2,"%s.setEntity(reqEntity);",e.var("request"));else if(t.postData.text){const a=t.postData.text,s=a.match(/^--([^\r\n]+)/);if(s){const n=s[1],o=a.split(new RegExp(`--${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(h=>h.trim().length>0);e.push(2,"MultipartEntity reqEntity = new MultipartEntity();"),o.forEach(h=>{const m=h.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(m){const E=m[1],d=m[2],b=h.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),x=(b?b[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');d?e.push(2,'reqEntity.addPart("%s", new FileBody(new File("%s")));',E,d):e.push(2,'reqEntity.addPart("%s", new StringBody("%s"));',E,x)}}),e.push(2,"%s.setEntity(reqEntity);",e.var("request"))}else e.push(2,'%s.setEntity(new StringEntity("%s"));',e.var("request"),t.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"'))}break;case r.JSON:if(t.postData.jsonObj){e.push(2,"JSONObject payload = new JSONObject();");for(const[a,s]of Object.entries(t.postData.jsonObj))Array.isArray(s)?(e.push(2,'payload.put("%s", new JSONArray()',a),s.forEach(n=>{c(n)?(e.push(3,".put(new JSONObject()"),u(n,4),e.push(3,")")):e.push(3,".put(%s)",f(n))}),e.push(2,");")):c(s)?(e.push(2,'payload.put("%s", new JSONObject()%s',a,S(s)?");":""),u(s,3),S(s)||e.push(2,");")):e.push(2,'payload.put("%s", %s);',a,f(s));e.push(2,"%s.setEntity(new StringEntity(payload.toString()));",e.var("request"))}break;case r.XML:t.postData.text&&(e.push(2,'String payload = String.join("\\n"'),t.postData.text.trim().split(`
`).forEach(a=>{const s=a.replace(/"/g,'\\"');e.push(3,`"${s}", `)}),e.push(2,");"),e.push(2,"%s.setEntity(new StringEntity(payload));",e.var("request")));break;case r.OCTET_STREAM:t.postData.text&&e.push(2,'%s.setEntity(new StringEntity("%s"));',e.var("request"),t.postData.text);break}return p.withWrapper&&(e.push(2,`String ${e.var("response")} = EntityUtils.toString(httpClient.execute(request).getEntity());`),e.blank(),e.push(2,"System.out.println(response);"),e.push(1,"}"),e.push("}")),e.join();function u(a,s){for(const[n,o]of Object.entries(a))c(o)?(e.push(s,'.put("%s", new JSONObject()',n),u(o,s+1),e.push(s,")")):e.push(s,'.put("%s", %s)',n,f(o))}},W={key:"apachehttp",title:"Apache http",link:"https://hc.apache.org/httpcomponents-client-4.5.x/",description:"Apache HttpClient"};var K=M;function P(t){t.push("/**"),t.push(" * Requires JDK >= 8"),t.push(" *"),t.push(" * Requires Apache HttpComponents Client >= 4.3.5"),t.push(" * See here for installation details:"),t.push(" *   https://search.maven.org/artifact/org.apache.httpcomponents/httpcomponents-client"),t.push(" *"),t.push(' * Requires package "junit4"'),t.push(" * See here for installation details:"),t.push(" *   https://junit.org/junit4"),t.push(" *"),t.push(' * Requires package "org.json" >= 20180130'),t.push(" * See here for installation details:"),t.push(" *   https://search.maven.org/artifact/org.json/json"),t.push(" */"),t.blank()}function R(t,i){t.push("import org.apache.http.util.EntityUtils;"),t.push("import org.apache.http.NameValuePair;"),t.push("import org.apache.http.client.HttpClient;"),t.push("import org.apache.http.client.entity.UrlEncodedFormEntity;"),i.method&&w(t,i.method),i.securityOAuth2ExtraCalls?.length&&i.securityOAuth2ExtraCalls?.[0].method.toLowerCase()!==i.method.toLowerCase()&&w(t,i.securityOAuth2ExtraCalls?.[0].method),t.push("import org.apache.http.impl.client.HttpClientBuilder;"),t.push("import org.apache.http.message.BasicNameValuePair;"),t.push("import org.apache.http.entity.StringEntity;"),t.push("import org.json.JSONObject;"),t.push("import org.json.JSONArray;"),t.push("import java.util.ArrayList;"),t.push("import java.util.List;"),t.push("import org.apache.http.entity.mime.MultipartEntity;"),t.push("import org.apache.http.entity.mime.content.StringBody;"),!i.postData?.params?.length&&i.postData?.text&&O(i.postData.mimeType)===r.MULTIPART&&(t.push("import org.apache.http.entity.mime.content.FileBody;"),t.push("import java.io.File;")),i.basicAuth&&t.push("import java.util.Base64;"),t.blank()}function w(t,i){const l=j(i);t.push(`import org.apache.http.client.methods.${l};`)}function j(t){return"Http"+N(t.toLowerCase())}function v(t){return Object.prototype.toString.call(t)==="[object String]"}function c(t){const i=typeof t;return i==="function"||i==="object"&&!!t}function f(t){return v(t)?JSON.stringify(t):t??"JSONObject.NULL"}export{K as default,W as info};
