Best Carina code snippet using com.qaprosoft.appcenter.http.resttemplate.RestTemplateBuilder.newInstance
Source:AppCenterManager.java
...49 */50public class AppCenterManager {51 private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());52 53 protected RestTemplate restTemplate = RestTemplateBuilder.newInstance().withDisabledSslChecking().withSpecificJsonMessageConverter().build();54 private String ownerName;55 private String versionLong;56 private String versionShort;57 private static final String HOST_URL = "api.appcenter.ms";58 private static final String API_APPS = "/v0.1/apps";59 private static AppCenterManager instance = null;60 private AppCenterManager() {61 }62 public synchronized static AppCenterManager getInstance() {63 if (instance == null) {64 instance = new AppCenterManager();65 }66 return instance;67 }68 /**69 *70 * @param appName takes in the AppCenter Name to look for.71 * @param platformName takes in the platform we wish to download for.72 * @param buildType takes in the particular build to download (i.e. Prod.AdHoc, QA.Debug, Prod-Release, QA-Internal etc...)73 * @param version takes in either "latest" to take the first build that matches the criteria or allows to consume a version to download that74 * build.75 * @return download url for build artifact.76 */77 public String getDownloadUrl(String appName, String platformName, String buildType, String version) {78 return scanAppForBuild(getAppId(appName, platformName), buildType, version);79 } 80 /**81 *82 * @param folder to which upload build artifact.83 * @param appName takes in the AppCenter Name to look for.84 * @param platformName takes in the platform we wish to download for.85 * @param buildType takes in the particular build to download (i.e. Prod.AdHoc, QA.Debug, Prod-Release, QA-Internal etc...)86 * @param version takes in either "latest" to take the first build that matches the criteria or allows to consume a version to download that87 * build.88 * @return file to the downloaded build artifact89 */90 public File getBuild(String folder, String appName, String platformName, String buildType, String version) {91 String buildToDownload = getDownloadUrl(appName, platformName, buildType, version);92 //TODO: wrap below code into the public download method93 String fileName = folder + "/" + createFileName(appName, buildType, platformName);94 File fileToLocate = null;95 try {96 File file = new File(folder);97 File[] listOfFiles = file.listFiles();98 if (file.list() != null) {99 for (int i = 0; i < listOfFiles.length; ++i) {100 if (listOfFiles[i].isFile() && fileName.contains(listOfFiles[i].getName())) {101 LOGGER.info("File has been Located Locally. File path is: " + listOfFiles[i].getAbsolutePath());102 fileToLocate = listOfFiles[i];103 }104 }105 }106 } catch (Exception ex) {107 LOGGER.error("Error Attempting to Look for Existing File!", ex);108 }109 if (fileToLocate == null) {110 try {111 LOGGER.debug("Beginning Transfer of AppCenter Build");112 URL downloadLink = new URL(buildToDownload);113 int retryCount = 0;114 boolean retry = true;115 while (retry && retryCount <= 5) {116 retry = downloadBuild(fileName, downloadLink);117 retryCount = retryCount + 1;118 }119 LOGGER.debug(String.format("AppCenter Build (%s) was retrieved", fileName));120 } catch (Exception ex) {121 LOGGER.error("Error Thrown When Attempting to Transfer AppCenter Build!", ex);122 }123 } else {124 LOGGER.info("Preparing to use local version of AppCenter Build...");125 }126 return new File(fileName);127 }128 /**129 *130 * @param fileName will be the name of the downloaded file.131 * @param downloadLink will be the URL to retrieve the build from.132 * @return brings back a true/false on whether or not the build was successfully downloaded.133 * @throws IOException throws a non Interruption Exception up.134 */135 private boolean downloadBuild(String fileName, URL downloadLink) throws IOException {136 try (ReadableByteChannel readableByteChannel = Channels.newChannel(downloadLink.openStream());137 FileOutputStream fos = new FileOutputStream(fileName)) {138 if (Thread.currentThread().isInterrupted()) {139 LOGGER.debug(String.format("Current Thread (%s) is interrupted, clearing interruption.", Thread.currentThread().getId()));140 Thread.interrupted();141 }142 fos.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);143 LOGGER.info("Successfully Transferred...");144 return false;145 } catch (ClosedByInterruptException ie1) {146 LOGGER.info("Retrying....");147 LOGGER.error("Getting Error!", ie1);148 return true;149 }150 }151 /**152 *153 * @param appName takes in the AppCenter Name to look for.154 * @param platformName takes in the platform we wish to download for.155 * @return Map<String, String>156 */157 private Map<String, String> getAppId(String appName, String platformName) {158 Map<String, String> appMap = new HashMap<>();159 RequestEntity<String> retrieveApps = buildRequestEntity(160 HOST_URL,161 API_APPS,162 HttpMethod.GET);163 JsonNode appResults = restTemplate.exchange(retrieveApps, JsonNode.class).getBody();164 LOGGER.info("AppCenter Searching For App: " + appName);165 LOGGER.debug("AppCenter JSON Response: " + appResults);166 for (JsonNode node : appResults) {167 if (platformName.equalsIgnoreCase(node.get("os").asText()) && node.get("name").asText().toLowerCase().contains(appName.toLowerCase())) {168 ownerName = node.get("owner").get("name").asText();169 String app = node.get("name").asText();170 LOGGER.info(String.format("Found Owner: %s App: %s", ownerName, app));171 appMap.put(app, getLatestBuildDate(app, node.get("updated_at").asText()));172 }173 }174 if (!appMap.isEmpty()) {175 return appMap.entrySet()176 .stream()177 .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))178 .collect(Collectors.toMap(179 Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));180 }181 throw new RuntimeException(String.format("Application Not Found in AppCenter for Organization (%s) Name (%s), Platform (%s)", ownerName, appName, platformName));182 }183 /**184 *185 * @param apps takes in the application Ids186 * @param buildType takes in the particular build to download (i.e. Prod.AdHoc, QA.Debug, Prod-Release, QA-Internal etc...)187 * @param version takes in either "latest" to take the first build that matches the criteria or allows to consume a version to download that188 * build.189 * @return String190 */191 private String scanAppForBuild(Map<String, String> apps, String buildType, String version) {192 for (String currentApp : apps.keySet()) {193 LOGGER.info("Scanning App " + currentApp);194 MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();195 queryParams.add("published_only", "true");196 queryParams.add("scope", "tester");197 RequestEntity<String> retrieveList = buildRequestEntity(198 HOST_URL,199 String.format("%s/%s/%s/releases", API_APPS, ownerName, currentApp),200 queryParams,201 HttpMethod.GET);202 JsonNode buildList = restTemplate.exchange(retrieveList, JsonNode.class).getBody();203 LOGGER.debug("Available Builds JSON: " + buildList);204 if (buildList.size() > 0) {205 int buildLimiter = 0;206 for (JsonNode build : buildList) {207 buildLimiter += 1;208 if (buildLimiter >=50) {209 break;210 }211 String latestBuildNumber = build.get("id").asText();212 versionShort = build.get("short_version").asText();213 versionLong = build.get("version").asText();214 RequestEntity<String> retrieveBuildUrl = buildRequestEntity(215 HOST_URL,216 String.format("%s/%s/%s/releases/%s", API_APPS, ownerName, currentApp, latestBuildNumber),217 HttpMethod.GET);218 JsonNode appBuild = restTemplate.exchange(retrieveBuildUrl, JsonNode.class).getBody();219 if (checkBuild(version, appBuild) && (checkTitleForCorrectPattern(buildType.toLowerCase(), appBuild) || checkNotesForCorrectBuild(buildType.toLowerCase(), appBuild))) {220 LOGGER.debug("Print Build Info: " + appBuild);221 LOGGER.info(222 String.format(223 "Fetching Build ID (%s) Version: %s (%s)", latestBuildNumber, versionShort, versionLong));224 String buildUrl = appBuild.get("download_url").asText();225 LOGGER.info("Download URL For Build: " + buildUrl);226 return buildUrl;227 }228 }229 }230 }231 throw new RuntimeException(String.format("Unable to find build to download, version provided (%s)", version));232 }233 /**234 * The updated_at field returned by AppCenter doesn't contain the "latest time" a build was updated, so we grab the first build to do our sort.235 * @param app name of the app to check.236 * @param appUpdatedAt passing in of a backup date value if the app we look at doesn't have a build associated to it.237 * @return the date value to be used in sorting.238 */239 private String getLatestBuildDate(String app, String appUpdatedAt) {240 MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();241 queryParams.add("published_only", "true");242 queryParams.add("scope", "tester");243 RequestEntity<String> retrieveList = buildRequestEntity(244 HOST_URL,245 String.format("%s/%s/%s/releases", API_APPS, ownerName, app),246 queryParams,247 HttpMethod.GET);248 JsonNode buildList = restTemplate.exchange(retrieveList, JsonNode.class).getBody();249 if (buildList.size() > 0) {250 return buildList.get(0).get("uploaded_at").asText();251 }252 return appUpdatedAt;253 }254 private boolean checkBuild(String version, JsonNode node) {255 if ("latest".equalsIgnoreCase(version)) {256 return true;257 }258 return version.equalsIgnoreCase(259 node.get("short_version").asText() + "." + node.get("version").asText())260 || version.equalsIgnoreCase(node.get("short_version").asText());261 }262 @SuppressWarnings({ "rawtypes", "unchecked" })263 private RequestEntity<String> buildRequestEntity(String hostUrl, String path,264 HttpMethod httpMethod) {265 UriComponents uriComponents = UriComponentsBuilder.newInstance()266 .scheme("https")267 .host(hostUrl)268 .path(path)269 .build();270 return new RequestEntity(setHeaders(), httpMethod, uriComponents.toUri());271 }272 @SuppressWarnings({ "rawtypes", "unchecked" })273 private RequestEntity<String> buildRequestEntity(String hostUrl, String path,274 MultiValueMap<String, String> listQueryParams, HttpMethod httpMethod) {275 UriComponents uriComponents = UriComponentsBuilder.newInstance()276 .scheme("https")277 .host(hostUrl)278 .path(path)279 .queryParams(listQueryParams)280 .build();281 return new RequestEntity(setHeaders(), httpMethod, uriComponents.toUri());282 }283 private HttpHeaders setHeaders() {284 HttpHeaders httpHeader = new HttpHeaders();285 httpHeader.add("Content-Type", "application/json; charset=utf-8");286 httpHeader.add("x-api-token", Configuration.get(Parameter.APPCENTER_TOKEN));287 return httpHeader;288 }289 private String createFileName(String appName, String buildType, String platformName) {...
Source:RestTemplateBuilder.java
...48 protected String basicAuthUsername;49 protected String basicAuthPassword;50 protected RestTemplateBuilder() {51 }52 public static RestTemplateBuilder newInstance() {53 return new RestTemplateBuilder();54 }55 public RestTemplateBuilder withMessageConverter(56 HttpMessageConverter<?> messageConverter) {57 this.httpMessageConverters.add(messageConverter);58 return this;59 }60 public RestTemplateBuilder withDisabledSslChecking() {61 this.isDisableSslChecking = true;62 return this;63 }64 public RestTemplateBuilder withSpecificJsonMessageConverter() {65 isUseDefaultJsonMessageConverter = false;66 AbstractHttpMessageConverter<?> jsonMessageConverter = new MappingJackson2HttpMessageConverter(...
newInstance
Using AI Code Generation
1package com.qaprosoft.appcenter.http.resttemplate;2import java.io.File;3import java.io.IOException;4import java.util.HashMap;5import java.util.Map;6import org.apache.http.HttpEntity;7import org.apache.http.entity.ContentType;8import org.apache.http.entity.mime.MultipartEntityBuilder;9import org.apache.http.entity.mime.content.FileBody;10import org.apache.http.entity.mime.content.StringBody;11import org.apache.http.impl.client.HttpClientBuilder;12import org.apache.http.impl.client.HttpClients;13import org.apache.http.util.EntityUtils;14import org.springframework.http.HttpEntity;15import org.springframework.http.HttpHeaders;16import org.springframework.http.HttpMethod;17import org.springframework.http.MediaType;18import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;19import org.springframework.http.client.SimpleClientHttpRequestFactory;20import org.springframework.web.client.RestTemplate;21public class RestTemplateBuilder {22public static RestTemplate newInstance() {
newInstance
Using AI Code Generation
1package com.qaprosoft.appcenter.http.resttemplate;2import com.qaprosoft.appcenter.http.resttemplate.RestTemplateBuilder;3public class RestTemplateBuilderTest {4public static void main(String[] args) {5RestTemplateBuilder builder = new RestTemplateBuilder();6builder.newInstance();7}8}9package com.qaprosoft.appcenter.http.resttemplate;10import org.apache.http.client.HttpClient;11import org.apache.http.impl.client.HttpClientBuilder;12import org.apache.http.impl.client.HttpClients;13import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;14import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;15import org.springframework.web.client.RestTemplate;16public class RestTemplateBuilder {17public RestTemplateBuilder() {18}19public RestTemplate newInstance() {20PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();21connectionManager.setMaxTotal(100);22connectionManager.setDefaultMaxPerRoute(20);23HttpClientBuilder httpClientBuilder = HttpClients.custom();24httpClientBuilder.setConnectionManager(connectionManager);25HttpClient httpClient = httpClientBuilder.build();26HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();27requestFactory.setHttpClient(httpClient);28RestTemplate restTemplate = new RestTemplate(requestFactory);29return restTemplate;30}31}32package com.qaprosoft.appcenter.http.resttemplate;33import org.apache.http.client.HttpClient;34import org.apache.http.impl.client.HttpClientBuilder;35import org.apache.http.impl.client.HttpClients;36import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;37import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;38import org.springframework.web.client.RestTemplate;39public class RestTemplateBuilder {40public RestTemplateBuilder() {41}42public RestTemplate newInstance() {43PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();44connectionManager.setMaxTotal(100);45connectionManager.setDefaultMaxPerRoute(20);46HttpClientBuilder httpClientBuilder = HttpClients.custom();47httpClientBuilder.setConnectionManager(connectionManager);48HttpClient httpClient = httpClientBuilder.build();49HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();50requestFactory.setHttpClient(httpClient);51RestTemplate restTemplate = new RestTemplate(requestFactory);52return restTemplate;53}54}55package com.qaprosoft.appcenter.http.resttemplate;56import org.apache.http.client.HttpClient;57import org.apache.http.impl.client.HttpClientBuilder;58import org.apache.http.impl.client.HttpClients;59import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;60import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;61import org
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!