001package com.thed.zblast.util;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.IOException;
006import java.io.InputStream;
007import java.io.UnsupportedEncodingException;
008import java.lang.reflect.Type;
009import java.net.InetAddress;
010import java.net.URLEncoder;
011import java.nio.charset.StandardCharsets;
012import java.nio.file.Files;
013import java.nio.file.Path;
014import java.util.*;
015import java.util.Map.Entry;
016import java.util.logging.Level;
017import java.util.logging.LogManager;
018import java.util.logging.Logger;
019import java.util.stream.Collectors;
020
021import com.thed.model.*;
022import com.thed.util.ErrorResource;
023import org.apache.commons.configuration.PropertiesConfiguration;
024import org.apache.commons.httpclient.*;
025import org.apache.commons.httpclient.methods.GetMethod;
026import org.apache.commons.httpclient.methods.PostMethod;
027import org.apache.commons.httpclient.methods.PutMethod;
028import org.apache.commons.httpclient.methods.StringRequestEntity;
029import org.apache.commons.httpclient.params.HttpMethodParams;
030import org.apache.commons.io.IOUtils;
031import org.apache.commons.lang.StringUtils;
032import org.apache.http.HttpEntity;
033import org.apache.http.HttpResponse;
034import org.apache.http.client.ClientProtocolException;
035import org.apache.http.client.methods.HttpPost;
036import org.apache.http.entity.mime.MultipartEntity;
037import org.apache.http.entity.mime.content.FileBody;
038import org.apache.http.impl.client.DefaultHttpClient;
039
040import com.google.gson.reflect.TypeToken;
041import com.thed.agent.ZephyrAgent;
042import com.thed.util.CodecUtils;
043import com.thed.util.Utils;
044import com.thed.util.ZeeConstants;
045import com.thed.util.gson.CustomDateUtil;
046import com.thed.util.gson.GsonUtil;
047import com.thed.zblast.parser.model.TCRCatalogTreeTestcase;
048import com.thed.zblast.parser.model.TreeSelectionInfo;
049import com.thed.zblast.scheduler.JobProgressDTO;
050import org.apache.http.message.BasicNameValuePair;
051import org.json.JSONArray;
052import org.json.JSONObject;
053
054public class RestUtil {
055        public static final String urlFragmentZblast = "/flex/services/rest/v3/automation/schedule/jobs";
056        public static final String URL_BULK_AUTOMATION_UPDATE = "/flex/services/rest/v3/automation/bulkStatus";
057        public static final String URL_FOR_PROJECT = "/flex/services/rest/v3/project/";
058        public static final String URL_BULK_TESECASES = "/flex/services/rest/v3/testcase/bulk";
059        public static final String URL_RELEASE_SCHEDULED_TCRTESTCASES = "/flex/services/rest/v3/testcase/tcrTestCases/releaseScheduled";
060        public static final String URL_BULK_TESECASES_UPDATE = "/flex/services/rest/v3/testcase/update";
061        public static final String URL_TESTCASE_SEARCH = "/flex/services/rest/v3/testcase/tree/{treeId}?offset=0&pagesize=1&dbsearch=true&maxresults=1&frozen=false";
062        public static final String URL_CREATE_CYCLE = "/flex/services/rest/v3/cycle/";
063        public static final String URL_UPDATE_CYCLE = "/flex/services/rest/v3/cycle/{cycleId}";
064        public static final String URL_CREATE_PHASE = "/flex/services/rest/v3/testcasetree/";
065        public static final String URL_ADD_PHASE_TO_CYCLE = "/flex/services/rest/v3/cycle/{cycleId}/phase";
066        public static final String URL_ASSIGN_PHASE = "/flex/services/rest/v3/assignmenttree/{cyclephaseid}/bulk/tree/{treeId}/from/-1/to/{assignTO}?cascade=true&easmode=2";
067        public static final String URL_UPDATE_EXECUTION = "/flex/services/rest/v3/execution/";
068        public static final String URL_EXECUTE_IN_BULK = "/flex/services/rest/v3/execution/bulk/execute";
069        public static final String URL_UPDATE_STEP_EXECUTION = "/flex/services/rest/v3/execution/teststepresult/saveorupdate";
070        public static final String URL_GET_PHASES = "/flex/services/rest/v3/testcasetree/?type={type}&revisionid={revisionid}&releaseid={releaseid}";
071        public static final String URL_GET_PHASES_BY_ID = "/flex/services/rest/v3/testcasetree/{tcrCatalogTreeId}";
072        public static final String URL_GET_TESTSTEPS = "/flex/services/rest/v3/testcase/{testcaseId}/teststep";
073        public static final String URL_GET_LOGGED_IN_USER = "/flex/services/rest/v3/user/current";
074        public static final String URL_GET_RELEASE_TEST_SCHEDULES = "/flex/services/rest/v3/execution/user/project?&dbsearch=true&cyclephaseid={cycleId}&pagesize={pageSize}&releaseid={releaseId}";
075        public static final String URL_BROWSE_TESTCASES_TO_PHASE = "/flex/services/rest/v3/assignmenttree/{cyclephaseid}/assign/bytree/{parenttreeid}?includehierarchy={createPackage}";
076        public static final String URL_SEARCH_TESTCASES_ON_NAME = "/flex/services/rest/v3/advancesearch/?word={testCaseName}&firstresult=0&maxresults=50&entitytype=testcase&zql=true&releaseid={releaseId}&dbSearch=true";
077        public static final String URL_GET_CYCLE_BY_ID = "/flex/services/rest/v3/cycle/{cycleId}";
078        public static final String URL_GET_CYCLE_NAMES = "/flex/services/rest/v3/cycle/cycleName/{releaseid}?cycleName={cycleName}&orderBy={sortBy}";
079        public static final String URL_GET_CYCLE_PHASE_BY_ID = "/flex/services/rest/v3/assignmenttree/{cyclePhaseID}";
080    public static final String URL_BULK_REQUIREMENTS_RELEASE = "/flex/services/rest/v3/requirement/bulk";
081    private static final String URL_UPDATE_TEST_RESULT = "/flex/services/rest/v3/execution/updateteststatus";
082    private static final String URL_GET_TEST_EXECUTION_STATUSES = "/flex/services/rest/v3/admin/preference?key=testresult.testresultStatus.LOV";
083
084        public static final String URL_JOB_SCHEDULED = "/flex/services/rest/v3/automation/schedule";
085        private static final String URL_UPDATE_FAILED_TESTCASE_EXECUTION = "/flex/services/rest/v3/automation/failedtc/update";
086    private static final String URL_GET_RELEASETEST_SCHEDULE_BYIDS = "/flex/services/rest/v3/execution/ids";
087    private static final String URL_GET_SCRIPT_JOB_DETAIL = "/flex/services/rest/v3/automationscriptjob/scriptjob/detail?jobid=";
088
089
090        static PropertiesConfiguration props = Utils.getZbotProperties();
091        static String username = props.getString("username");
092    static String password = props.getString("encPwd");
093    static String apitoken = props.getString("apitoken");
094        static String cred = "";
095        private static Logger logger = Logger.getLogger(ZephyrAgent.class.getName());
096
097        static {
098                try {
099                        LogManager.getLogManager().readConfiguration(new FileInputStream(Utils.getLogPropertiesFile()));
100                        logger.info("Path : " + Utils.getLogPropertiesFile());
101                } catch (Exception e) {
102                }
103        }
104
105        /**
106         * @return
107         */
108        private static String getURLZblast() {
109                return Utils.getZbotProperties().getString("zephyrServerURL") + ZeeConstants.urlFragmentZblast;
110        }
111
112        private static String getURLFileWatcher() {
113                return Utils.getZbotProperties().getString("zephyrServerURL") + ZeeConstants.urlFragmentFileWatcher;
114        }
115
116        public static HttpClient getConnectionFromPool() {
117                MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManager();
118                HttpClient c = new HttpClient(connman);
119                return c;
120        }
121
122        private static String getURLZblastUpdateStatus() {
123                return props.getString("zephyrServerURL") + ZeeConstants.urlFragmentZblastUpdateStatus;
124        }
125
126     static String createRequestHeader(){
127        if(apitoken!=null && apitoken!=""){
128            logger.info("Going to make API call using API Token.");
129            return "Bearer " + apitoken;
130        }else{
131            logger.info("Going to make API call basic authentication.");
132            String decryptPassword = CodecUtils.decrypt(password);
133            cred = username + ":" + decryptPassword;
134            return "Basic " + Base64.getEncoder().encodeToString(cred.getBytes());
135        }
136    }
137
138        private static String getURLZFileWatcherUpdateStatus() {
139                return props.getString("zephyrServerURL") + ZeeConstants.urlFragmentFileWatcherUpdate;
140        }
141
142        public static String getURL() {
143                return Utils.getZbotProperties().getString("zephyrServerURL") + "/" + ZeeConstants.urlFragment;
144        }
145
146        public static Integer getAutomationJobResultFilereadingMonitorWaitTime() {
147
148                return new Integer(Utils.getZbotProperties().getString("automation_job_result_filereading_monitor_waittime"));
149        }
150
151        public static String updateZblastScheduleStatus(Long id, String status, String cycleId, AutomationJobDetail automationJob)
152                        throws HttpException, IOException {
153                String response = "";
154                HttpClient client = getConnectionFromPool();
155                String zblastScheduleStatusUpdateURL = getURLZblastUpdateStatus() + "?scheduleid=" + id + "&status=" + URLEncoder.encode(status, StandardCharsets.UTF_8.toString());
156                logger.info("zblastScheduleStatusUpdateURL:" + zblastScheduleStatusUpdateURL);
157                if (cycleId != null) {
158                        zblastScheduleStatusUpdateURL += "&cycleid=" + cycleId;
159                }
160                if (automationJob.getCyclePhaseId() != null) {
161                        zblastScheduleStatusUpdateURL += "&cyclePhaseid=" + automationJob.getCyclePhaseId();
162                }
163                if (automationJob.getTcrCatalogTreeId() != null) {
164                        zblastScheduleStatusUpdateURL += "&tcrTreeId=" + automationJob.getTcrCatalogTreeId();
165                }
166                InputStream inputStream = null;
167                PutMethod method = new PutMethod(zblastScheduleStatusUpdateURL);
168                method.setRequestHeader("Authorization", createRequestHeader());
169                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
170
171                try {
172                        int statusCode = -1;
173                        try {
174                                statusCode = client.executeMethod(method);
175                                logger.info(" updateZblastScheduleStatus:: " + statusCode);
176                        } catch (Exception e) {
177                                logger.log(Level.WARNING, e.getMessage());
178                        }
179
180                        if (statusCode != HttpStatus.SC_OK) {
181                handleHttpError(statusCode,"updateZblastScheduleStatus",method);
182                        } else {
183                                inputStream = method.getResponseBodyAsStream();
184                                if (inputStream != null) {
185                                        response = IOUtils.toString(inputStream, "utf-8");
186                                        logger.info("checkPayLoad || Response " + response);
187                                }
188                        }
189                } finally {
190                        if (inputStream != null) {
191                                inputStream.close();
192                        }
193                        method.releaseConnection();
194                }
195                return response;
196        }
197
198        public static void updateFileWatcher(AutomationJobDetail schedule, String status, String info) throws IOException {
199                HttpClient client = getConnectionFromPool();
200                boolean isUpdate = false;
201                InputStream inputStream = null;
202                StringBuilder zblastScheduleStatusUpdateURL = new StringBuilder(
203                                getURLZFileWatcherUpdateStatus() + "?scheduleid=" + schedule.getId());
204                if (status != null && !status.isEmpty()) {
205                        zblastScheduleStatusUpdateURL
206                                        .append("&status=" + URLEncoder.encode(status, StandardCharsets.UTF_8.toString()));
207                        isUpdate = true;
208                }
209                if (schedule.getCycleId() != null) {
210                        zblastScheduleStatusUpdateURL
211                                        .append("&cycleId=" + schedule.getCycleId());
212                }
213                if (schedule.getCyclePhaseId() != null) {
214                        zblastScheduleStatusUpdateURL
215                                        .append("&cyclePhaseId=" + schedule.getCyclePhaseId());
216                }
217                if (schedule.getTcrCatalogTreeId() != null) {
218                        zblastScheduleStatusUpdateURL
219                                        .append("&tcrTreeId=" + schedule.getTcrCatalogTreeId());
220                }
221                if (info != null && !info.isEmpty()) {
222                        zblastScheduleStatusUpdateURL.append("&info=" + URLEncoder.encode(info, StandardCharsets.UTF_8.toString()));
223                        isUpdate = true;
224                }
225                if (!isUpdate) {
226                        return;
227                }
228
229                PutMethod method = new PutMethod(zblastScheduleStatusUpdateURL.toString());
230                method.setRequestHeader("Authorization", createRequestHeader());
231                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
232
233                try {
234                        int statusCode = -1;
235                        try {
236                                statusCode = client.executeMethod(method);
237                        } catch (Exception e) {
238                                logger.log(Level.WARNING, e.getMessage());
239                        }
240
241                        if (statusCode != HttpStatus.SC_OK) {
242                handleHttpError(statusCode,"updateFileWatcher",method);
243                        } else {
244                                inputStream = method.getResponseBodyAsStream();
245                                if (inputStream != null) {
246                                        String response = IOUtils.toString(inputStream, "utf-8");
247                                        logger.info("checkPayLoad || Response " + response);
248                                }
249                        }
250                } finally {
251                        if (inputStream != null) {
252                                inputStream.close();
253                        }
254                        method.releaseConnection();
255                }
256        }
257
258        public static ProjectDTO getMethodForProject(Long id) throws IOException {
259                InputStream inputStream = null;
260                ProjectDTO projectById = null;
261                String urlZblast = props.getString("zephyrServerURL") + URL_FOR_PROJECT + id;
262                HttpClient httpClient = new HttpClient();
263                GetMethod method = new GetMethod(urlZblast);
264                method.setRequestHeader("Authorization", createRequestHeader());
265                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
266
267                try {
268                        int statusCode = -1;
269                        try {
270                                statusCode = httpClient.executeMethod(method);
271                        } catch (Exception e) {
272                                logger.log(Level.WARNING, e.getMessage());
273                        }
274
275                        if (statusCode != HttpStatus.SC_OK) {
276                handleHttpError(statusCode,"getMethodForProject",method);
277                        } else {
278                                inputStream = method.getResponseBodyAsStream();
279                                String response = IOUtils.toString(inputStream, "utf-8");
280                                projectById = CustomDateUtil.gson.fromJson(response, ProjectDTO.class);
281                                if (response != null) {
282                                }
283                        }
284                } finally {
285                        method.releaseConnection();
286                }
287                return projectById;
288        }
289
290        public static String updateTCRTestCasesForCycleName(String cycleName, List<Long> tcrCatalogTreeTestcasesIds) throws IOException {
291                InputStream inputStream = null;
292                HttpClient httpClient = new HttpClient();
293
294                StringRequestEntity requestEntity = new StringRequestEntity(tcrCatalogTreeTestcasesIds.toString(), "application/json", "UTF-8");
295
296                String encodedCycleName = URLEncoder.encode(cycleName, "UTF-8");
297                PutMethod method = new PutMethod(props.getString("zephyrServerURL") + URL_RELEASE_SCHEDULED_TCRTESTCASES+ "?cycleName=" + encodedCycleName);
298                logger.info("""
299                                bulk URL: %s%s?cycleName=%s""".formatted(props.getString("zephyrServerURL"), URL_RELEASE_SCHEDULED_TCRTESTCASES, encodedCycleName));
300                method.setRequestHeader("Authorization", createRequestHeader());
301                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
302
303                method.setRequestEntity(requestEntity);
304                String response = null;
305                try {
306                        int statusCode = -1;
307                        try {
308                                statusCode = httpClient.executeMethod(method);
309                        } catch (Exception e) {
310                                logger.log(Level.WARNING, e.getMessage());
311                        }
312
313                        if (statusCode != HttpStatus.SC_OK) {
314                                handleHttpError(statusCode, "getMethodForReleaseTestScheduledTCRTestCases", method);
315                        } else {
316                                inputStream = method.getResponseBodyAsStream();
317                                response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
318                        }
319                } finally {
320                        if (inputStream != null) {
321                                inputStream.close();
322                        }
323                        method.releaseConnection();
324                }
325                return response;
326        }
327        public static List<TCRCatalogTreeTestcase> saveBulkTestCases(List<TCRCatalogTreeTestcase> testcaseList, AutomationJobDetail automationJobDetail)
328                        throws HttpException, IOException {
329                HttpClient client = getConnectionFromPool();
330                List<TCRCatalogTreeTestcase> tcbe = null;
331                InputStream inputStream = null;
332                long scheduleId = 0l;
333                if (automationJobDetail.getFromFileWatcher()) {
334                        scheduleId = automationJobDetail.getId();
335                } else {
336                        scheduleId = automationJobDetail.getScheduleId();
337                }
338                logger.info("saveBulkTestCases Request ::::" + GsonUtil.CUSTOM_GSON.toJson(testcaseList));
339
340
341                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(testcaseList), "application/json", "UTF-8");
342
343                PostMethod method = new PostMethod(props.getString("zephyrServerURL") + URL_BULK_TESECASES + "?scheduleId=" + scheduleId);
344
345
346                logger.info("""
347                                bulk URL: %s%s?scheduleId=%d""".formatted(props.getString("zephyrServerURL"), URL_BULK_TESECASES, scheduleId));
348
349                method.setRequestHeader("Authorization", createRequestHeader());
350                method.setRequestEntity(requestEntity);
351                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
352                try {
353                        int statusCode = -1;
354                        try {
355                                statusCode = client.executeMethod(method);
356                                logger.info("statusCode :::" + statusCode);
357                        } catch (Exception e) {
358                                logger.log(Level.WARNING, e.getMessage());
359                        }
360                        if (statusCode != HttpStatus.SC_OK) {
361                handleHttpError(statusCode,"saveBulkTestCases",method);
362                        } else {
363                                inputStream = method.getResponseBodyAsStream();
364                                if (inputStream != null) {
365                                        String response = IOUtils.toString(inputStream, "utf-8");
366                                        logger.info("saveBulkTestCases ... checkPayLoad || Response " + response);
367                                        Type listType = new TypeToken<ArrayList<TCRCatalogTreeTestcase>>() {
368                                        }.getType();
369                                        tcbe = CustomDateUtil.gson.fromJson(response, listType);
370                                }
371                        }
372                } finally {
373                        if (inputStream != null) {
374                                inputStream.close();
375                        }
376                        method.releaseConnection();
377                }
378                return tcbe;
379        }
380
381        public static List<TCRCatalogTreeTestcase> updateTestcases(List<TestcaseBulkUpdateParam> paramList)
382                        throws HttpException, IOException {
383                HttpClient client = getConnectionFromPool();
384                List<TCRCatalogTreeTestcase> tcbe = null;
385                InputStream inputStream = null;
386                String url = props.getString("zephyrServerURL") + URL_BULK_TESECASES_UPDATE;
387                String requestPayload = GsonUtil.CUSTOM_GSON.toJson(paramList);
388                logger.info("updateTestcases Request ::::" + requestPayload);
389
390                StringRequestEntity requestEntity = new StringRequestEntity(requestPayload, "application/json", "UTF-8");
391                PutMethod method = new PutMethod(url);
392
393                logger.info("updateTestcases URL:" + url);
394
395                method.setRequestHeader("Authorization", createRequestHeader());
396                method.setRequestEntity(requestEntity);
397                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
398                try {
399                        int statusCode = -1;
400                        try {
401                                statusCode = client.executeMethod(method);
402                                logger.info("statusCode :::" + statusCode);
403                        } catch (Exception e) {
404                                logger.log(Level.WARNING, e.getMessage());
405                        }
406                        if (statusCode != HttpStatus.SC_OK) {
407                handleHttpError(statusCode,"updateTestcases",method);
408                        } else {
409                                inputStream = method.getResponseBodyAsStream();
410                                if (inputStream != null) {
411                                        String response = IOUtils.toString(inputStream, "utf-8");
412                                        logger.info("updateTestcases ... checkPayLoad || Response " + response);
413                                        Type listType = new TypeToken<ArrayList<TCRCatalogTreeTestcase>>() {
414                                        }.getType();
415                                        tcbe = CustomDateUtil.gson.fromJson(response, listType);
416                                }
417                        }
418                } finally {
419                        if (inputStream != null) {
420                                inputStream.close();
421                        }
422                        method.releaseConnection();
423                }
424                return tcbe;
425        }
426
427        public static SearchResult<TCRCatalogTreeTestcase> inSearchtestcase(GetMethod method)
428                        throws HttpException, IOException {
429                HttpClient client = getConnectionFromPool();
430                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
431                SearchResult<TCRCatalogTreeTestcase> tcbe = null;
432                InputStream inputStream = null;
433                try {
434                        int statusCode = -1;
435                        try {
436                                statusCode = client.executeMethod(method);
437                        } catch (Exception e) {
438                                logger.log(Level.WARNING, e.getMessage());
439                        }
440                        if (statusCode != HttpStatus.SC_OK) {
441                handleHttpError(statusCode,"inSearchtestcase",method);
442                        } else {
443                                inputStream = method.getResponseBodyAsStream();
444                                if (inputStream != null) {
445                                        String response = IOUtils.toString(inputStream, "utf-8");
446                                        logger.info("checkPayLoad || Response " + response);
447                                        Type listType = new TypeToken<SearchResult<TCRCatalogTreeTestcase>>() {
448                                        }.getType();
449                                        tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
450                                }
451                        }
452                } finally {
453                        if (inputStream != null) {
454                                inputStream.close();
455                        }
456                        method.releaseConnection();
457                }
458                return tcbe;
459        }
460
461        public static SearchResult<TCRCatalogTreeTestcase> searchtestcase(Long altId) throws IOException {
462                HttpClient client = getConnectionFromPool();
463                InputStream inputStream = null;
464                String urlZblast = props.getString("zephyrServerURL")
465                                + URL_TESTCASE_SEARCH.replace("{treeId}", Long.toString(altId));
466                GetMethod method = new GetMethod(urlZblast);
467                method.setRequestHeader("Authorization", createRequestHeader());
468                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
469                SearchResult<TCRCatalogTreeTestcase> tcbe = inSearchtestcase(method);
470                if (tcbe != null && tcbe.getResultSize() > 1) {
471                        urlZblast = urlZblast.replace("maxresults=1", "maxresults=" + tcbe.getResultSize()).replace("pagesize=1", "pagesize=" + tcbe.getResultSize());
472                        method = new GetMethod(urlZblast);
473                        method.setRequestHeader("Authorization", createRequestHeader());
474                        try {
475                                int statusCode = -1;
476                                try {
477                                        statusCode = client.executeMethod(method);
478                                } catch (Exception e) {
479                                        logger.log(Level.WARNING, e.getMessage());
480                                }
481                                if (statusCode != HttpStatus.SC_OK) {
482                    handleHttpError(statusCode,"searchtestcase",method);
483                                } else {
484                                        inputStream = method.getResponseBodyAsStream();
485                                        if (inputStream != null) {
486                                                String response = IOUtils.toString(inputStream, "utf-8");
487                                                logger.info("checkPayLoad || Response " + response);
488
489                                                Type listType = new TypeToken<SearchResult<TCRCatalogTreeTestcase>>() {
490                                                }.getType();
491                                                tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
492
493                                        }
494                                }
495                        } finally {
496                                if (inputStream != null) {
497                                        inputStream.close();
498                                }
499                                method.releaseConnection();
500                        }
501                }
502                return tcbe;
503        }
504
505        public static CycleDTO CreateCycle(CycleDTO rCycle) throws HttpException, IOException {
506                HttpClient client = getConnectionFromPool();
507                CycleDTO cycle = null;
508                InputStream inputStream = null;
509                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(rCycle),
510                                "application/json", "UTF-8");
511                PostMethod post = new PostMethod(props.getString("zephyrServerURL") + URL_CREATE_CYCLE);
512                post.setRequestHeader("Authorization", createRequestHeader());
513                post.setRequestEntity(requestEntity);
514                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
515                try {
516                        int statusCode = -1;
517                        try {
518                                statusCode = client.executeMethod(post);
519                        } catch (Exception e) {
520                                logger.log(Level.WARNING, e.getMessage());
521                        }
522
523                        if (statusCode != HttpStatus.SC_OK) {
524                handleHttpError(statusCode,"CreateCycle",post);
525                        } else {
526                                inputStream = post.getResponseBodyAsStream();
527                                if (inputStream != null) {
528                                        String response = IOUtils.toString(inputStream, "utf-8");
529                                        logger.info("checkPayLoad || Response " + response);
530                                        cycle = CustomDateUtil.gson.fromJson(response, CycleDTO.class);
531                                }
532                        }
533                } finally {
534                        if (inputStream != null) {
535                                inputStream.close();
536                        }
537                        post.releaseConnection();
538                }
539                return cycle;
540        }
541
542        public static CycleDTO updateCycle(CycleDTO rCycle) throws IOException {
543                HttpClient client = getConnectionFromPool();
544                CycleDTO cycle = null;
545                InputStream inputStream = null;
546                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(rCycle),
547                                "application/json", "UTF-8");
548                PutMethod post = new PutMethod(props.getString("zephyrServerURL") + URL_UPDATE_CYCLE.replace("{cycleId}", String.valueOf(rCycle.getId())));
549                post.setRequestHeader("Authorization", createRequestHeader());
550                post.setRequestEntity(requestEntity);
551                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
552                try {
553                        int statusCode = -1;
554                        try {
555                                statusCode = client.executeMethod(post);
556                        } catch (Exception e) {
557                                logger.log(Level.WARNING, e.getMessage());
558                        }
559
560                        if (statusCode != HttpStatus.SC_OK) {
561                handleHttpError(statusCode,"updateCycle",post);
562                        } else {
563                                inputStream = post.getResponseBodyAsStream();
564                                if (inputStream != null) {
565                                        String response = IOUtils.toString(inputStream, "utf-8");
566                                        logger.info("checkPayLoad || Response " + response);
567                                        cycle = CustomDateUtil.gson.fromJson(response, CycleDTO.class);
568                                }
569                        }
570                } finally {
571                        if (inputStream != null) {
572                                inputStream.close();
573                        }
574                        post.releaseConnection();
575                }
576                return cycle;
577        }
578
579        public static TCRCatalogTreeDTO createTree(TCRCatalogTreeDTO remoteRepositoryTree)
580                        throws HttpException, IOException {
581                HttpClient client = getConnectionFromPool();
582                InputStream inputStream = null;
583                TCRCatalogTreeDTO tree = null;
584                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(remoteRepositoryTree),
585                                "application/json", "UTF-8");
586                PostMethod post = new PostMethod(props.getString("zephyrServerURL") + URL_CREATE_PHASE);
587                post.setRequestHeader("Authorization", createRequestHeader());
588                post.setRequestEntity(requestEntity);
589                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
590                try {
591                        int statusCode = -1;
592                        try {
593                                statusCode = client.executeMethod(post);
594                        } catch (Exception e) {
595                                logger.log(Level.WARNING, e.getMessage());
596                        }
597
598                        if (statusCode != HttpStatus.SC_OK) {
599                handleHttpError(statusCode,"createTree",post);
600                        } else {
601                                inputStream = post.getResponseBodyAsStream();
602                                if (inputStream != null) {
603                                        String response = IOUtils.toString(inputStream, "utf-8");
604                                        logger.info("checkPayLoad || Response " + response);
605                                        tree = CustomDateUtil.gson.fromJson(response, TCRCatalogTreeDTO.class);
606                                }
607                        }
608                } finally {
609                        if (inputStream != null) {
610                                inputStream.close();
611                        }
612                        post.releaseConnection();
613                }
614                return tree;
615
616        }
617
618        public static CyclePhaseDTO addPhaseToCycle(CyclePhaseDTO cyclePhase, AutomationJobDetail automationJobDetail) throws HttpException, IOException {
619                HttpClient client = getConnectionFromPool();
620                CyclePhaseDTO dto = null;
621                long schduleId = 0;
622                if (automationJobDetail.getFromFileWatcher()) {
623                        schduleId = automationJobDetail.getId();
624                } else {
625                        schduleId = automationJobDetail.getScheduleId();
626                }
627                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(cyclePhase),
628                                "application/json", "UTF-8");
629                PostMethod post = new PostMethod(props.getString("zephyrServerURL")
630                                + URL_ADD_PHASE_TO_CYCLE.replace("{cycleId}", String.valueOf(cyclePhase.getCycleId())) + "?scheduleId=" + schduleId);
631
632                System.out.println("""
633                                addPhaseToCycle::%s%s?scheduleId=%d""".formatted(props.getString("zephyrServerURL"), URL_ADD_PHASE_TO_CYCLE.replace("{cycleId}", String.valueOf(cyclePhase.getCycleId())), schduleId));
634
635                post.setRequestHeader("Authorization", createRequestHeader());
636                post.setRequestEntity(requestEntity);
637                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
638                InputStream inputStream = null;
639                try {
640                        int statusCode = -1;
641                        try {
642                                statusCode = client.executeMethod(post);
643                        } catch (Exception e) {
644                                logger.log(Level.WARNING, e.getMessage());
645                        }
646                        if (statusCode != HttpStatus.SC_OK) {
647                handleHttpError(statusCode,"addPhaseToCycle",post);
648                        } else {
649                                inputStream = post.getResponseBodyAsStream();
650                                if (inputStream != null) {
651                                        String response = IOUtils.toString(inputStream, "utf-8");
652                                        logger.info("checkPayLoad || Response " + response);
653                                        dto = CustomDateUtil.gson.fromJson(response, CyclePhaseDTO.class);
654                                }
655                        }
656                } finally {
657                        if (inputStream != null) {
658                                inputStream.close();
659                        }
660                        post.releaseConnection();
661                }
662                return dto;
663        }
664
665        public Set<Long> getTCRCatalogTreeIdHierarchy(Long tcrCatalogTreeId) throws IOException {
666                TCRCatalogTreeDTO tcrCatalogTreeDTO = getTreesByTreeId(tcrCatalogTreeId);
667                return getIdHierarchy(tcrCatalogTreeDTO);
668        }
669
670        private Set<Long> getIdHierarchy(TCRCatalogTreeDTO tcrCatalogTreeDTO) {
671                Set<Long> idSet = new HashSet<>();
672                for(TCRCatalogTreeDTO childNode : tcrCatalogTreeDTO.getCategories()) {
673                        idSet.addAll(getIdHierarchy(childNode));
674                }
675                idSet.add(tcrCatalogTreeDTO.getId());
676                return idSet;
677        }
678
679        public static void assignExecutions(CyclePhaseDTO cyclePhase, ZephyrConfigModel zephyrData) throws HttpException, IOException {
680                HttpClient client = getConnectionFromPool();
681                InputStream inputStream = null;
682                PutMethod post = new PutMethod(props.getString("zephyrServerURL") + URL_ASSIGN_PHASE.replace("{cyclephaseid}", String.valueOf(cyclePhase.getId())).replace("{treeId}", String.valueOf(cyclePhase.getTcrCatalogTreeId())).replace("{assignTO}", String.valueOf(zephyrData.getAssignResultsTo())));
683                post.setRequestHeader("Authorization", createRequestHeader());
684                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
685                try {
686                        int statusCode = -1;
687                        try {
688                                statusCode = client.executeMethod(post);
689                        } catch (Exception e) {
690                                logger.log(Level.WARNING, e.getMessage());
691                        }
692
693                        if (statusCode != HttpStatus.SC_OK) {
694                handleHttpError(statusCode,"assignExecutions",post);
695                        } else {
696                                inputStream = post.getResponseBodyAsStream();
697                                if (inputStream != null) {
698                                        String response = IOUtils.toString(inputStream, "utf-8");
699                                }
700                        }
701                } finally {
702                        if (inputStream != null) {
703                                inputStream.close();
704                        }
705                        post.releaseConnection();
706                }
707        }
708
709
710        public static SearchResult<ReleaseTestSchedule> inGetReleaseTestSchedules(GetMethod method)
711                        throws HttpException, IOException {
712                HttpClient client = getConnectionFromPool();
713                SearchResult<ReleaseTestSchedule> tcbe = null;
714                InputStream inputStream = null;
715                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
716
717                try {
718                        int statusCode = -1;
719                        try {
720                                statusCode = client.executeMethod(method);
721                        } catch (Exception e) {
722                                logger.log(Level.WARNING, e.getMessage());
723                        }
724                        if (statusCode != HttpStatus.SC_OK) {
725                handleHttpError(statusCode,"inGetReleaseTestSchedules",method);
726                        } else {
727                                inputStream = method.getResponseBodyAsStream();
728                                if (inputStream != null) {
729                                        String response = IOUtils.toString(inputStream, "utf-8");
730                                        logger.info("checkPayLoad || Response " + response);
731                                        Type listType = new TypeToken<SearchResult<ReleaseTestSchedule>>() {
732                                        }.getType();
733                                        tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
734                                }
735                        }
736                } finally {
737                        if (inputStream != null) {
738                                inputStream.close();
739                        }
740                        method.releaseConnection();
741                }
742                return tcbe;
743        }
744
745        public static SearchResult<ReleaseTestSchedule> getReleaseTestSchedules(CyclePhaseDTO cycle, Long releaseId)
746                        throws IOException {
747                HttpClient client = getConnectionFromPool();
748                InputStream inputStream = null;
749                String urlZblast = props.getString("zephyrServerURL")
750                                + URL_GET_RELEASE_TEST_SCHEDULES.replace("{cycleId}", Long.toString(cycle.getId()))
751                                .replace("{pageSize}", Integer.toString(1)).replace("{releaseId}", Long.toString(releaseId));
752                GetMethod method = new GetMethod(urlZblast);
753                method.setRequestHeader("Authorization", createRequestHeader());
754                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
755                SearchResult<ReleaseTestSchedule> tcbe = inGetReleaseTestSchedules(method);
756                if (tcbe.getResultSize() > 1) {
757                        urlZblast = urlZblast.replace("pagesize=1", "pagesize=" + tcbe.getResultSize());
758                        method = new GetMethod(urlZblast);
759                        method.setRequestHeader("Authorization", createRequestHeader());
760                        try {
761                                int statusCode = -1;
762                                try {
763                                        statusCode = client.executeMethod(method);
764                                } catch (Exception e) {
765                                        logger.log(Level.WARNING, e.getMessage());
766                                }
767
768                                if (statusCode != HttpStatus.SC_OK) {
769                    handleHttpError(statusCode,"getReleaseTestSchedules",method);
770                                } else {
771                                        inputStream = method.getResponseBodyAsStream();
772                                        if (inputStream != null) {
773                                                String response = IOUtils.toString(inputStream, "utf-8");
774                                                logger.info("checkPayLoad || Response " + response);
775
776                                                Type listType = new TypeToken<SearchResult<ReleaseTestSchedule>>() {
777                                                }.getType();
778                                                tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
779                                        }
780                                }
781                        } finally {
782                                if (inputStream != null) {
783                                        inputStream.close();
784                                }
785                                method.releaseConnection();
786                        }
787
788                }
789                return tcbe;
790        }
791
792        public static List<ReleaseTestSchedule> updateExecutions(List<ReleaseTestSchedule> releaseSchedulesList)
793                        throws HttpException, IOException {
794            List<ReleaseTestSchedule> tcbe = new ArrayList<>();
795                for(int i=0;i<releaseSchedulesList.size();i+=ZeeConstants.BATCH_SIZE){
796            final List<ReleaseTestSchedule> releaseTestSchedules = i + ZeeConstants.BATCH_SIZE > releaseSchedulesList.size() ? updateExecutions(releaseSchedulesList.subList(i, releaseSchedulesList.size()), ZeeConstants.BATCH_SIZE) :
797                    updateExecutions(releaseSchedulesList.subList(i, i + ZeeConstants.BATCH_SIZE), ZeeConstants.BATCH_SIZE);
798            tcbe.addAll(releaseTestSchedules);
799        }
800                return tcbe;
801
802        }
803
804    public static List<ReleaseTestSchedule> updateExecutions(List<ReleaseTestSchedule> releaseSchedulesList,int batch_size)
805            throws HttpException, IOException {
806        HttpClient client = getConnectionFromPool();
807        InputStream inputStream = null;
808        List<ReleaseTestSchedule> tcbe = null;
809
810        logger.info("RestUtil updateExecutions  Request::" + CustomDateUtil.gson.toJson(releaseSchedulesList));
811
812        StringRequestEntity requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(releaseSchedulesList),
813                "application/json", "UTF-8");
814        PostMethod post = new PostMethod(props.getString("zephyrServerURL") + URL_UPDATE_EXECUTION);
815        post.setRequestHeader("Authorization", createRequestHeader());
816        post.setRequestEntity(requestEntity);
817        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
818        try {
819            int statusCode = -1;
820            try {
821                statusCode = client.executeMethod(post);
822            } catch (Exception e) {
823                logger.log(Level.WARNING, e.getMessage());
824            }
825
826            if (statusCode != HttpStatus.SC_OK) {
827                handleHttpError(statusCode,"updateExecutions",post);
828            } else {
829                inputStream = post.getResponseBodyAsStream();
830                if (inputStream != null) {
831                    String response = IOUtils.toString(inputStream, "utf-8");
832                    logger.info("checkPayLoad || Response " + response);
833                    Type listType = new TypeToken<ArrayList<ReleaseTestSchedule>>() {
834                    }.getType();
835                    tcbe = CustomDateUtil.gson.fromJson(response, listType);
836                }
837            }
838        } finally {
839            if (inputStream != null) {
840                inputStream.close();
841            }
842            post.releaseConnection();
843        }
844        return tcbe;
845
846    }
847
848        public static List<ReleaseTestSchedule> executeAll(List<ExecutionRequest> executionRequestList)
849                        throws HttpException, IOException {
850                List<ReleaseTestSchedule> tcbe = new ArrayList<>();
851                for(int i=0;i<executionRequestList.size();i+=ZeeConstants.BATCH_SIZE){
852                        final List<ReleaseTestSchedule> releaseTestSchedules = i + ZeeConstants.BATCH_SIZE > executionRequestList.size()
853                                        ? execute(executionRequestList.subList(i, executionRequestList.size()))
854                                        : execute(executionRequestList.subList(i, i + ZeeConstants.BATCH_SIZE));
855                        tcbe.addAll(releaseTestSchedules);
856                }
857                return tcbe;
858
859        }
860
861    public static List<ReleaseTestSchedule> execute(List<ExecutionRequest> executionRequestList) throws IOException {
862                HttpClient client = getConnectionFromPool();
863                InputStream inputStream = null;
864                List<ReleaseTestSchedule> tcbe = null;
865
866                logger.info("RestUtil execute  Request::" + GsonUtil.CUSTOM_GSON.toJson(executionRequestList));
867
868                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(executionRequestList),
869                                "application/json", "UTF-8");
870                PutMethod putMethod = new PutMethod(props.getString("zephyrServerURL") + URL_EXECUTE_IN_BULK);
871                putMethod.setRequestHeader("Authorization", createRequestHeader());
872                putMethod.setRequestEntity(requestEntity);
873                putMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
874                try {
875                        int statusCode = -1;
876                        try {
877                                statusCode = client.executeMethod(putMethod);
878                        } catch (Exception e) {
879                                logger.log(Level.WARNING, e.getMessage());
880                        }
881
882                        if (statusCode != HttpStatus.SC_OK) {
883                handleHttpError(statusCode,"execute",putMethod);
884                        } else {
885                                inputStream = putMethod.getResponseBodyAsStream();
886                                if (inputStream != null) {
887                                        String response = IOUtils.toString(inputStream, "utf-8");
888                                        logger.info("checkPayLoad || Response " + response);
889                                        Type listType = new TypeToken<ArrayList<ReleaseTestSchedule>>() {
890                                        }.getType();
891                                        tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
892                                }
893                        }
894                } finally {
895                        if (inputStream != null) {
896                                inputStream.close();
897                        }
898                        putMethod.releaseConnection();
899                }
900                return tcbe;
901        }
902
903        public static List<TCRCatalogTreeDTO> getTreesByReleaseId(AutomationJobDetail releaseId, String type, int revisionId)
904                        throws HttpException, IOException {
905                HttpClient client = getConnectionFromPool();
906                List<TCRCatalogTreeDTO> tcbe = null;
907                InputStream inputStream = null;
908                String urlZblast = props.getString("zephyrServerURL")
909                                + URL_GET_PHASES.replace("{releaseid}", Long.toString(releaseId.getReleaseId())).replace("{type}", type)
910                                .replace("{revisionid}", Integer.toString(revisionId));
911                GetMethod method = new GetMethod(urlZblast);
912                method.setRequestHeader("Authorization", createRequestHeader());
913                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
914                try {
915                        int statusCode = -1;
916                        try {
917                                statusCode = client.executeMethod(method);
918                        } catch (Exception e) {
919                                logger.log(Level.WARNING, e.getMessage());
920                        }
921
922                        if (statusCode != HttpStatus.SC_OK) {
923                handleHttpError(statusCode,"getTreesByReleaseId",method);
924                        } else {
925
926                                inputStream = method.getResponseBodyAsStream();
927                                if (inputStream != null) {
928                                        String response = IOUtils.toString(inputStream, "utf-8");
929
930                                        Type listType = new TypeToken<ArrayList<TCRCatalogTreeDTO>>() {
931                                        }.getType();
932                                        tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
933
934                                }
935                        }
936                } finally {
937                        if (inputStream != null) {
938                                inputStream.close();
939                        }
940                        method.releaseConnection();
941                }
942                return tcbe;
943        }
944
945        public static TCRCatalogTreeDTO getTreesByTreeId(Long tcrCatalogTreeId)
946                        throws HttpException, IOException {
947                HttpClient client = getConnectionFromPool();
948                TCRCatalogTreeDTO tcbe = null;
949                InputStream inputStream = null;
950                String urlZblast = props.getString("zephyrServerURL")
951                                + URL_GET_PHASES_BY_ID.replace("{tcrCatalogTreeId}", String.valueOf(tcrCatalogTreeId));
952                GetMethod method = new GetMethod(urlZblast);
953                method.setRequestHeader("Authorization", createRequestHeader());
954                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
955                try {
956                        int statusCode = -1;
957                        try {
958                                statusCode = client.executeMethod(method);
959                        } catch (Exception e) {
960                                logger.log(Level.WARNING, e.getMessage());
961                        }
962
963                        if (statusCode != HttpStatus.SC_OK) {
964                handleHttpError(statusCode,"getTreesByTreeId",method);
965                        } else {
966
967                                inputStream = method.getResponseBodyAsStream();
968                                if (inputStream != null) {
969                                        String response = IOUtils.toString(inputStream, "utf-8");
970                                        tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, TCRCatalogTreeDTO.class);
971
972                                }
973                        }
974                } finally {
975                        if (inputStream != null) {
976                                inputStream.close();
977                        }
978                        method.releaseConnection();
979                }
980                return tcbe;
981        }
982
983
984        public static TCRCatalogTreeDTO createNode(TCRCatalogTreeDTO tree, String type, Long parentId, String parentName) throws IOException {
985                HttpClient client = getConnectionFromPool();
986                TCRCatalogTreeDTO treeDTO = null;
987                InputStream inputStream = null;
988                StringRequestEntity requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(tree),
989                                "application/json", "UTF-8");
990                PostMethod post = new PostMethod(
991                                props.getString("zephyrServerURL") + URL_CREATE_PHASE + "?parentid=" + parentId);
992                post.setRequestHeader("Authorization", createRequestHeader());
993                post.setRequestEntity(requestEntity);
994                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
995                try {
996                        int statusCode = -1;
997                        try {
998                                statusCode = client.executeMethod(post);
999                        } catch (Exception e) {
1000                                logger.log(Level.WARNING, e.getMessage());
1001                        }
1002
1003                        if (statusCode != HttpStatus.SC_OK) {
1004                handleHttpError(statusCode,"createNode",post);
1005                        } else {
1006
1007                                inputStream = post.getResponseBodyAsStream();
1008                                if (inputStream != null) {
1009                                        String response = IOUtils.toString(inputStream, "utf-8");
1010                                        logger.info("checkPayLoad || Response " + response);
1011                                        treeDTO = CustomDateUtil.gson.fromJson(response, TCRCatalogTreeDTO.class);
1012                                }
1013                        }
1014                } finally {
1015                        if (inputStream != null) {
1016                                inputStream.close();
1017                        }
1018                        post.releaseConnection();
1019                }
1020                treeDTO.setParentName(parentName);
1021                return treeDTO;
1022        }
1023
1024        public static UserDTO getCurrentLoggedinUser() throws HttpException, IOException {
1025                HttpClient client = getConnectionFromPool();
1026                UserDTO user = null;
1027                InputStream inputStream = null;
1028                String urlZblast = props.getString("zephyrServerURL") + URL_GET_LOGGED_IN_USER;
1029                GetMethod method = new GetMethod(urlZblast);
1030                method.setRequestHeader("Authorization", createRequestHeader());
1031                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1032                try {
1033                        int statusCode = -1;
1034                        try {
1035                                statusCode = client.executeMethod(method);
1036                        } catch (Exception e) {
1037                                logger.log(Level.WARNING, e.getMessage());
1038                        }
1039
1040                        if (statusCode != HttpStatus.SC_OK) {
1041                handleHttpError(statusCode,"getCurrentLoggedinUser",method);
1042                        } else {
1043                                inputStream = method.getResponseBodyAsStream();
1044                                if (inputStream != null) {
1045                                        String response = IOUtils.toString(inputStream, "utf-8");
1046                                        logger.info("checkPayLoad || Response " + response);
1047                                        user = GsonUtil.CUSTOM_GSON.fromJson(response, UserDTO.class);
1048                                }
1049                        }
1050                } finally {
1051                        if (inputStream != null) {
1052                                inputStream.close();
1053                        }
1054                        method.releaseConnection();
1055                }
1056                return user;
1057
1058        }
1059
1060        public static void addAttachment(Map<Long, List<File>> releaseAttachmentFile, long testerId)
1061                        throws ClientProtocolException, IOException {
1062                HttpClient client = getConnectionFromPool();
1063                InputStream inputStream = null;
1064                String res = "";
1065                DefaultHttpClient httpclient = new DefaultHttpClient();
1066                String urlZblast = props.getString("zephyrServerURL") + "/flex/upload/document/genericattachment";
1067                List<Attachment> attachmentList = new ArrayList<>();
1068                HttpPost httppost = new HttpPost(urlZblast);
1069                httppost.addHeader("Authorization", createRequestHeader());
1070                httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1071                Type listType = new TypeToken<ArrayList<AttachmentDTO>>() {
1072                }.getType();
1073                for (Entry<Long, List<File>> iterator : releaseAttachmentFile.entrySet()) {
1074                        List<File> attachments = iterator.getValue();
1075                        for (File attachmentFile : attachments) {
1076                                try {
1077                                        FileBody bin = new FileBody(attachmentFile);
1078                                        MultipartEntity reqEntity = new MultipartEntity();
1079                                        reqEntity.addPart("fileItem", bin);
1080                                        httppost.setEntity(reqEntity);
1081                                        HttpResponse response = httpclient.execute(httppost);
1082                                        HttpEntity resEntity = response.getEntity();
1083                                        inputStream = resEntity.getContent();
1084                                        if (inputStream != null) {
1085                                                res = IOUtils.toString(inputStream, "utf-8");
1086                                                inputStream.close();
1087                                        }
1088                                        List<AttachmentDTO> attachment = GsonUtil.CUSTOM_GSON.fromJson(res, listType);
1089
1090                                        Attachment attach = new Attachment();
1091
1092                                        attach.setContentType("text/plain");
1093                                        attach.setCreatedBy(testerId);// tester id
1094                                        attach.setFileSize(String.valueOf(attachmentFile.length()));
1095                                        attach.setItemId(iterator.getKey());// get release schedule id
1096                                        attach.setItemType("releaseTestSchedule");
1097                                        attach.setName(attachment.get(0).getFileName());
1098                                        attach.setTempPath(attachment.get(0).getTempFilePath());
1099                                        attach.setTimeStamp(new Date());
1100                                        attachmentList.add(attach);
1101                                        StringRequestEntity requestEntity;
1102                                        requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(attachmentList),
1103                                                        "application/json", "UTF-8");
1104                                        PostMethod post = new PostMethod(
1105                                                        props.getString("zephyrServerURL") + "/flex/services/rest/v3/attachment/list");
1106                                        post.setRequestHeader("Authorization",createRequestHeader());
1107                                        post.setRequestEntity(requestEntity);
1108                                        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1109                                        try {
1110                                                int statusCode = -1;
1111                                                try {
1112                                                        statusCode = client.executeMethod(post);
1113                                                } catch (Exception e) {
1114                                                        logger.log(Level.WARNING, e.getMessage());
1115                                                }
1116
1117                                                if (statusCode != HttpStatus.SC_OK) {
1118                            handleHttpError(statusCode,"addAttachment",post);
1119                                                } else {
1120                                                        logger.log(Level.WARNING, "checkPayload(): " + response);
1121                                                }
1122                                        } finally {
1123                                                post.releaseConnection();
1124                                        }
1125                                        attachmentList.clear();
1126                                } catch (IOException e) {
1127                                        logger.log(Level.WARNING, "ERROR: failure in attachments: " + e);
1128                                }
1129                        }
1130                }
1131        }
1132
1133        public static List<TestStepResult> updateStepExecutions(List<TestStepResult> releaseStepList) throws IOException {
1134                if(releaseStepList==null || releaseStepList.isEmpty()){
1135                        return Collections.emptyList();
1136                }
1137                List<TestStepResult> tcbe = new ArrayList<>();
1138                for(int i=0;i<releaseStepList.size();i+=ZeeConstants.BATCH_SIZE){
1139            final List<TestStepResult> testStepResults = i + ZeeConstants.BATCH_SIZE > releaseStepList.size() ? updateStepExecutions(releaseStepList.subList(i, releaseStepList.size()), ZeeConstants.BATCH_SIZE) :
1140                    updateStepExecutions(releaseStepList.subList(i, i + ZeeConstants.BATCH_SIZE), ZeeConstants.BATCH_SIZE);
1141            tcbe.addAll(testStepResults);
1142        }
1143                return tcbe;
1144        }
1145
1146    public static List<TestStepResult> updateStepExecutions(List<TestStepResult> releaseStepList , int batchSize) throws IOException {
1147        if(releaseStepList==null || releaseStepList.isEmpty()){
1148            return Collections.emptyList();
1149        }
1150        HttpClient client = getConnectionFromPool();
1151        List<TestStepResult> tcbe = null;
1152        InputStream inputStream = null;
1153        StringRequestEntity requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(releaseStepList),
1154                "application/json", "UTF-8");
1155        PostMethod post = new PostMethod(props.getString("zephyrServerURL") + URL_UPDATE_STEP_EXECUTION);
1156        post.setRequestHeader("Authorization", createRequestHeader());
1157        post.setRequestEntity(requestEntity);
1158        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1159        try {
1160            int statusCode = -1;
1161            try {
1162                statusCode = client.executeMethod(post);
1163            } catch (Exception e) {
1164                logger.log(Level.WARNING, e.getMessage());
1165            }
1166
1167            if (statusCode != HttpStatus.SC_OK) {
1168                handleHttpError(statusCode,"updateStepExecutions",post);
1169            } else {
1170
1171                inputStream = post.getResponseBodyAsStream();
1172                if (inputStream != null) {
1173                    String response = IOUtils.toString(inputStream, "utf-8");
1174                    logger.info("checkPayLoad || Response " + response);
1175
1176                    Type listType = new TypeToken<ArrayList<TestStepResult>>() {
1177                    }.getType();
1178                    tcbe = CustomDateUtil.gson.fromJson(response, listType);
1179                }
1180            }
1181        } finally {
1182            if (inputStream != null) {
1183                inputStream.close();
1184            }
1185            post.releaseConnection();
1186        }
1187        return tcbe;
1188    }
1189
1190        public static TestStep getStepsForTestcase(Long testcaseId) throws IOException {
1191                HttpClient client = getConnectionFromPool();
1192                InputStream inputStream = null;
1193                TestStep steps = null;
1194                GetMethod method = new GetMethod(props.getString("zephyrServerURL") + URL_GET_TESTSTEPS.replace("{testcaseId}", testcaseId.toString()));
1195
1196                method.setRequestHeader("Authorization", createRequestHeader());
1197                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1198                try {
1199                        int statusCode = -1;
1200                        try {
1201                                statusCode = client.executeMethod(method);
1202                        } catch (Exception e) {
1203                                logger.log(Level.WARNING, e.getMessage());
1204                        }
1205
1206                        if (statusCode != HttpStatus.SC_OK) {
1207                handleHttpError(statusCode,"getStepsForTestcase",method);
1208                        } else {
1209
1210                                inputStream = method.getResponseBodyAsStream();
1211                                if (inputStream != null) {
1212                                        String response = IOUtils.toString(inputStream, "utf-8");
1213                                        logger.info("checkPayLoad || Response " + response);
1214
1215                                        steps = CustomDateUtil.gson.fromJson(response, TestStep.class);
1216                                }
1217                        }
1218                } finally {
1219                        if (inputStream != null) {
1220                                inputStream.close();
1221                        }
1222                        method.releaseConnection();
1223                }
1224                return steps;
1225        }
1226
1227        public static void browseTestcases(CyclePhaseDTO cyclePhase, List<TreeSelectionInfo> selectionTree, Boolean createPackage)
1228                        throws IOException {
1229                HttpClient client = getConnectionFromPool();
1230                String response = "";
1231                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(selectionTree),
1232                                "application/json", "UTF-8");
1233                PostMethod post = new PostMethod(props.getString("zephyrServerURL")
1234                                + URL_BROWSE_TESTCASES_TO_PHASE.replace("{cyclephaseid}", String.valueOf(cyclePhase.getId()))
1235                                .replace("{parenttreeid}", String.valueOf(cyclePhase.getTcrCatalogTreeId())).replace("{createPackage}", String.valueOf(createPackage)));
1236                post.setRequestHeader("Authorization", createRequestHeader());
1237                post.setRequestEntity(requestEntity);
1238                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1239
1240                InputStream inputStream = null;
1241                try {
1242                        int statusCode = -1;
1243                        try {
1244                                statusCode = client.executeMethod(post);
1245                        } catch (Exception e) {
1246                                logger.log(Level.WARNING, e.getMessage());
1247                        }
1248                        if (statusCode != HttpStatus.SC_OK) {
1249                handleHttpError(statusCode,"browseTestcases",post);
1250                        } else {
1251                                inputStream = post.getResponseBodyAsStream();
1252                                if (inputStream != null) {
1253                                        response = IOUtils.toString(inputStream, "utf-8");
1254                                        logger.info("checkPayLoad || Response " + response);
1255                                }
1256                        }
1257                } finally {
1258                        if (inputStream != null) {
1259                                inputStream.close();
1260                        }
1261                        post.releaseConnection();
1262                }
1263        }
1264
1265        public static boolean logout(Agent agent) throws IOException {
1266                HttpClient client = getConnectionFromPool();
1267                boolean isAlive = false;
1268                PostMethod method = new PostMethod(getURL());
1269                InputStream inputStream = null;
1270                try {
1271                        method.setParameter(ZeeConstants.PARAM_ACTION_REQUEST, ZeeConstants.ACTION_LOGOUT);
1272                        method.setParameter(ZeeConstants.PARAM_TOKEN_REQUEST, agent.getToken());
1273                        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1274                        // Execute the method.
1275                        int statusCode = -1;
1276                        try {
1277                                statusCode = client.executeMethod(method);
1278                        } catch (Exception e) {
1279                                logger.log(Level.WARNING, e.getMessage());
1280                        }
1281
1282                        if (statusCode != HttpStatus.SC_OK) {
1283                handleHttpError(statusCode,"logout",method);
1284                                isAlive = false;
1285                        } else {
1286                                inputStream = method.getResponseBodyAsStream();
1287                                if (inputStream != null) {
1288                                        String response = IOUtils.toString(inputStream, "utf-8");
1289                                        logger.info(" logout " + response);
1290                                        if (response != null && response.equalsIgnoreCase(ZeeConstants.STATUS_LOGOUT)) {
1291                                                logger.info("Logout successful.");
1292                                        } else {
1293                                                logger.info("Logout forced. response: " + response);
1294                                        }
1295                                }
1296                        }
1297                } finally {
1298                        if (inputStream != null) {
1299                                inputStream.close();
1300                        }
1301                        method.releaseConnection();
1302                }
1303                return isAlive;
1304        }
1305
1306        public static String login(boolean multiThreading, String zBotname) throws IOException {
1307                String response = null;
1308                HttpClient client = getConnectionFromPool();
1309                PostMethod method = new PostMethod(getURL());
1310                InputStream inputStream = null;
1311                try {
1312                        method.setParameter(ZeeConstants.PARAM_ACTION_REQUEST, ZeeConstants.ACTION_LOGIN);
1313            if(zBotname==null){
1314                zBotname="";
1315            }
1316            //setting zBot name if not entered by user then default Host and IP combination will be displayed
1317            if(ZeeConstants.DEFAULT_ZBOT_NAME.equals(zBotname)){
1318                logger.info("Zbot is login to Zephyr with default name :" + InetAddress.getLocalHost().getHostName());
1319                method.setParameter(ZeeConstants.PARAM_HOST_REQUEST, InetAddress.getLocalHost().getHostName());
1320            }else if(zBotname.trim().equals("")){
1321                logger.info("Zbot is login to Zephyr with default name as zbotname is blank :" + InetAddress.getLocalHost().getHostName());
1322                            method.setParameter(ZeeConstants.PARAM_HOST_REQUEST, InetAddress.getLocalHost().getHostName());
1323            }else {
1324                logger.info("Zbot is login to Zephyr with name provided in download :" + zBotname);
1325                method.setParameter(ZeeConstants.PARAM_HOST_REQUEST, zBotname);
1326            }
1327                        method.setParameter(ZeeConstants.PARAM_AGENT_MULTITHREADING, "" + multiThreading);
1328                        // Provide custom retry handler is necessary
1329                        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1330                        int statusCode = -1;
1331                        try {
1332                                statusCode = client.executeMethod(method);
1333                        } catch (Exception e) {
1334                                logger.log(Level.WARNING, e.getMessage());
1335                        }
1336
1337                        if (statusCode != HttpStatus.SC_OK) {
1338                handleHttpError(statusCode,"login",method);
1339
1340                        } else {
1341                                inputStream = method.getResponseBodyAsStream();
1342                                if (inputStream != null) {
1343                                        response = IOUtils.toString(inputStream, "utf-8");
1344                                        logger.info("login || response : " + response);
1345                                }
1346                        }
1347                } finally {
1348                        if (inputStream != null) {
1349                                inputStream.close();
1350                        }
1351                        method.releaseConnection();
1352                }
1353                return response;
1354        }
1355
1356        public static List<SearchResult<TCRCatalogTreeTestcase>> searchTestcaseOnName(String name, long releaseId) throws IOException {
1357                HttpClient client = getConnectionFromPool();
1358                InputStream inputStream = null;
1359                List<SearchResult<TCRCatalogTreeTestcase>> tcbe = null;
1360                String urlZblast = props.getString("zephyrServerURL")
1361                                + URL_SEARCH_TESTCASES_ON_NAME.replace("{testCaseName}", URLEncoder.encode("name ~ \"" + name + "\"", StandardCharsets.UTF_8.toString())).replace("{releaseId}", String.valueOf(releaseId));
1362                GetMethod method = new GetMethod(urlZblast);
1363                method.setRequestHeader("Authorization", createRequestHeader());
1364                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1365                try {
1366                        int statusCode = -1;
1367                        try {
1368                                statusCode = client.executeMethod(method);
1369                        } catch (Exception e) {
1370                                logger.log(Level.WARNING, e.getMessage());
1371                        }
1372                        if (statusCode != HttpStatus.SC_OK) {
1373                handleHttpError(statusCode,"searchTestcaseOnName",method);
1374                        } else {
1375                                inputStream = method.getResponseBodyAsStream();
1376                                if (inputStream != null) {
1377                                        String response = IOUtils.toString(inputStream, "utf-8");
1378                                        logger.info("checkPayLoad || Response " + response);
1379
1380                                        Type listType = new TypeToken<List<SearchResult<TCRCatalogTreeTestcase>>>() {
1381                                        }.getType();
1382                                        tcbe = GsonUtil.CUSTOM_GSON.fromJson(response, listType);
1383
1384                                }
1385                        }
1386                } finally {
1387                        if (inputStream != null) {
1388                                inputStream.close();
1389                        }
1390                        method.releaseConnection();
1391                }
1392
1393                return tcbe;
1394        }
1395
1396        public static void updateStatus(Long scheduleId, String zblastJobStatusInprogress, AutomationJobDetail automationJob, long cycleId) throws HttpException, IOException {
1397                if (automationJob.getFromFileWatcher()) {
1398                        RestUtil.updateFileWatcher(automationJob, ZeeConstants.ZBLAST_FILE_JOB_STATUS_RUNNING, zblastJobStatusInprogress);
1399                } else {
1400                        String cycle = (cycleId != 0) ? String.valueOf(cycleId) : null;
1401                        RestUtil.updateZblastScheduleStatus(scheduleId, zblastJobStatusInprogress, cycle, automationJob);
1402                }
1403        }
1404
1405        /**
1406         * Input: method sends agent.token attribute Output: can be one of these:
1407         * TestcaseBatchExecution object in JSON format. i.e. task to be processed
1408         * blank string, i.e. no task to be processed STATUS_SESSION_EXPIRED, i.e.
1409         * session expired.
1410         *
1411         * @throws HttpException
1412         * @throws IOException
1413         */
1414        public static AutomationJobSet checkPayLoadForZblast(String status, Agent agent) throws HttpException, IOException {
1415                HttpClient client = getConnectionFromPool();
1416                AutomationJobSet automationJobSet = null;
1417                InputStream inputStream = null;
1418                PropertiesConfiguration props = Utils.getZbotProperties();
1419                String urlZblast = getURLZblast();
1420                String encodedQueryString = URLEncoder.encode(agent.getAgentHostAndIp(), "utf-8");
1421                urlZblast += """
1422                                ?%s=%s""".formatted(ZeeConstants.ZBLAST_AGENT_MACHINE, encodedQueryString);
1423                logger.info("Zblast payload URL: " + urlZblast);
1424                GetMethod method = new GetMethod(urlZblast);
1425                try {
1426                        logger.info("encodedQueryString for Zblast :" + encodedQueryString);
1427                        method.setQueryString(ZeeConstants.ZBLAST_AGENT_MACHINE + "=" + encodedQueryString);
1428                        method.setRequestHeader("Authorization", createRequestHeader());
1429                        // Provide custom retry handler is necessary
1430                        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1431                        // Execute the method.
1432                        int statusCode = -1;
1433                        try {
1434                                statusCode = client.executeMethod(method);
1435                        } catch (Exception e) {
1436                                logger.log(Level.WARNING, e.getMessage());
1437                        }
1438
1439                        if (statusCode != HttpStatus.SC_OK) {
1440                handleHttpError(statusCode,"checkPayLoadForZblast",method);
1441                        } else {
1442                                inputStream = method.getResponseBodyAsStream();
1443                                String response = IOUtils.toString(inputStream, "utf-8");
1444                                if (response != null) {
1445                                        if (response.equals("{}")) {
1446                                                return null;
1447                                        } else {
1448                                                automationJobSet = CustomDateUtil.gson.fromJson(response, AutomationJobSet.class);
1449                                        }
1450                                } else {
1451                                        logger.log(Level.WARNING, "ERROR: checkPayload(): " + response);
1452                                }
1453                        }
1454                } finally {
1455                        if (inputStream != null) {
1456                                inputStream.close();
1457                        }
1458                        method.releaseConnection();
1459                }
1460                return automationJobSet;
1461        }
1462
1463
1464        public static List<AutomationJobDetail> getFileWatcherJobs(Agent agent) throws UnsupportedEncodingException {
1465                HttpClient client = getConnectionFromPool();
1466                PropertiesConfiguration props = Utils.getZbotProperties();
1467                String urlZblast = getURLFileWatcher();
1468                String encodedQueryString = URLEncoder.encode(agent.getAgentHostAndIp(), "utf-8");
1469                urlZblast += """
1470                                ?%s=%s""".formatted(ZeeConstants.ZBLAST_AGENT_MACHINE, encodedQueryString);
1471                logger.info("Zblast payload URL: " + urlZblast);
1472                GetMethod method = new GetMethod(urlZblast);
1473                try {
1474                        logger.info("encodedQueryString for Zblast :" + encodedQueryString);
1475                        method.setQueryString(ZeeConstants.ZBLAST_AGENT_MACHINE + "=" + encodedQueryString);
1476                        method.setRequestHeader("Authorization", createRequestHeader());
1477                        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1478                        int statusCode = -1;
1479                        try {
1480                                statusCode = client.executeMethod(method);
1481                        } catch (Exception e) {
1482                                logger.log(Level.WARNING, e.getMessage());
1483                        }
1484                        if (statusCode != HttpStatus.SC_OK) {
1485                handleHttpError(statusCode,"getFileWatcherJobs",method);
1486                        } else {
1487                                InputStream inputStream = method.getResponseBodyAsStream();
1488                                String response = IOUtils.toString(inputStream, "utf-8");
1489                                logger.info("checkPayLoad for Zblast || Response " + response);
1490                                if (response != null) {
1491                                        if (response.equals("{}")) {
1492                                                return null;
1493                                        } else {
1494                                                Type listType = new TypeToken<List<AutomationJobDetail>>() {
1495                                                }.getType();
1496                                                List<AutomationJobDetail> tcbe = CustomDateUtil.gson.fromJson(response, listType);
1497                                                return tcbe;
1498                                        }
1499                                } else {
1500                                        logger.log(Level.WARNING, "ERROR: checkPayload(): " + response);
1501                                }
1502                        }
1503                } catch (IOException e) {
1504                        logger.log(Level.WARNING, "ERROR: checkPayload(): " + e.getMessage());
1505                } finally {
1506                        method.releaseConnection();
1507                }
1508                return null;
1509        }
1510
1511        public static String updateAutomationStatusInBulk(LongIdListRequest ids, String status) throws IOException {
1512
1513                String response = "";
1514                HttpClient client = getConnectionFromPool();
1515                String zblastScheduleStatusUpdateURL = props.getString("zephyrServerURL")
1516                                + URL_BULK_AUTOMATION_UPDATE + "?status=" + URLEncoder.encode(status, StandardCharsets.UTF_8.toString());
1517                InputStream inputStream = null;
1518                PutMethod method = new PutMethod(zblastScheduleStatusUpdateURL);
1519                StringRequestEntity requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(ids),
1520                                "application/json", "UTF-8");
1521                method.setRequestEntity(requestEntity);
1522                method.setRequestHeader("Authorization", createRequestHeader());
1523                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1524
1525                try {
1526                        int statusCode = -1;
1527                        try {
1528                                statusCode = client.executeMethod(method);
1529                        } catch (Exception e) {
1530                                logger.log(Level.WARNING, e.getMessage());
1531                        }
1532
1533                        if (statusCode != HttpStatus.SC_OK) {
1534                handleHttpError(statusCode,"updateAutomationStatusInBulk",method);
1535                        } else {
1536                                inputStream = method.getResponseBodyAsStream();
1537                                if (inputStream != null) {
1538                                        response = IOUtils.toString(inputStream, "utf-8");
1539                                        logger.info("checkPayLoad || Response " + response);
1540                                }
1541                        }
1542                } finally {
1543                        if (inputStream != null) {
1544                                inputStream.close();
1545                        }
1546                        method.releaseConnection();
1547                }
1548                return response;
1549        }
1550
1551
1552        public static List<AutomationJobScheduleDTO> createScheduleForSchduledJobs(AutomationJobDetail automationJobDetail, String status) throws HttpException, IOException {
1553
1554                List<AutomationJobScheduleDTO> automationJobScheduleDTOs = null;
1555                logger.info("createScheduleForSchduledJobs ......");
1556                try {
1557
1558                        Long automationJobDetailId = automationJobDetail.getId().longValue();
1559
1560                        logger.info(">>in createScheduleForSchduledJobs automationJobDetail :::" + automationJobDetail);
1561
1562
1563                        List<Long> jobScheduledDetailIds = new ArrayList<>();
1564                        jobScheduledDetailIds.add(automationJobDetailId);
1565
1566
1567                        LongIdListRequest request = new LongIdListRequest(jobScheduledDetailIds);
1568
1569
1570                        HttpClient client = RestUtil.getConnectionFromPool();
1571
1572                        InputStream inputStream = null;
1573
1574                        logger.info("GsonUtil.CUSTOM_GSON.toJson(jobScheduledDetailIds):::" + GsonUtil.CUSTOM_GSON.toJson(request));
1575
1576
1577                        StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(request), "application/json", "UTF-8");
1578
1579                        String queryString = """
1580                                        ?cycleName=%s&assignedUser=%s&addTimeStamp=false&phaseName=%s&status=%s""".formatted(
1581                                        URLEncoder.encode(automationJobDetail.getCycleName(), StandardCharsets.UTF_8.toString()),
1582                                        automationJobDetail.getResultsAssignedTo(),
1583                                        URLEncoder.encode(automationJobDetail.getPhaseName(), StandardCharsets.UTF_8.toString()),
1584                                        status
1585                        );
1586
1587                        logger.info(">>URL:" + props.getString("zephyrServerURL") + URL_JOB_SCHEDULED + queryString);
1588
1589
1590                        PostMethod method = new PostMethod(props.getString("zephyrServerURL") + URL_JOB_SCHEDULED + queryString);
1591                        method.setRequestHeader("Authorization", createRequestHeader());
1592                        method.setRequestEntity(requestEntity);
1593                        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1594                        try {
1595                                int statusCode = -1;
1596                                try {
1597
1598                                        statusCode = client.executeMethod(method);
1599                                        logger.info(">>>statusCode........" + statusCode);
1600                                } catch (Exception e) {
1601                                        logger.info("Exceptions........");
1602                                        e.printStackTrace();
1603                                        logger.log(Level.WARNING, e.getMessage());
1604                                }
1605                                if (statusCode != HttpStatus.SC_OK) {
1606                    handleHttpError(statusCode,"createScheduleForSchduledJobs",method);
1607                                } else {
1608                                        inputStream = method.getResponseBodyAsStream();
1609                                        if (inputStream != null) {
1610                                                String response = IOUtils.toString(inputStream, "utf-8");
1611                                                logger.info("checkPayLoad || Response " + response);
1612                                                Type listType = new TypeToken<ArrayList<AutomationJobScheduleDTO>>() {
1613                                                }.getType();
1614                                                automationJobScheduleDTOs = CustomDateUtil.gson.fromJson(response, listType);
1615                                        }
1616                                }
1617                        } finally {
1618                                if (inputStream != null) {
1619                                        inputStream.close();
1620                                }
1621                                method.releaseConnection();
1622                        }
1623
1624
1625                } catch (Exception e) {
1626                        e.printStackTrace();
1627                }
1628                return automationJobScheduleDTOs;
1629        }
1630
1631        public static String updateAutomationScheduledJobStatus(Long id, String status) throws HttpException, IOException {
1632                String response = "";
1633                HttpClient client = getConnectionFromPool();
1634                String zblastScheduleStatusUpdateURL = """
1635                                %s?detailid=%d&status=%s""".formatted(getURLZblastAutomationScheduleJobUpdateStatus(), id, URLEncoder.encode(status, StandardCharsets.UTF_8.toString()));
1636                logger.info("zblastScheduleStatusUpdateURL::" + zblastScheduleStatusUpdateURL);
1637
1638                InputStream inputStream = null;
1639                PutMethod method = new PutMethod(zblastScheduleStatusUpdateURL);
1640                method.setRequestHeader("Authorization", createRequestHeader());
1641                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1642
1643                try {
1644                        int statusCode = -1;
1645                        try {
1646                                logger.info("******updateAutomationScheduledJobStatus************");
1647                                statusCode = client.executeMethod(method);
1648                                logger.info("statusCode :::" + statusCode);
1649                        } catch (Exception e) {
1650                                logger.log(Level.WARNING, e.getMessage());
1651                        }
1652
1653                        if (statusCode != HttpStatus.SC_OK) {
1654                handleHttpError(statusCode,"updateAutomationScheduledJobStatus",method);
1655                        } else {
1656                                inputStream = method.getResponseBodyAsStream();
1657                                if (inputStream != null) {
1658                                        response = IOUtils.toString(inputStream, "utf-8");
1659                                        logger.info("checkPayLoad || Response " + response);
1660                                }
1661                        }
1662                } finally {
1663                        if (inputStream != null) {
1664                                inputStream.close();
1665                        }
1666                        method.releaseConnection();
1667                }
1668                return response;
1669        }
1670
1671        private static String getURLZblastAutomationScheduleJobUpdateStatus() {
1672                return props.getString("zephyrServerURL") + ZeeConstants.URL_AUTOMATION_SCHEDULED_JOB_UPDATE;
1673        }
1674
1675        private static String getURLZblastAutomationScheduleJob() {
1676                return props.getString("zephyrServerURL") + ZeeConstants.URL_AUTOMATION_SCHEDULED_JOB_PROGRESS;
1677        }
1678
1679        private static String getURLZblastAutomationScheduleFailedTestcasesJob() {
1680                return props.getString("zephyrServerURL") + ZeeConstants.URL_AUTOMATION_SCHEDULED_FAILED_TCS_JOB;
1681        }
1682
1683        public static void postProgressDetails(JobProgressDTO dto) throws IOException {
1684
1685                String response = "";
1686                HttpClient client = getConnectionFromPool();
1687                String postProgressDetailsURL = getURLZblastAutomationScheduleJob();
1688
1689                logger.info("postProgressDetailsURL::" + postProgressDetailsURL);
1690                logger.info("post data ::" + GsonUtil.CUSTOM_GSON.toJson(dto));
1691
1692                InputStream inputStream = null;
1693                PostMethod method = new PostMethod(postProgressDetailsURL);
1694
1695                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(dto),
1696                                "application/json", "UTF-8");
1697
1698                method.setRequestHeader("Authorization", createRequestHeader());
1699                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1700                method.setRequestEntity(requestEntity);
1701                try {
1702                        int statusCode = -1;
1703                        try {
1704                                logger.info("******UpdatepostProgressDetails************");
1705                                statusCode = client.executeMethod(method);
1706                                logger.info("postProgressDetails statusCode :::" + statusCode);
1707                        } catch (Exception e) {
1708                                logger.log(Level.WARNING, e.getMessage());
1709                        }
1710
1711                        if (statusCode != HttpStatus.SC_OK) {
1712                handleHttpError(statusCode,"postProgressDetails",method);
1713                        } else {
1714                                inputStream = method.getResponseBodyAsStream();
1715                                if (inputStream != null) {
1716                                        response = IOUtils.toString(inputStream, "utf-8");
1717                                        logger.info("checkPayLoad || Response " + response);
1718                                }
1719                        }
1720                } finally {
1721                        if (inputStream != null) {
1722                                inputStream.close();
1723                        }
1724                        method.releaseConnection();
1725                }
1726                logger.info(response);
1727        }
1728
1729        public static List<ScheduledTestCaseMetaDataDTO> getFailedTCSMetadata(int schedulerId) throws HttpException, IOException {
1730                HttpClient client = getConnectionFromPool();
1731                List<ScheduledTestCaseMetaDataDTO> scheduledTestCaseMetaDataDTOs = null;
1732                InputStream inputStream = null;
1733                PropertiesConfiguration props = Utils.getZbotProperties();
1734                String username = props.getString(ZeeConstants.USERNAME);
1735                String password = CodecUtils.decrypt(props.getString(ZeeConstants.ENC_PWD));
1736                String cred = username + ":" + password;
1737                String urlZblast = getURLZblastAutomationScheduleFailedTestcasesJob();
1738                logger.info("""
1739                                Zblast payload URL: %s?schedulerId=%d""".formatted(urlZblast, schedulerId));
1740                GetMethod method = new GetMethod(urlZblast);
1741                try {
1742
1743                        method.setQueryString("schedulerId" + "=" + schedulerId);
1744                        method.setRequestHeader("Authorization", createRequestHeader());
1745                        // Provide custom retry handler is necessary
1746                        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1747                        // Execute the method.
1748                        int statusCode = -1;
1749                        try {
1750                                statusCode = client.executeMethod(method);
1751                        } catch (Exception e) {
1752                                logger.log(Level.WARNING, e.getMessage());
1753                        }
1754
1755                        if (statusCode != HttpStatus.SC_OK) {
1756                handleHttpError(statusCode,"getFailedTCSMetadata",method);
1757                        } else {
1758                                inputStream = method.getResponseBodyAsStream();
1759                                String response = IOUtils.toString(inputStream, "utf-8");
1760                                if (response != null) {
1761                                        if (response.equals("{}")) {
1762                                                return null;
1763                                        } else {
1764                                                Type listType = new TypeToken<ArrayList<ScheduledTestCaseMetaDataDTO>>() {
1765                                                }.getType();
1766                                                scheduledTestCaseMetaDataDTOs = CustomDateUtil.gson.fromJson(response, listType);
1767                                        }
1768                                } else {
1769                                        logger.log(Level.WARNING, "ERROR: checkPayload(): " + response);
1770                                }
1771                        }
1772                } finally {
1773                        if (inputStream != null) {
1774                                inputStream.close();
1775                        }
1776                        method.releaseConnection();
1777                }
1778                return scheduledTestCaseMetaDataDTOs;
1779        }
1780
1781        public static boolean updateFailedTestExecutions(List<ScheduledTestCaseMetaDataDTO> scheduledTestCaseMetaDataDTOResults) throws HttpException, IOException {
1782                HttpClient client = getConnectionFromPool();
1783                InputStream inputStream = null;
1784                boolean status = false;
1785
1786                logger.info("RestUtil scheduledTestCaseMetaDataDTOResults  Request::" + CustomDateUtil.gson.toJson(scheduledTestCaseMetaDataDTOResults));
1787
1788                StringRequestEntity requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(scheduledTestCaseMetaDataDTOResults),
1789                                "application/json", "UTF-8");
1790                PostMethod post = new PostMethod(props.getString("zephyrServerURL") + URL_UPDATE_FAILED_TESTCASE_EXECUTION);
1791                post.setRequestHeader("Authorization", createRequestHeader());
1792                post.setRequestEntity(requestEntity);
1793                post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1794                try {
1795                        int statusCode = -1;
1796                        try {
1797                                statusCode = client.executeMethod(post);
1798                        } catch (Exception e) {
1799                                logger.log(Level.WARNING, e.getMessage());
1800                        }
1801
1802                        if (statusCode != HttpStatus.SC_OK) {
1803                handleHttpError(statusCode,"updateFailedTestExecutions",post);
1804                        } else {
1805                                inputStream = post.getResponseBodyAsStream();
1806                                if (inputStream != null) {
1807                                        String response = IOUtils.toString(inputStream, "utf-8");
1808                                        logger.info("checkPayLoad || Response " + response);
1809
1810                                        status = CustomDateUtil.gson.fromJson(response, Boolean.class);
1811
1812                                        System.out.println("status....." + status);
1813                                }
1814                        }
1815                } finally {
1816                        if (inputStream != null) {
1817                                inputStream.close();
1818                        }
1819                        post.releaseConnection();
1820                }
1821                return status;
1822
1823        }
1824
1825        public static CycleDTO getCycle(Long cycleId) throws IOException {
1826                HttpClient client = getConnectionFromPool();
1827                CycleDTO cycle = null;
1828                InputStream inputStream = null;
1829                String urlZblast = props.getString("zephyrServerURL") + URL_GET_CYCLE_BY_ID.replace("{cycleId}", Long.toString(cycleId));
1830                GetMethod method = new GetMethod(urlZblast);
1831                method.setRequestHeader("Authorization", createRequestHeader());
1832                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1833                try {
1834                        int statusCode = -1;
1835                        try {
1836                                statusCode = client.executeMethod(method);
1837                        } catch (Exception e) {
1838                                logger.log(Level.WARNING, e.getMessage());
1839                        }
1840                        if (statusCode != HttpStatus.SC_OK) {
1841                handleHttpError(statusCode,"getCycle",method);
1842                        } else {
1843                                inputStream = method.getResponseBodyAsStream();
1844                                if (inputStream != null) {
1845                                        String response = IOUtils.toString(inputStream, "utf-8");
1846                                        cycle = GsonUtil.CUSTOM_GSON.fromJson(response, CycleDTO.class);
1847                                }
1848                        }
1849                } finally {
1850                        if (inputStream != null) {
1851                                inputStream.close();
1852                        }
1853                        method.releaseConnection();
1854                }
1855                return cycle;
1856        }
1857
1858        public static CycleDTO getCycleNames(Long releaseId,String sortBy,String cycleName) throws IOException {
1859                HttpClient client = getConnectionFromPool();
1860                CycleDTO cycle = null;
1861                InputStream inputStream = null;
1862                String urlZblast = props.getString("zephyrServerURL") + URL_GET_CYCLE_NAMES.replace("{releaseid}",releaseId.toString())
1863                                .replace("{cycleName}", URLEncoder.encode(cycleName,"utf-8")).replace("{sortBy}","createdOn");
1864                GetMethod method = new GetMethod(urlZblast);
1865                method.setRequestHeader("Authorization", createRequestHeader());
1866                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1867                try {
1868                        int statusCode = -1;
1869                        try {
1870                                statusCode = client.executeMethod(method);
1871                        } catch (Exception e) {
1872                                logger.log(Level.WARNING, e.getMessage());
1873                        }
1874                        if (statusCode != HttpStatus.SC_OK) {
1875                handleHttpError(statusCode,"getCycleNames",method);
1876                        } else {
1877                                inputStream = method.getResponseBodyAsStream();
1878                                if (inputStream != null) {
1879                                        String response = IOUtils.toString(inputStream, "utf-8");
1880                                        cycle = GsonUtil.CUSTOM_GSON.fromJson(response, CycleDTO.class);
1881                                }
1882                        }
1883                } finally {
1884                        if (inputStream != null) {
1885                                inputStream.close();
1886                        }
1887                        method.releaseConnection();
1888                }
1889                return cycle;
1890        }
1891
1892    public static void addTestCaseAttachment(Map<Long, List<File>> testCaseAttachmentFile, long testerId)
1893            throws ClientProtocolException, IOException {
1894        HttpClient client = getConnectionFromPool();
1895        InputStream inputStream = null;
1896        String res = "";
1897        DefaultHttpClient httpclient = new DefaultHttpClient();
1898        String urlZblast = props.getString("zephyrServerURL") + "/flex/upload/document/genericattachment";
1899        List<Attachment> attachmentList = new ArrayList<>();
1900        HttpPost httppost = new HttpPost(urlZblast);
1901                httppost.addHeader("Authorization", createRequestHeader());
1902        httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1903        Type listType = new TypeToken<ArrayList<AttachmentDTO>>() {
1904        }.getType();
1905        for (Entry<Long, List<File>> iterator : testCaseAttachmentFile.entrySet()) {
1906            List<File> attachments = iterator.getValue();
1907            for (File attachmentFile : attachments) {
1908                try {
1909                    FileBody bin = new FileBody(attachmentFile);
1910                    MultipartEntity reqEntity = new MultipartEntity();
1911                    reqEntity.addPart("fileItem", bin);
1912                    httppost.setEntity(reqEntity);
1913                    HttpResponse response = httpclient.execute(httppost);
1914                    HttpEntity resEntity = response.getEntity();
1915                    inputStream = resEntity.getContent();
1916                    if (inputStream != null) {
1917                        res = IOUtils.toString(inputStream, "utf-8");
1918                        inputStream.close();
1919                    }
1920                    List<AttachmentDTO> attachment = GsonUtil.CUSTOM_GSON.fromJson(res, listType);
1921
1922                    Attachment attach = new Attachment();
1923                    Path path = new File(attachmentFile.getName()).toPath();
1924                    String mimeType = Files.probeContentType(path);
1925
1926                    attach.setContentType(mimeType);
1927                    attach.setCreatedBy(testerId);// tester id
1928                    attach.setFileSize(String.valueOf(attachmentFile.length()));
1929                    attach.setItemId(iterator.getKey());// get release schedule id
1930                    attach.setItemType("releaseTestSchedule");
1931                    attach.setName(attachment.get(0).getFileName());
1932                    attach.setTempPath(attachment.get(0).getTempFilePath());
1933                    attach.setTimeStamp(new Date());
1934                    attachmentList.add(attach);
1935                    StringRequestEntity requestEntity;
1936                    requestEntity = new StringRequestEntity(CustomDateUtil.gson.toJson(attachmentList),
1937                            "application/json", "UTF-8");
1938                    PostMethod post = new PostMethod(
1939                            props.getString("zephyrServerURL") + "/flex/services/rest/v3/attachment/list");
1940                    post.setRequestHeader("Authorization",createRequestHeader());
1941                    post.setRequestEntity(requestEntity);
1942                    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1943                    try {
1944                        int statusCode = -1;
1945                        try {
1946                            statusCode = client.executeMethod(post);
1947                        } catch (Exception e) {
1948                            logger.log(Level.WARNING, e.getMessage());
1949                        }
1950
1951                        if (statusCode != HttpStatus.SC_OK) {
1952                            handleHttpError(statusCode,"addTestCaseAttachment",post);
1953                        } else {
1954                            logger.log(Level.WARNING, "checkPayload(): " + response);
1955                        }
1956                    } finally {
1957                        post.releaseConnection();
1958                    }
1959                    attachmentList.clear();
1960                } catch (IOException e) {
1961                    logger.log(Level.WARNING, "ERROR: failure in Testcase attachments: " + e);
1962                }
1963            }
1964        }
1965    }
1966
1967
1968    public static String updateRequirement(List<MapTestcaseToRequirement> mapTestcaseToRequirements) throws HttpException, IOException {
1969                for(int i=0;i<mapTestcaseToRequirements.size();i+=ZeeConstants.BATCH_SIZE){
1970                        final String s = i + ZeeConstants.BATCH_SIZE > mapTestcaseToRequirements.size() ? updateRequirement(mapTestcaseToRequirements.subList(i, mapTestcaseToRequirements.size()), ZeeConstants.BATCH_SIZE) :
1971                                        updateRequirement(mapTestcaseToRequirements.subList(i, i + ZeeConstants.BATCH_SIZE), ZeeConstants.BATCH_SIZE);
1972                }
1973       return "";
1974    }
1975
1976        public static String updateRequirement(List<MapTestcaseToRequirement> mapTestcaseToRequirements,int batchSize) throws HttpException, IOException {
1977                HttpClient client = getConnectionFromPool();
1978                InputStream inputStream = null;
1979                logger.info("saveBulkTestCases Request ::::" + GsonUtil.CUSTOM_GSON.toJson(mapTestcaseToRequirements));
1980
1981                StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(mapTestcaseToRequirements), "application/json", "UTF-8");
1982
1983                PostMethod method = new PostMethod(props.getString("zephyrServerURL") + URL_BULK_REQUIREMENTS_RELEASE );
1984
1985
1986                logger.info("bulk URL:" + props.getString("zephyrServerURL") + URL_BULK_REQUIREMENTS_RELEASE );
1987
1988                method.setRequestHeader("Authorization", createRequestHeader());
1989                method.setRequestEntity(requestEntity);
1990                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
1991                try {
1992                        int statusCode = -1;
1993                        try {
1994                                statusCode = client.executeMethod(method);
1995                                logger.info("statusCode :::" + statusCode);
1996                        } catch (Exception e) {
1997                                logger.log(Level.WARNING, e.getMessage());
1998                        }
1999                        if (statusCode != HttpStatus.SC_OK) {
2000                handleHttpError(statusCode,"updateRequirement",method);
2001                        } else {
2002                                inputStream = method.getResponseBodyAsStream();
2003                                if (inputStream != null) {
2004                                        String response = IOUtils.toString(inputStream, "utf-8");
2005                                        logger.info("MapBulkTestCases to requiremnt ... checkPayLoad || Response " + response);
2006                                        Type listType = new TypeToken<ArrayList<String>>() {
2007                                        }.getType();
2008                                        List<String> responseString = CustomDateUtil.gson.fromJson(response, listType);
2009                                        if(responseString!=null && responseString.size()>0){
2010                                                logger.info("Requirement list doesn't exist " + responseString);
2011                                        }
2012                                }
2013                        }
2014                } finally {
2015                        if (inputStream != null) {
2016                                inputStream.close();
2017                        }
2018                        method.releaseConnection();
2019                }
2020                return "";
2021        }
2022
2023    public static void updateTestResult(List<RemoteTestResult> testResults) throws HttpException, IOException {
2024        HttpClient client = getConnectionFromPool();
2025        InputStream inputStream = null;
2026        logger.info("saveBulkTestCases Request ::::" + GsonUtil.CUSTOM_GSON.toJson(testResults));
2027
2028        StringRequestEntity requestEntity = new StringRequestEntity(GsonUtil.CUSTOM_GSON.toJson(testResults), "application/json", "UTF-8");
2029
2030        PostMethod method = new PostMethod(props.getString("zephyrServerURL") + URL_UPDATE_TEST_RESULT );
2031
2032
2033        logger.info("Update test result:" + props.getString("zephyrServerURL") + URL_UPDATE_TEST_RESULT );
2034
2035        method.setRequestHeader("Authorization", createRequestHeader());
2036        method.setRequestEntity(requestEntity);
2037        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
2038        try {
2039            int statusCode = -1;
2040            try {
2041                statusCode = client.executeMethod(method);
2042                logger.info("statusCode :::" + statusCode);
2043            } catch (Exception e) {
2044                logger.log(Level.WARNING, e.getMessage());
2045            }
2046            if (statusCode != HttpStatus.SC_OK) {
2047                handleHttpError(statusCode,"updateTestResult",method);
2048            } else {
2049                inputStream = method.getResponseBodyAsStream();
2050                if (inputStream != null) {
2051                    String response = IOUtils.toString(inputStream, "utf-8");
2052                    logger.info("Update test result ... checkPayLoad || Response " + response);
2053                    Type listType = new TypeToken<ArrayList<RemoteFieldValue>>() {
2054                    }.getType();
2055                    List<String> responseString = CustomDateUtil.gson.fromJson(response, listType);
2056                    if(responseString!=null && responseString.size()>0){
2057                        logger.info("Update test result " + responseString);
2058                    }
2059                }
2060            }
2061        } finally {
2062            if (inputStream != null) {
2063                inputStream.close();
2064            }
2065            method.releaseConnection();
2066        }
2067    }
2068
2069        public static PreferenceDTO getTestExecutionStatuses() throws IOException {
2070                PreferenceDTO preferenceDTO = null;
2071                HttpClient client = getConnectionFromPool();
2072                InputStream inputStream = null;
2073
2074                logger.info("getTestExecutionStatuses Request");
2075
2076                String urlZblast = props.getString("zephyrServerURL") + URL_GET_TEST_EXECUTION_STATUSES;
2077                GetMethod method = new GetMethod(urlZblast);
2078                method.setRequestHeader("Authorization", createRequestHeader());
2079                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
2080                try {
2081                        int statusCode = -1;
2082                        try {
2083                                statusCode = client.executeMethod(method);
2084                        } catch (Exception e) {
2085                                logger.log(Level.WARNING, e.getMessage());
2086                        }
2087                        if (statusCode != HttpStatus.SC_OK) {
2088                handleHttpError(statusCode,"getTestExecutionStatuses",method);
2089                        } else {
2090                                inputStream = method.getResponseBodyAsStream();
2091                                if (inputStream != null) {
2092                                        String response = IOUtils.toString(inputStream, "utf-8");
2093                                        preferenceDTO = GsonUtil.CUSTOM_GSON.fromJson(response, PreferenceDTO.class);
2094                                }
2095                        }
2096                } finally {
2097                        if (inputStream != null) {
2098                                inputStream.close();
2099                        }
2100                        method.releaseConnection();
2101                }
2102                return preferenceDTO;
2103        }
2104
2105    public static List<ReleaseTestSchedule> getReleaseTestSchedulesById(List<Long> rtsIds) throws IOException {
2106        InputStream inputStream = null;
2107        List<ReleaseTestSchedule> releaseTestSchedules = null;
2108        String urlZblast = props.getString("zephyrServerURL") + URL_GET_RELEASETEST_SCHEDULE_BYIDS;
2109        HttpClient httpClient = new HttpClient();
2110        GetMethod method = new GetMethod(urlZblast);
2111        List<NameValuePair> nameValuePairList = new ArrayList<>();
2112        for (Long rtsId : rtsIds) {
2113                nameValuePairList.add(new NameValuePair("ids", rtsId.toString()));
2114                }
2115        method.setQueryString(nameValuePairList.toArray(new NameValuePair[0]));
2116        method.setRequestHeader("Authorization", createRequestHeader());
2117        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
2118
2119        try {
2120            int statusCode = -1;
2121            try {
2122                statusCode = httpClient.executeMethod(method);
2123            } catch (Exception e) {
2124                logger.log(Level.WARNING, e.getMessage());
2125            }
2126
2127            if (statusCode != HttpStatus.SC_OK) {
2128                handleHttpError(statusCode,"getReleaseTestSchedulesById",method);
2129            } else {
2130                inputStream = method.getResponseBodyAsStream();
2131                String response = IOUtils.toString(inputStream, "utf-8");
2132                Type listType = new TypeToken<ArrayList<ReleaseTestSchedule>>() { }.getType();
2133                releaseTestSchedules = CustomDateUtil.gson.fromJson(response, listType);
2134                if (response != null) {
2135                }
2136            }
2137        } finally {
2138            method.releaseConnection();
2139        }
2140        return releaseTestSchedules;
2141    }
2142
2143    public static AutomationScriptJobDTO getScriptJobDetail(Long JobId) throws IOException {
2144        InputStream inputStream = null;
2145        AutomationScriptJobDTO automationScriptJobDTO = null;
2146        String urlZblast = props.getString("zephyrServerURL") + URL_GET_SCRIPT_JOB_DETAIL + JobId;
2147        HttpClient httpClient = new HttpClient();
2148        GetMethod method = new GetMethod(urlZblast);
2149        method.setRequestHeader("Authorization", createRequestHeader());
2150        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
2151
2152        try {
2153            int statusCode = -1;
2154            try {
2155                statusCode = httpClient.executeMethod(method);
2156            } catch (Exception e) {
2157                logger.log(Level.WARNING, e.getMessage());
2158            }
2159
2160            if (statusCode != HttpStatus.SC_OK) {
2161                handleHttpError(statusCode,"getScriptJobDetail",method);
2162            } else {
2163                inputStream = method.getResponseBodyAsStream();
2164                String response = IOUtils.toString(inputStream, "utf-8");
2165                automationScriptJobDTO = CustomDateUtil.gson.fromJson(response, AutomationScriptJobDTO.class);
2166                if (response != null) {
2167                }
2168            }
2169        } finally {
2170            method.releaseConnection();
2171        }
2172        return automationScriptJobDTO;
2173    }
2174
2175    public static void handleHttpError(int statusCode,String calledMethodName,HttpMethod method)throws IOException
2176    {
2177        String response =null;
2178        ErrorResource errorResource =null;
2179        InputStream inputStream=method.getResponseBodyAsStream();
2180
2181        if(inputStream!= null) {
2182             response = IOUtils.toString(inputStream, "utf-8");
2183             errorResource = CustomDateUtil.gson.fromJson(response, ErrorResource.class);
2184        }
2185
2186        if (errorResource != null &&  !StringUtils.isEmpty(errorResource.getErrorMsg())) {
2187            logger.log(Level.SEVERE,calledMethodName+"... Method failed: "+ errorResource.getErrorMsg());
2188        }
2189        else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
2190                        logger.log(Level.SEVERE, """
2191                                        %s... Method failed: User do not have access to project(s) or permission denied""".formatted(calledMethodName));
2192        }
2193        else if (statusCode == HttpStatus.SC_FORBIDDEN) {
2194                        logger.log(Level.SEVERE, """
2195                                        %s... Method failed: User does not have associated to any Zephyr projects""".formatted(calledMethodName));
2196        } else {
2197            logger.log(Level.SEVERE, calledMethodName+"... Method failed: " + method.getStatusLine());
2198        }
2199    }
2200}