1- package com . microsoft . azure . search . samples . service ;
1+ package service ;
22
33import javax .json .Json ;
44import javax .net .ssl .HttpsURLConnection ;
1616/**
1717 * This class is responsible for implementing HTTP operations for creating the index, uploading documents and searching the data*/
1818public class SearchServiceClient {
19- private final String _apiKey ;
19+ private final String _adminKey ;
20+ private final String _queryKey ;
2021 private final String _apiVersion ;
2122 private final String _serviceName ;
2223 private final String _indexName ;
2324 private final static HttpClient client = HttpClient .newHttpClient ();
2425
25-
26- public SearchServiceClient (String serviceName , String apiKey , String apiVersion , String indexName ) {
26+ public SearchServiceClient (String serviceName , String adminKey , String queryKey , String apiVersion , String indexName ) {
2727 this ._serviceName = serviceName ;
28- this ._apiKey = apiKey ;
28+ this ._adminKey = adminKey ;
29+ this ._queryKey = queryKey ;
2930 this ._apiVersion = apiVersion ;
3031 this ._indexName = indexName ;
3132 }
3233
33- private HttpRequest httpRequest (URI uri , String method , String contents )
34- {
35- return httpRequest (uri , _apiKey , method , contents );
36- }
37-
3834 private static HttpResponse <String > sendRequest (HttpRequest request ) throws IOException , InterruptedException {
3935 logMessage (String .format ("%s: %s" , request .method (), request .uri ()));
4036 return client .send (request , HttpResponse .BodyHandlers .ofString ());
4137 }
4238
39+ private static URI buildURI (Consumer <Formatter > fmtFn )
40+ {
41+ Formatter strFormatter = new Formatter ();
42+ fmtFn .accept (strFormatter );
43+ String url = strFormatter .out ().toString ();
44+ strFormatter .close ();
45+ return URI .create (url );
46+ }
47+
48+ public static void logMessage (String message ) {
49+ System .out .println (message );
50+ }
51+
52+ public static boolean isSuccessResponse (HttpResponse <String > response ) {
53+ try {
54+ int responseCode = response .statusCode ();
55+
56+ logMessage ("\n Response code = " + responseCode );
57+
58+ if (responseCode == HttpURLConnection .HTTP_OK || responseCode == HttpURLConnection .HTTP_ACCEPTED
59+ || responseCode == HttpURLConnection .HTTP_NO_CONTENT || responseCode == HttpsURLConnection .HTTP_CREATED ) {
60+ return true ;
61+ }
62+
63+ // We got an error
64+ var msg = response .body ();
65+ if (msg != null ) {
66+ logMessage (String .format ("\n MESSAGE: %s" , msg ));
67+ }
68+
69+ } catch (Exception e ) {
70+ e .printStackTrace ();
71+ }
72+
73+ return false ;
74+ }
75+
76+ public static HttpRequest httpRequest (URI uri , String key , String method , String contents ) {
77+ contents = contents == null ? "" : contents ;
78+ var builder = HttpRequest .newBuilder ();
79+ builder .uri (uri );
80+ builder .setHeader ("content-type" , "application/json" );
81+ builder .setHeader ("api-key" , key );
82+
83+ switch (method ) {
84+ case "GET" :
85+ builder = builder .GET ();
86+ break ;
87+ case "HEAD" :
88+ builder = builder .GET ();
89+ break ;
90+ case "DELETE" :
91+ builder = builder .DELETE ();
92+ break ;
93+ case "PUT" :
94+ builder = builder .PUT (HttpRequest .BodyPublishers .ofString (contents ));
95+ break ;
96+ case "POST" :
97+ builder = builder .POST (HttpRequest .BodyPublishers .ofString (contents ));
98+ break ;
99+ default :
100+ throw new IllegalArgumentException (String .format ("Can't create request for method '%s'" , method ));
101+ }
102+ return builder .build ();
103+ }
104+
43105 public boolean indexExists () throws IOException , InterruptedException {
44106 logMessage ("\n Checking if index exists..." );
45107 var uri = buildURI (strFormatter -> strFormatter .format (
46108 "https://%s.search.windows.net/indexes/%s/docs?api-version=%s&search=*" ,
47109 _serviceName ,_indexName ,_apiVersion ));
48- var request = httpRequest (uri , "HEAD" , "" );
110+ var request = httpRequest (uri , _adminKey , "HEAD" , "" );
49111 var response = sendRequest (request );
50112 return isSuccessResponse (response );
51113 }
@@ -55,7 +117,7 @@ public boolean deleteIndex() throws IOException, InterruptedException {
55117 var uri = buildURI (strFormatter -> strFormatter .format (
56118 "https://%s.search.windows.net/indexes/%s?api-version=%s" ,
57119 _serviceName ,_indexName ,_apiVersion ));
58- var request = httpRequest (uri , "DELETE" , "*" );
120+ var request = httpRequest (uri , _adminKey , "DELETE" , "*" );
59121 var response = sendRequest (request );
60122 return isSuccessResponse (response );
61123 }
@@ -71,7 +133,7 @@ public boolean createIndex(String indexDefinitionFile) throws IOException, Inter
71133 var inputStream = SearchServiceClient .class .getResourceAsStream ("index.json" );
72134 var indexDef = new String (inputStream .readAllBytes (), StandardCharsets .UTF_8 );
73135 //Send HTTP PUT request to create the index in the search service
74- var request = httpRequest (uri , "PUT" , indexDef );
136+ var request = httpRequest (uri , _adminKey , "PUT" , indexDef );
75137 var response = sendRequest (request );
76138 return isSuccessResponse (response );
77139 }
@@ -86,13 +148,15 @@ public boolean uploadDocuments(String documentsFile) throws IOException, Interru
86148 var inputStream = SearchServiceClient .class .getResourceAsStream (documentsFile );
87149 var documents = new String (inputStream .readAllBytes (), StandardCharsets .UTF_8 );
88150 //Send HTTP POST request to upload and index the data
89- var request = httpRequest (endpoint , "POST" , documents );
151+ var request = httpRequest (endpoint , _adminKey , "POST" , documents );
90152 var response = sendRequest (request );
91153 return isSuccessResponse (response );
92154 }
93155
156+ public SearchOptions createSearchOptions () { return new SearchOptions ();}
157+
94158 //Defines available search parameters that can be set
95- public class SearchOptions {
159+ public static class SearchOptions {
96160
97161 public String select = "" ;
98162 public String filter = "" ;
@@ -125,94 +189,26 @@ public void searchPlus(String queryString)
125189 public void searchPlus (String queryString , SearchOptions options ) {
126190
127191 try {
128- String optionsString = createOptionsString (options );
192+ String optionsString = createOptionsString (options );
129193 var uri = buildURI (strFormatter -> strFormatter .format (
130194 "https://%s.search.windows.net/indexes/%s/docs?api-version=%s&search=%s%s" ,
131195 _serviceName , _indexName , _apiVersion , queryString , optionsString ));
132- var request = httpRequest (uri , "GET" , null );
196+ var request = httpRequest (uri , _queryKey , "GET" , null );
133197 var response = sendRequest (request );
134- // logMessage("Full response:\n");
135- // logMessage(response.body());
136198 var jsonReader = Json .createReader (new StringReader (response .body ()));
137199 var jsonArray = jsonReader .readObject ().getJsonArray ("value" );
138- var resultsCount = jsonArray .size ();
200+ var resultsCount = jsonArray .size ();
139201 logMessage ("Results:\n Count: " + resultsCount );
140202 for (int i = 0 ; i <= resultsCount - 1 ; i ++) {
141203 logMessage (jsonArray .get (i ).toString ());
142204 }
143205
144206 jsonReader .close ();
145207
146- }
147- catch (Exception e ) {
148- e .printStackTrace ();
149- }
150-
151- }
152-
153- private static URI buildURI (Consumer <Formatter > fmtFn )
154- {
155- Formatter strFormatter = new Formatter ();
156- fmtFn .accept (strFormatter );
157- String url = strFormatter .out ().toString ();
158- strFormatter .close ();
159- return URI .create (url );
160- }
161-
162- public static void logMessage (String message ) {
163- System .out .println (message );
164- }
165-
166- public static boolean isSuccessResponse (HttpResponse <String > response ) {
167- try {
168- int responseCode = response .statusCode ();
169-
170- logMessage ("\n Response code = " + responseCode );
171-
172- if (responseCode == HttpURLConnection .HTTP_OK || responseCode == HttpURLConnection .HTTP_ACCEPTED
173- || responseCode == HttpURLConnection .HTTP_NO_CONTENT || responseCode == HttpsURLConnection .HTTP_CREATED ) {
174- return true ;
175- }
176-
177- // We got an error
178- var msg = response .body ();
179- if (msg != null ) {
180- logMessage (String .format ("\n MESSAGE: %s" , msg ));
181- }
182-
183- } catch (Exception e ) {
208+ }
209+ catch (Exception e ) {
184210 e .printStackTrace ();
185211 }
186212
187- return false ;
188- }
189-
190- private static HttpRequest httpRequest (URI uri , String apiKey , String method , String contents ) {
191- contents = contents == null ? "" : contents ;
192- var builder = HttpRequest .newBuilder ();
193- builder .uri (uri );
194- builder .setHeader ("content-type" , "application/json" );
195- builder .setHeader ("api-key" , apiKey );
196-
197- switch (method ) {
198- case "GET" :
199- builder = builder .GET ();
200- break ;
201- case "HEAD" :
202- builder = builder .GET ();
203- break ;
204- case "DELETE" :
205- builder = builder .DELETE ();
206- break ;
207- case "PUT" :
208- builder = builder .PUT (HttpRequest .BodyPublishers .ofString (contents ));
209- break ;
210- case "POST" :
211- builder = builder .POST (HttpRequest .BodyPublishers .ofString (contents ));
212- break ;
213- default :
214- throw new IllegalArgumentException (String .format ("Can't create request for method '%s'" , method ));
215- }
216- return builder .build ();
217213 }
218- }
214+ }
0 commit comments