How to use AmazonS3Manager class of com.qaprosoft.amazon package

Best Carina code snippet using com.qaprosoft.amazon.AmazonS3Manager

Source:AbstractTest.java Github

copy

Full Screen

...49import org.testng.xml.XmlTest;50import com.amazonaws.services.s3.model.S3Object;51import com.amazonaws.services.s3.model.S3ObjectSummary;52import com.jayway.restassured.RestAssured;53import com.qaprosoft.amazon.AmazonS3Manager;54import com.qaprosoft.carina.core.foundation.api.APIMethodBuilder;55import com.qaprosoft.carina.core.foundation.dataprovider.core.DataProviderFactory;56import com.qaprosoft.carina.core.foundation.jira.Jira;57import com.qaprosoft.carina.core.foundation.listeners.AbstractTestListener;58import com.qaprosoft.carina.core.foundation.log.ThreadLogAppender;59import com.qaprosoft.carina.core.foundation.report.Artifacts;60import com.qaprosoft.carina.core.foundation.report.HtmlReportGenerator;61import com.qaprosoft.carina.core.foundation.report.ReportContext;62import com.qaprosoft.carina.core.foundation.report.TestResultItem;63import com.qaprosoft.carina.core.foundation.report.TestResultType;64import com.qaprosoft.carina.core.foundation.report.email.EmailManager;65import com.qaprosoft.carina.core.foundation.report.email.EmailReportGenerator;66import com.qaprosoft.carina.core.foundation.report.email.EmailReportItemCollector;67import com.qaprosoft.carina.core.foundation.report.spira.Spira;68import com.qaprosoft.carina.core.foundation.report.testrail.TestRail;69import com.qaprosoft.carina.core.foundation.utils.Configuration;70import com.qaprosoft.carina.core.foundation.utils.Configuration.DriverMode;71import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter;72import com.qaprosoft.carina.core.foundation.utils.DateUtils;73import com.qaprosoft.carina.core.foundation.utils.JsonUtils;74import com.qaprosoft.carina.core.foundation.utils.Messager;75import com.qaprosoft.carina.core.foundation.utils.R;76import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords;77import com.qaprosoft.carina.core.foundation.utils.metadata.MetadataCollector;78import com.qaprosoft.carina.core.foundation.utils.metadata.model.ElementsInfo;79import com.qaprosoft.carina.core.foundation.utils.naming.TestNamingUtil;80import com.qaprosoft.carina.core.foundation.utils.resources.I18N;81import com.qaprosoft.carina.core.foundation.utils.resources.L10N;82import com.qaprosoft.carina.core.foundation.utils.resources.L10Nparser;83import com.qaprosoft.carina.core.foundation.webdriver.DriverPool;84import com.qaprosoft.carina.core.foundation.webdriver.device.DevicePool;85/*86 * AbstractTest - base test for UI and API tests.87 * 88 * @author Alex Khursevich89 */90@Listeners({AbstractTestListener.class})91public abstract class AbstractTest // extends DriverHelper92{93 protected static final Logger LOGGER = Logger.getLogger(AbstractTest.class);94 protected APIMethodBuilder apiMethodBuilder;95 protected static final long IMPLICIT_TIMEOUT = Configuration.getLong(Parameter.IMPLICIT_TIMEOUT);96 protected static final long EXPLICIT_TIMEOUT = Configuration.getLong(Parameter.EXPLICIT_TIMEOUT);97 protected static final String SUITE_TITLE = "%s%s%s - %s (%s%s)";98 protected static final String XML_SUITE_NAME = " (%s)";99 protected static ThreadLocal<String> suiteNameAppender = new ThreadLocal<String>();100 101 // 3rd party integrations102 protected String browserVersion = "";103 protected long startDate;104 @BeforeSuite(alwaysRun = true)105 public void executeBeforeTestSuite(ITestContext context) throws Throwable {106 107 DevicePool.addDevices();108 // Add shutdown hook109 Runtime.getRuntime().addShutdownHook(new ShutdownHook());110 // Set log4j properties111 PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));112 // Set SoapUI log4j properties113 System.setProperty("soapui.log4j.config", "./src/main/resources/soapui-log4j.xml");114 try {115 Logger root = Logger.getRootLogger();116 Enumeration<?> allLoggers = root.getLoggerRepository().getCurrentCategories();117 while (allLoggers.hasMoreElements()) {118 Category tmpLogger = (Category) allLoggers.nextElement();119 if (tmpLogger.getName().equals("com.qaprosoft.carina.core")) {120 tmpLogger.setLevel(Level.toLevel(Configuration.get(Parameter.CORE_LOG_LEVEL)));121 }122 }123 } catch (NoSuchMethodError e) {124 LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!");125 }126 startDate = new Date().getTime();127 LOGGER.info(Configuration.asString());128 // Configuration.validateConfiguration();129 LOGGER.debug("Default thread_count=" + context.getCurrentXmlTest().getSuite().getThreadCount());130 context.getCurrentXmlTest().getSuite().setThreadCount(Configuration.getInt(Parameter.THREAD_COUNT));131 LOGGER.debug("Updated thread_count=" + context.getCurrentXmlTest().getSuite().getThreadCount());132 // update DataProviderThreadCount if any property is provided otherwise sync with value from suite xml file133 int count = Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT);134 if (count > 0) {135 LOGGER.debug("Updated 'data_provider_thread_count' from "136 + context.getCurrentXmlTest().getSuite().getDataProviderThreadCount() + " to " + count);137 context.getCurrentXmlTest().getSuite().setDataProviderThreadCount(count);138 } else {139 LOGGER.debug("Synching data_provider_thread_count with values from suite xml file...");140 R.CONFIG.put(Parameter.DATA_PROVIDER_THREAD_COUNT.getKey(), String.valueOf(context.getCurrentXmlTest().getSuite().getDataProviderThreadCount()));141 LOGGER.debug("Updated 'data_provider_thread_count': " + Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT));142 }143 LOGGER.debug("Default data_provider_thread_count="144 + context.getCurrentXmlTest().getSuite().getDataProviderThreadCount());145 LOGGER.debug("Updated data_provider_thread_count="146 + context.getCurrentXmlTest().getSuite().getDataProviderThreadCount());147 if (!Configuration.isNull(Parameter.URL)) {148 if (!Configuration.get(Parameter.URL).isEmpty()) {149 RestAssured.baseURI = Configuration.get(Parameter.URL);150 }151 }152 try {153 L10N.init();154 } catch (Exception e) {155 LOGGER.error("L10N bundle is not initialized successfully!", e);156 }157 try {158 I18N.init();159 } catch (Exception e) {160 LOGGER.error("I18N bundle is not initialized successfully!", e);161 }162 try {163 L10Nparser.init();164 } catch (Exception e) {165 LOGGER.error("L10Nparser bundle is not initialized successfully!", e);166 }167 try {168 TestRail.updateBeforeSuite(context, this.getClass().getName(), getTitle(context));169 } catch (Exception e) {170 LOGGER.error("TestRail is not initialized successfully!", e);171 }172 try {173 if (!Configuration.get(Parameter.ACCESS_KEY_ID).isEmpty()) {174 LOGGER.info("Initializing AWS S3 client...");175 AmazonS3Manager.getInstance().initS3client(Configuration.get(Parameter.ACCESS_KEY_ID),176 Configuration.get(Parameter.SECRET_KEY));177 updateS3AppPath();178 }179 } catch (Exception e) {180 LOGGER.error("AWS S3 client is not initialized successfully!", e);181 }182 183 // moved from UITest->executeBeforeTestSuite184 String customCapabilities = Configuration.get(Parameter.CUSTOM_CAPABILITIES);185 if (!customCapabilities.isEmpty()) {186 //redefine core properties using custom capabilities file187 Map<String, String> properties = Configuration.loadCoreProperties(customCapabilities);188 //reregister device if mobile core properties are redefined 189 DevicePool.addDevice(properties);190 }191 }192 193 @BeforeClass(alwaysRun = true)194 public void executeBeforeTestClass(ITestContext context) throws Throwable {195 // do nothing for now196 }197 @AfterClass(alwaysRun = true)198 public void executeAfterTestClass(ITestContext context) throws Throwable {199 if (Configuration.getDriverMode() == DriverMode.CLASS_MODE) {200 LOGGER.debug("Deinitialize driver(s) in UITest->AfterClass.");201 quitDrivers();202 }203 }204 @BeforeMethod(alwaysRun = true)205 public void executeBeforeTestMethod(XmlTest xmlTest, Method testMethod,206 ITestContext context) throws Throwable {207 // do nothing for now208 Spira.registerStepsFromAnnotation(testMethod);209 210 apiMethodBuilder = new APIMethodBuilder();211 }212 213 214 @AfterMethod(alwaysRun = true)215 public void executeAfterTestMethod(ITestResult result) {216 try {217 DriverMode driverMode = Configuration.getDriverMode();218 if (driverMode == DriverMode.METHOD_MODE) {219 LOGGER.debug("Deinitialize driver(s) in @AfterMethod.");220 quitDrivers();221 }222 // TODO: improve later removing duplicates with AbstractTestListener223 //handle Zafira already passed exception for re-run and do nothing. maybe return should be enough224 if (result.getThrowable() != null && result.getThrowable().getMessage() != null225 && result.getThrowable().getMessage().startsWith(SpecialKeywords.ALREADY_PASSED)) {226 // [VD] it is prohibited to release TestInfoByThread in this place.!227 return;228 }229 //handle AbstractTest->SkipExecution230 if (result.getThrowable() != null && result.getThrowable().getMessage() != null231 && result.getThrowable().getMessage().startsWith(SpecialKeywords.SKIP_EXECUTION)) {232 // [VD] it is prohibited to release TestInfoByThread in this place.!233 return;234 }235 String test = TestNamingUtil.getCanonicalTestName(result);236 List<String> tickets = Jira.getTickets(result);237 result.setAttribute(SpecialKeywords.JIRA_TICKET, tickets);238 Jira.updateAfterTest(result);239 // Populate Spira Steps240 Spira.updateAfterTest(result, (String) result.getTestContext().getAttribute(SpecialKeywords.TEST_FAILURE_MESSAGE), tickets);241 Spira.clear();242 // Populate TestRail Cases243 if (!R.ZAFIRA.getBoolean("zafira_enabled")){244 result.setAttribute(SpecialKeywords.TESTRAIL_CASES_ID, TestRail.getCases(result));245 TestRail.updateAfterTest(result, (String) result.getTestContext().getAttribute(SpecialKeywords.TEST_FAILURE_MESSAGE));246 TestRail.clearCases();247 }248 //we shouldn't deregister info here as all retries will not work249 //TestNamingUtil.releaseZafiraTest();250 // clear jira tickets to be sure that next test is not affected.251 Jira.clearTickets();252 Artifacts.clearArtifacts();253 try {254 ThreadLogAppender tla = (ThreadLogAppender) Logger.getRootLogger().getAppender("ThreadLogAppender");255 if (tla != null) {256 tla.closeResource(test);257 }258 } catch (NoSuchMethodError e) {259 LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!");260 }261 } catch (Exception e) {262 LOGGER.error("Exception in AbstractTest->executeAfterTestMethod: " + e.getMessage());263 e.printStackTrace();264 }265 }266 @AfterSuite(alwaysRun = true)267 public void executeAfterTestSuite(ITestContext context) {268 try {269 if (Configuration.getDriverMode() == DriverMode.SUITE_MODE) {270 LOGGER.debug("Deinitialize driver(s) in UITest->AfterSuite.");271 quitDrivers(); 272 }273 ReportContext.removeTempDir(); //clean temp artifacts directory274 HtmlReportGenerator.generate(ReportContext.getBaseDir().getAbsolutePath());275 String browser = getBrowser();276 String deviceName = getDeviceName();277 String suiteName = getSuiteName(context);278 String title = getTitle(context);279 TestResultType testResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults());280 String status = testResult.getName();281 title = status + ": " + title;282 String env = "";283 if (!Configuration.isNull(Parameter.ENV)) {284 env = Configuration.get(Parameter.ENV);285 }286 if (!Configuration.get(Parameter.URL).isEmpty()) {287 env += " - <a href='" + Configuration.get(Parameter.URL) + "'>" + Configuration.get(Parameter.URL) + "</a>";288 }289 ReportContext.getTempDir().delete();290 // Update JIRA291 Jira.updateAfterSuite(context, EmailReportItemCollector.getTestResults());292 // Update Spira293 Spira.updateAfterSuite(this.getClass().getName(), testResult, title + "; " + getCIJobReference(), suiteName, startDate);294 //generate and send email report by Zafira to test group of people295 String emailList = Configuration.get(Parameter.EMAIL_LIST);296 String failureEmailList = Configuration.get(Parameter.FAILURE_EMAIL_LIST);297 String senderEmail = Configuration.get(Parameter.SENDER_EMAIL);298 String senderPassword = Configuration.get(Parameter.SENDER_PASSWORD);299 // Generate and send email report using regular method300 EmailReportGenerator report = new EmailReportGenerator(title, env,301 Configuration.get(Parameter.APP_VERSION), deviceName,302 browser, DateUtils.now(), DateUtils.timeDiff(startDate), getCIJobReference(),303 EmailReportItemCollector.getTestResults(),304 EmailReportItemCollector.getCreatedItems());305 String emailContent = report.getEmailBody();306 307 if (!R.ZAFIRA.getBoolean("zafira_enabled")) {308 //Do not send email if run is running with enabled Zafira309 EmailManager.send(title, emailContent,310 emailList,311 senderEmail,312 senderPassword);313 314 if (testResult.equals(TestResultType.FAIL) && !failureEmailList.isEmpty()) {315 EmailManager.send(title, emailContent,316 failureEmailList,317 senderEmail,318 senderPassword);319 }320 }321 // Store emailable report under emailable-report.html322 ReportContext.generateHtmlReport(emailContent);323 printExecutionSummary(EmailReportItemCollector.getTestResults());324 TestResultType suiteResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults());325 switch (suiteResult) {326 case SKIP_ALL:327 Assert.fail("All tests were skipped! Analyze logs to determine possible configuration issues.");328 break;329 case SKIP_ALL_ALREADY_PASSED:330 LOGGER.info("Nothing was executed in rerun mode because all tests already passed and registered in Zafira Repoting Service!");331 break;332 default:333 //do nothing334 }335 336 } catch (Exception e) {337 LOGGER.error("Exception in AbstractTest->executeAfterSuite: " + e.getMessage());338 e.printStackTrace();339 }340 }341 private String getDeviceName() {342 String deviceName = "Desktop";343 if (Configuration.get(Parameter.DRIVER_TYPE).toLowerCase().contains(SpecialKeywords.MOBILE)) {344 //Samsung - Android 4.4.2; iPhone - iOS 7345 String deviceTemplate = "%s - %s %s";346 deviceName = String.format(deviceTemplate, Configuration.get(Parameter.MOBILE_DEVICE_NAME), Configuration.get(Parameter.MOBILE_PLATFORM_NAME), Configuration.get(Parameter.MOBILE_PLATFORM_VERSION));347 }348 return deviceName;349 }350 protected String getBrowser() {351 String browser = "";352 if (!Configuration.get(Parameter.BROWSER).isEmpty()) {353 browser = Configuration.get(Parameter.BROWSER);354 }355 if (!browserVersion.isEmpty()) {356 browser = browser + " " + browserVersion;357 }358 return browser;359 }360 protected String getTitle(ITestContext context) {361 String browser = getBrowser();362 if (!browser.isEmpty()) {363 browser = " " + browser; //insert the space before364 }365 String device = getDeviceName();366 String env = !Configuration.isNull(Parameter.ENV) ? Configuration.get(Parameter.ENV) : Configuration.get(Parameter.URL);367 String title = "";368 String app_version = "";369 if (!Configuration.get(Parameter.APP_VERSION).isEmpty()) {370 // if nothing is specified then title will contain nothing371 app_version = Configuration.get(Parameter.APP_VERSION) + " - ";372 }373 String suiteName = getSuiteName(context);374 String xmlFile = getSuiteFileName(context);375 title = String.format(SUITE_TITLE, app_version, suiteName, String.format(XML_SUITE_NAME, xmlFile), env, device, browser);376 return title;377 }378 private String getSuiteFileName(ITestContext context) {379 String fileName = context.getSuite().getXmlSuite().getFileName();380 LOGGER.debug("Full suite file name: " + fileName);381 if (fileName.contains("\\")) {382 fileName = fileName.replaceAll("\\\\", "/");383 }384 fileName = StringUtils.substringAfterLast(fileName, "/");385 LOGGER.debug("Short suite file name: " + fileName);386 return fileName;387 }388 protected String getSuiteName(ITestContext context) {389 String suiteName = "";390 if (context.getSuite().getXmlSuite() != null && !"Default suite".equals(context.getSuite().getXmlSuite().getName())) {391 suiteName = Configuration.get(Parameter.SUITE_NAME).isEmpty() ? context.getSuite().getXmlSuite().getName()392 : Configuration.get(Parameter.SUITE_NAME);393 } else {394 suiteName = Configuration.get(Parameter.SUITE_NAME).isEmpty() ? R.EMAIL.get("title") : Configuration.get(Parameter.SUITE_NAME);395 }396 String appender = getSuiteNameAppender();397 if (appender != null && !appender.isEmpty()) {398 suiteName = suiteName + " - " + appender;399 }400 return suiteName;401 }402 protected void setSuiteNameAppender(String appender) {403 suiteNameAppender.set(appender);404 }405 protected String getSuiteNameAppender() {406 return suiteNameAppender.get();407 }408 private void printExecutionSummary(List<TestResultItem> tris) {409 Messager.INROMATION410 .info("**************** Test execution summary ****************");411 int num = 1;412 for (TestResultItem tri : tris) {413 String failReason = tri.getFailReason();414 if (failReason == null) {415 failReason = "";416 }417 if (!tri.isConfig() && !failReason.contains(SpecialKeywords.ALREADY_PASSED)418 && !failReason.contains(SpecialKeywords.SKIP_EXECUTION)) {419 String reportLinks = !StringUtils.isEmpty(tri.getLinkToScreenshots())420 ? "screenshots=" + tri.getLinkToScreenshots() + " | " : "";421 reportLinks += !StringUtils.isEmpty(tri.getLinkToLog()) ? "log=" + tri.getLinkToLog() : "";422 Messager.TEST_RESULT.info(String.valueOf(num++), tri.getTest(), tri.getResult().toString(),423 reportLinks);424 }425 }426 }427 private String getCIJobReference() {428 String ciTestJob = null;429 if (!Configuration.isNull(Parameter.CI_URL)430 && !Configuration.isNull(Parameter.CI_BUILD)) {431 ciTestJob = Configuration.get(Parameter.CI_URL)432 + Configuration.get(Parameter.CI_BUILD);433 }434 return ciTestJob;435 }436 /**437 * Redefine Jira tickets from test.438 *439 * @param tickets to set440 */441 @Deprecated442 protected void setJiraTicket(String... tickets) {443 List<String> jiraTickets = new ArrayList<String>();444 for (String ticket : tickets) {445 jiraTickets.add(ticket);446 }447 Jira.setTickets(jiraTickets);448 }449 /**450 * Redefine TestRails cases from test.451 *452 * @param cases to set453 */454 protected void setTestRailCase(String... cases) {455 TestRail.setCasesID(cases);456 }457 @DataProvider(name = "DataProvider", parallel = true)458 public Object[][] createData(final ITestNGMethod testMethod, ITestContext context)459 {460 Annotation[] annotations = testMethod.getConstructorOrMethod().getMethod().getDeclaredAnnotations();461 Object[][] objects = DataProviderFactory.getNeedRerunDataProvider(annotations, context, testMethod);462 return objects;463 }464 @DataProvider(name = "SingleDataProvider")465 public Object[][] createDataSingeThread(final ITestNGMethod testMethod,466 ITestContext context) {467 Annotation[] annotations = testMethod.getConstructorOrMethod().getMethod().getDeclaredAnnotations();468 Object[][] objects = DataProviderFactory.getNeedRerunDataProvider(annotations, context, testMethod);469 return objects;470 }471 /**472 * Pause for specified timeout.473 *474 * @param timeout in seconds.475 */476 public void pause(long timeout) {477 try {478 Thread.sleep(timeout * 1000);479 } catch (InterruptedException e) {480 e.printStackTrace();481 }482 }483 public void pause(Double timeout) {484 try {485 timeout = timeout * 1000;486 long miliSec = timeout.longValue();487 Thread.sleep(miliSec);488 } catch (InterruptedException e) {489 e.printStackTrace();490 }491 }492 protected void putS3Artifact(String key, String path) {493 AmazonS3Manager.getInstance().put(Configuration.get(Parameter.S3_BUCKET_NAME), key, path);494 }495 protected S3Object getS3Artifact(String bucket, String key) {496 return AmazonS3Manager.getInstance().get(Configuration.get(Parameter.S3_BUCKET_NAME), key);497 }498 protected S3Object getS3Artifact(String key) {499 return getS3Artifact(Configuration.get(Parameter.S3_BUCKET_NAME), key);500 }501 /**502 * Method to update MOBILE_APP path in case if apk is located in s3 bucket.503 */504 private void updateS3AppPath() {505 Pattern S3_BUCKET_PATTERN = Pattern.compile("s3:\\/\\/([a-zA-Z-0-9][^\\/]*)\\/(.*)");506 // get app path to be sure that we need(do not need) to download app507 // from s3 bucket508 String mobileAppPath = Configuration.get(Parameter.MOBILE_APP);509 Matcher matcher = S3_BUCKET_PATTERN.matcher(mobileAppPath);510 LOGGER.info("Analyzing if mobile_app is located on S3...");511 if (matcher.find()) {512 LOGGER.info("app artifact is located on s3...");513 String bucketName = matcher.group(1);514 String key = matcher.group(2);515 Pattern pattern = Pattern.compile(key);516 // analyze if we have any pattern inside mobile_app to make extra517 // search in AWS518 int position = key.indexOf(".*");519 if (position > 0) {520 // /android/develop/dfgdfg.*/Mapmyrun.apk521 int slashPosition = key.substring(0, position).lastIndexOf("/");522 if (slashPosition > 0) {523 key = key.substring(0, slashPosition);524 S3ObjectSummary lastBuild = AmazonS3Manager.getInstance().getLatestBuildArtifact(bucketName, key,525 pattern);526 key = lastBuild.getKey();527 }528 }529 S3Object objBuild = AmazonS3Manager.getInstance().get(bucketName, key);530 String s3LocalStorage = Configuration.get(Parameter.S3_LOCAL_STORAGE);531 String fileName = s3LocalStorage + "/" + StringUtils.substringAfterLast(objBuild.getKey(), "/");532 File file = new File(fileName);533 // verify maybe requested artifact with the same size was already534 // download535 if (file.exists() && file.length() == objBuild.getObjectMetadata().getContentLength()) {536 LOGGER.info("build artifact with the same size already downloaded: " + file.getAbsolutePath());537 } else {538 LOGGER.info(String.format("Following data was extracted: bucket: %s, key: %s, local file: %s", bucketName, key,539 file.getAbsolutePath()));540 AmazonS3Manager.getInstance().download(bucketName, key, new File(fileName));541 }542 R.CONFIG.put(Parameter.MOBILE_APP.getKey(), file.getAbsolutePath());543 LOGGER.info("Updated mobile_app: " + Configuration.get(Parameter.MOBILE_APP));544 }545 }546 protected void setBug(String id) {547 String test = TestNamingUtil.getTestNameByThread();548 TestNamingUtil.associateBug(test, id);549 }550 protected void skipExecution(String message) {551 throw new SkipException(SpecialKeywords.SKIP_EXECUTION + ": " + message);552 }553 // --------------------------------------------------------------------------554 // Web Drivers...

Full Screen

Full Screen

Source:AmazonS3Manager.java Github

copy

Full Screen

...40import com.qaprosoft.carina.core.foundation.crypto.CryptoTool;41import com.qaprosoft.carina.core.foundation.utils.Configuration;42import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter;43import com.qaprosoft.carina.core.foundation.utils.common.CommonUtils;44public class AmazonS3Manager {45 protected static final Logger LOGGER = Logger46 .getLogger(AmazonS3Manager.class);47 private static volatile AmazonS3Manager instance = null;48 private static AmazonS3 s3client = null;49 private AmazonS3Manager() {50 }51 public static AmazonS3Manager getInstance() {52 if (instance == null) {53 synchronized (AmazonS3Manager.class) {54 if (instance == null) {55 instance = new AmazonS3Manager();56 CryptoTool cryptoTool = new CryptoTool(Configuration.get(Parameter.CRYPTO_KEY_PATH));57 Pattern CRYPTO_PATTERN = Pattern.compile(SpecialKeywords.CRYPT);58 59 String accessKey = cryptoTool.decryptByPattern(Configuration.get(Parameter.ACCESS_KEY_ID), CRYPTO_PATTERN);60 String secretKey = cryptoTool.decryptByPattern(Configuration.get(Parameter.SECRET_KEY), CRYPTO_PATTERN);61 System.setProperty("aws.accessKeyId", accessKey);62 System.setProperty("aws.secretKey", secretKey);63 s3client = new AmazonS3Client(new SystemPropertiesCredentialsProvider());64 }65 }66 }67 return instance;68 }69 public AmazonS3 getClient() {...

Full Screen

Full Screen

Source:AmazonS3ClientTest.java Github

copy

Full Screen

...19import org.testng.annotations.Test;20public class AmazonS3ClientTest {21 @Test()22 public void testS3ManagerInit() {23 Assert.assertNotNull(AmazonS3Manager.getInstance(), "Singleton for AmazonS3Manager is null!");24 }25 @Test()26 public void testPutKeyNull() {27 try {28 AmazonS3Manager.getInstance().put("", null, null);29 Assert.fail("Key verification doesn't work!");30 } catch (RuntimeException e) {31 // Expected failure32 }33 }34 @Test()35 public void testPutKeyEmpty() {36 try {37 AmazonS3Manager.getInstance().put("", "", null);38 Assert.fail("Key verification doesn't work!");39 } catch (RuntimeException e) {40 // Expected failure41 }42 }43 @Test()44 public void testPutFilePathNull() {45 try {46 AmazonS3Manager.getInstance().put("", "test", null);47 Assert.fail("FilePath verification doesn't work!");48 } catch (RuntimeException e) {49 // Expected failure50 }51 }52 @Test()53 public void testPutFilePathEmpty() {54 try {55 AmazonS3Manager.getInstance().put("", "test", "");56 Assert.fail("FilePath verification doesn't work!");57 } catch (RuntimeException e) {58 // Expected failure59 }60 }61 @Test()62 public void testPutFilePathNotExist() {63 try {64 AmazonS3Manager.getInstance().put("", "test", "test");65 Assert.fail("File existence verification doesn't work!");66 } catch (RuntimeException e) {67 // Expected failure68 }69 }70 @Test()71 public void testGetKeyNull() {72 try {73 AmazonS3Manager.getInstance().get("test", null);74 Assert.fail("Key verification doesn't work!");75 } catch (RuntimeException e) {76 // Expected failure77 }78 }79 @Test()80 public void testDeleteKeyNull() {81 try {82 AmazonS3Manager.getInstance().delete("", null);83 Assert.fail("Key verification doesn't work!");84 } catch (RuntimeException e) {85 // Expected failure86 }87 }88 @Test()89 public void testDeleteKeyEmpty() {90 try {91 AmazonS3Manager.getInstance().delete("", "");92 Assert.fail("Key verification doesn't work!");93 } catch (RuntimeException e) {94 // Expected failure95 }96 }97 @Test()98 public void testgeneratePreSignURL() {99 URL url = AmazonS3Manager.getInstance().generatePreSignUrl("carina.qaprosoft.com", "test.txt", 1000 * 60 * 10);100 System.out.println(url.toString());101 // Example:102 // https://carina.qaprosoft.com.s3.amazonaws.com/test.txt?AWSAccessKeyId=AKIAIF43YTFM7RWG7EVQ&Expires=1506266253&Signature=um7fDD2cZmTKLd%2BLZYs0Yq2%2Fc50%3D103 // TODO: add verification that file is accessible without creds104 }105}...

Full Screen

Full Screen

AmazonS3Manager

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.amazon.AmazonS3Manager;2public class 1 {3 public static void main(String[] args) {4 AmazonS3Manager s3 = new AmazonS3Manager();5 s3.uploadFileToS3("C:/Users/Downloads/1.txt", "test", "1.txt");6 }7}8import com.qaprosoft.amazon.AmazonS3Manager;9public class 2 {10 public static void main(String[] args) {11 AmazonS3Manager s3 = new AmazonS3Manager();12 s3.downloadFileFromS3("test", "1.txt", "C:/Users/Downloads/2.txt");13 }14}15import com.qaprosoft.amazon.AmazonS3Manager;16public class 3 {17 public static void main(String[] args) {18 AmazonS3Manager s3 = new AmazonS3Manager();19 s3.deleteFileFromS3("test", "1.txt");20 }21}22import com.qaprosoft.amazon.AmazonS3Manager;23public class 4 {24 public static void main(String[] args) {25 AmazonS3Manager s3 = new AmazonS3Manager();26 s3.deleteBucketFromS3("test");27 }28}29import com.qaprosoft.amazon.AmazonS3Manager;30public class 5 {31 public static void main(String[] args) {32 AmazonS3Manager s3 = new AmazonS3Manager();33 s3.createBucketInS3("test");34 }35}36import com.qaprosoft.amazon.AmazonS3Manager;37public class 6 {38 public static void main(String[] args) {39 AmazonS3Manager s3 = new AmazonS3Manager();40 s3.listAllBucketsInS3();41 }42}

Full Screen

Full Screen

AmazonS3Manager

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.amazon.AmazonS3Manager;2import com.amazonaws.services.s3.model.Bucket;3import com.amazonaws.services.s3.model.PutObjectResult;4public class AmazonS3ManagerTest {5 public static void main(String[] args) {6 AmazonS3Manager manager = new AmazonS3Manager();7 Bucket bucket = manager.createBucket("testbucket");8 System.out.println("Bucket created: " + bucket.getName());9 PutObjectResult result = manager.uploadFile("testbucket", "testfile.txt", "c:/temp/testfile.txt");10 System.out.println("File uploaded: " + result.getContentMd5());11 }12}13import com.qaprosoft.amazon.AmazonS3Manager;14import com.amazonaws.services.s3.model.Bucket;15import com.amazonaws.services.s3.model.PutObjectResult;16public class AmazonS3ManagerTest {17 public static void main(String[] args) {18 AmazonS3Manager manager = new AmazonS3Manager();19 Bucket bucket = manager.createBucket("testbucket");20 System.out.println("Bucket created: " + bucket.getName());21 PutObjectResult result = manager.uploadFile("testbucket", "testfile.txt", "c:/temp/testfile.txt");22 System.out.println("File uploaded: " + result.getContentMd5());23 }24}25import com.qaprosoft.amazon.AmazonS3Manager;26import com.amazonaws.services.s3.model.Bucket;27import com.amazonaws.services.s3.model.PutObjectResult;28public class AmazonS3ManagerTest {29 public static void main(String[] args) {30 AmazonS3Manager manager = new AmazonS3Manager();31 Bucket bucket = manager.createBucket("testbucket");32 System.out.println("Bucket created: " + bucket.getName());33 PutObjectResult result = manager.uploadFile("testbucket", "testfile.txt", "c:/temp/testfile.txt");34 System.out.println("File uploaded: " + result.getContentMd5());35 }36}37import com.qaprosoft.amazon.AmazonS3Manager;38import com

Full Screen

Full Screen

AmazonS3Manager

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.amazon.AmazonS3Manager;2import com.amazonaws.services.s3.model.Bucket;3import java.io.File;4import java.io.IOException;5import java.util.List;6public class AmazonS3ManagerTest {7 public static void main(String[] args) throws IOException {8 AmazonS3Manager s3Manager = new AmazonS3Manager();9 List<Bucket> buckets = s3Manager.listBuckets();10 for (Bucket bucket : buckets) {11 System.out.println(bucket.getName());12 }13 s3Manager.uploadFile("testbucket", "testfile", new File("C:/Users/.../testfile.txt"));14 }15}16import com.qaprosoft.amazon.AmazonS3Manager;17import com.amazonaws.services.s3.model.Bucket;18import java.io.File;19import java.io.IOException;20import java.util.List;21public class AmazonS3ManagerTest {22 public static void main(String[] args) throws IOException {23 AmazonS3Manager s3Manager = new AmazonS3Manager();24 List<Bucket> buckets = s3Manager.listBuckets();25 for (Bucket bucket : buckets) {26 System.out.println(bucket.getName());27 }28 s3Manager.uploadFile("testbucket", "testfile", new File("C:/Users/.../testfile.txt"));29 }30}31import com.qaprosoft.amazon.AmazonS3Manager;32import com.amazonaws.services.s3.model.Bucket;33import java.io.File;34import java.io.IOException;35import java.util.List;36public class AmazonS3ManagerTest {37 public static void main(String[] args) throws IOException {38 AmazonS3Manager s3Manager = new AmazonS3Manager();39 List<Bucket> buckets = s3Manager.listBuckets();40 for (Bucket bucket : buckets) {41 System.out.println(bucket.getName());42 }43 s3Manager.uploadFile("testbucket", "testfile", new File("C:/Users/.../testfile.txt"));44 }45}46import com.qaprosoft.amazon.AmazonS3Manager;47import com.amazonaws.services.s3.model.B

Full Screen

Full Screen

AmazonS3Manager

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.amazon.AmazonS3Manager;2public class 1 {3public static void main(String[] args) {4AmazonS3Manager s3 = new AmazonS3Manager();5s3.uploadFile("path_to_file", "bucket_name");6}7}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Carina automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful