Best Carina code snippet using com.qaprosoft.appcenter.http.resttemplate.RestTemplateBuilder.build
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) {290 String fileName = String.format("%s.%s.%s.%s", appName, buildType, versionShort, versionLong)291 .replace(" ", "");292 if (platformName.toLowerCase().contains("ios")) {293 return fileName + ".ipa";294 }295 return fileName + ".apk";296 }297 private boolean checkNotesForCorrectBuild(String pattern, JsonNode node) {298 return checkForPattern("release_notes", pattern, node);299 }300 private boolean checkTitleForCorrectPattern(String pattern, JsonNode node) {301 return checkForPattern("app_name", pattern, node);302 }303 private boolean checkForPattern(String nodeName, String pattern, JsonNode node) {304 LOGGER.debug("\nPattern to be checked: " + pattern);305 if (node.findPath("release_notes").isMissingNode()) {306 return false;307 }308 String nodeField = node.get(nodeName).asText().toLowerCase();309 String[] splitPattern = pattern.split("\\.");310 LinkedList<Boolean> segmentsFound = new LinkedList<>();311 for(String segment : splitPattern){312 segmentsFound.add(nodeField.contains(segment));313 }314 if (!segmentsFound.isEmpty() && !segmentsFound.contains(false)) {315 LOGGER.debug("\nPattern match found!! This is the buildType to be used: " + nodeField);316 return true;317 }318 String patternToReplace = ".*[ ->\\S]%s[ -<\\S].*";319 return !pattern.isEmpty() && scanningAllNotes(String.format(patternToReplace, pattern), nodeField);320 }321 private boolean searchFieldsForString(String pattern, String stringToSearch) {322 Pattern p = Pattern.compile(pattern);323 Matcher m = p.matcher(stringToSearch);324 return m.find();325 }326 private boolean scanningAllNotes(String pattern, String noteField) {327 boolean foundMessages = false;328 foundMessages = searchFieldsForString(pattern, noteField);329 return foundMessages;...
Source:RestTemplateBuilder.java
...68 .json()69 .featuresToEnable(70 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,71 DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)72 .build());73 jsonMessageConverter.setSupportedMediaTypes(Lists.newArrayList(74 MediaType.TEXT_HTML, MediaType.TEXT_PLAIN,75 MediaType.APPLICATION_JSON));76 withMessageConverter(jsonMessageConverter);77 return this;78 }79 /**80 * http://stackoverflow.com/questions/27603782/java-spring-resttemplate-character-encoding81 * 82 * @return RestTemplateBuilder83 */84 public RestTemplateBuilder withUtf8EncodingMessageConverter() {85 withMessageConverter(new StringHttpMessageConverter(Charset.forName("UTF-8")));86 return this;87 }88 public RestTemplateBuilder withBasicAuthentication(String username, String password) {89 isUseBasicAuth = true;90 basicAuthUsername = username;91 basicAuthPassword = password;92 return this;93 }94 public RestTemplate build() {95 if (!isUseDefaultJsonMessageConverter) {96 HttpMessageConverter<?> httpMessageConverter = Iterables.tryFind(97 restTemplate.getMessageConverters(),98 new Predicate<HttpMessageConverter<?>>() {99 @Override100 public boolean apply(HttpMessageConverter<?> input) {101 return input instanceof MappingJackson2HttpMessageConverter;102 }103 }).orNull();104 restTemplate.getMessageConverters().remove(httpMessageConverter);105 }106 restTemplate.getMessageConverters().addAll(httpMessageConverters);107 if (isDisableSslChecking) {108 restTemplate109 .setRequestFactory(new DisabledSslClientHttpRequestFactory());110 }111 if (isUseBasicAuth) {112 CredentialsProvider credentialsProvider = new BasicCredentialsProvider();113 credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(basicAuthUsername, basicAuthPassword));114 HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();115 restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));116 }117 return restTemplate;118 }119}...
build
Using AI Code Generation
1package com.qaprosoft.appcenter;2import org.springframework.boot.SpringApplication;3import org.springframework.boot.autoconfigure.SpringBootApplication;4import org.springframework.context.ConfigurableApplicationContext;5import org.springframework.http.HttpEntity;6import org.springframework.http.HttpHeaders;7import org.springframework.http.HttpMethod;8import org.springframework.http.MediaType;9import org.springframework.web.client.RestTemplate;10import com.qaprosoft.appcenter.http.resttemplate.RestTemplateBuilder;11public class App {12 public static void main(String[] args) {13 ConfigurableApplicationContext context = SpringApplication.run(App.class, args);14 RestTemplateBuilder builder = context.getBean(RestTemplateBuilder.class);15 RestTemplate restTemplate = builder.build();16 HttpHeaders headers = new HttpHeaders();17 headers.setContentType(MediaType.APPLICATION_JSON);18 HttpEntity<String> entity = new HttpEntity<String>("{\"key\":\"value\"}", headers);19 System.out.println(response);20 }21}22{23 "args": {}, 24 "data": "{\"key\":\"value\"}", 25 "files": {}, 26 "form": {}, 27 "headers": {28 "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_101)"29 }, 30 "json": {31 },
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!!