Example usage for com.amazonaws.services.devicefarm.model Project getArn

List of usage examples for com.amazonaws.services.devicefarm.model Project getArn

Introduction

In this page you can find the example usage for com.amazonaws.services.devicefarm.model Project getArn.

Prototype


public String getArn() 

Source Link

Document

The project's ARN.

Usage

From source file:org.jenkinsci.plugins.awsdevicefarm.AWSDeviceFarm.java

License:Open Source License

/**
 * Get Device Farm device pools for a given Device Farm project.
 *
 * @param project Device Farm Project./* w ww .j  a v a2  s.  c o m*/
 * @return A List of the Device Farm device pools.
 * @throws AWSDeviceFarmException
 */
public List<DevicePool> getDevicePools(Project project) {
    ListDevicePoolsResult poolsResult = api
            .listDevicePools(new ListDevicePoolsRequest().withArn(project.getArn()));
    List<DevicePool> pools = poolsResult.getDevicePools();
    return pools;
}

From source file:org.jenkinsci.plugins.awsdevicefarm.AWSDeviceFarm.java

License:Open Source License

/**
 * Private method to handle upload apps and tests to Device Farm.
 *
 * @param file        The file to upload.
 * @param project     TheDevice Farm project to upload to.
 * @param uploadType  The type of upload (app/test/etc.).
 * @param synchronous Whether or not to wait for the upload to complete before returning.
 * @return The Device Farm Upload object.
 * @throws IOException/*  www  . j a va2s .  c  o m*/
 * @throws AWSDeviceFarmException
 */
private Upload upload(File file, Project project, AWSDeviceFarmUploadType uploadType, Boolean synchronous)
        throws InterruptedException, IOException, AWSDeviceFarmException {
    CreateUploadRequest appUploadRequest = new CreateUploadRequest().withName(file.getName())
            .withProjectArn(project.getArn()).withContentType("application/octet-stream")
            .withType(uploadType.toString());
    Upload upload = api.createUpload(appUploadRequest).getUpload();

    CloseableHttpClient httpClient = HttpClients.createSystem();
    HttpPut httpPut = new HttpPut(upload.getUrl());
    httpPut.setHeader("Content-Type", upload.getContentType());

    FileEntity entity = new FileEntity(file);
    httpPut.setEntity(entity);

    writeToLog(String.format("Uploading %s to S3", file.getName()));
    HttpResponse response = httpClient.execute(httpPut);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new AWSDeviceFarmException(String.format("Upload returned non-200 responses: %d",
                response.getStatusLine().getStatusCode()));
    }

    if (synchronous) {
        while (true) {
            GetUploadRequest describeUploadRequest = new GetUploadRequest().withArn(upload.getArn());
            GetUploadResult describeUploadResult = api.getUpload(describeUploadRequest);
            String status = describeUploadResult.getUpload().getStatus();

            if ("SUCCEEDED".equalsIgnoreCase(status)) {
                writeToLog(String.format("Upload %s succeeded", file.getName()));
                break;
            } else if ("FAILED".equalsIgnoreCase(status)) {
                writeToLog(String.format("Error message from device farm: '%s'",
                        describeUploadResult.getUpload().getMetadata()));
                throw new AWSDeviceFarmException(String.format("Upload %s failed!", upload.getName()));
            } else {
                try {
                    writeToLog(String.format("Waiting for upload %s to be ready (current status: %s)",
                            file.getName(), status));
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    writeToLog(String.format("Thread interrupted while waiting for the upload to complete"));
                    throw e;
                }
            }
        }
    }

    return upload;
}

From source file:org.jenkinsci.plugins.awsdevicefarm.AWSDeviceFarmRecorder.java

License:Open Source License

/**
 * Perform the post-build test action./*  ww  w  . j  a v a  2  s  .c o m*/
 *
 * @param build    The build to follow.
 * @param launcher The launcher.
 * @param listener The build launcher.
 * @return Whether or not the post-build action succeeded.
 * @throws IOException
 * @throws InterruptedException
 */
@Override
public void perform(@Nonnull hudson.model.Run<?, ?> build, @Nonnull FilePath workspace,
        @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    // Check if the build result set from a previous build step.
    // A null build result indicates that the build is still ongoing and we're
    // likely being run as a build step by the "Any Build Step Plugin".
    Result buildResult = build.getResult();
    if (buildResult != null && buildResult.isWorseOrEqualTo(Result.FAILURE)) {
        listener.error("Still building");
    }

    EnvVars env = build.getEnvironment(listener);
    Map<String, String> parameters = build.getEnvironment(listener);

    log = listener.getLogger();

    // Artifacts location for this build on master.
    FilePath artifactsDir = new FilePath(build.getArtifactsDir());

    // Validate user selection & input values.
    boolean isValid = validateConfiguration() && validateTestConfiguration();
    if (!isValid) {
        writeToLog("Invalid configuration.");
        return;
    }

    // Create & configure the AWSDeviceFarm client.
    AWSDeviceFarm adf = getAWSDeviceFarm().withLogger(listener.getLogger()).withWorkspace(workspace)
            .withArtifactsDir(artifactsDir).withEnv(env);
    try {
        // Accept 'ADF_PROJECT' build parameter as an overload from job configuration.
        String projectNameParameter = parameters.get("AWSDEVICEFARM_PROJECT");
        if (projectNameParameter != null && !projectNameParameter.isEmpty()) {
            writeToLog(
                    String.format("Using overloaded project '%s' from build parameters", projectNameParameter));
            projectName = projectNameParameter;
        }

        // check for Unmetered Devices on Account
        if (isRunUnmetered != null && isRunUnmetered) {
            String os = adf.getOs(appArtifact);
            int unmeteredDeviceCount = adf.getUnmeteredDevices(os);
            if (unmeteredDeviceCount <= 0) {
                throw new AWSDeviceFarmException(
                        String.format("Your account does not have unmetered %s device slots. Please change "
                                + "your build settings to run on metered devices.", os));
            }
        }

        // Get AWS Device Farm project from user provided name.
        writeToLog(String.format("Using Project '%s'", projectName));
        Project project = adf.getProject(projectName);

        // Accept 'ADF_DEVICE_POOL' build parameter as an overload from job configuration.
        String devicePoolParameter = parameters.get("AWSDEVICEFARM_DEVICE_POOL");
        if (devicePoolParameter != null) {
            writeToLog(String.format("Using overloaded device pool '%s' from build parameters",
                    devicePoolParameter));
            devicePoolName = devicePoolParameter;
        }

        if (StringUtils.isBlank(locale)) {
            locale = "en_US";
        }

        // Get AWS Device Farm device pool from user provided name.
        writeToLog(String.format("Using DevicePool '%s'", devicePoolName));
        DevicePool devicePool = adf.getDevicePool(project, devicePoolName);

        // Upload app.
        String appArn = null;
        if (ifWebApp != null && ifWebApp) {
            writeToLog("Tesing a Web App.");

        } else {
            writeToLog(String.format("Using App '%s'", env.expand(appArtifact)));
            Upload appUpload = adf.uploadApp(project, appArtifact);
            appArn = appUpload.getArn();
        }

        String deviceFarmRunName = null;
        if (StringUtils.isBlank(runName)) {
            deviceFarmRunName = String.format("%s", env.get("BUILD_TAG"));
        } else {
            deviceFarmRunName = String.format("%s", env.expand(runName));
        }

        // Upload test content.
        writeToLog("Getting test to schedule.");
        ScheduleRunTest testToSchedule = getScheduleRunTest(env, adf, project);

        if (ifVideoRecording != null && !ifVideoRecording) {
            testToSchedule.addParametersEntry("video_recording", "false");
        }
        if (ifAppPerformanceMonitoring != null && !ifAppPerformanceMonitoring) {
            testToSchedule.addParametersEntry("app_performance_monitoring", "false");
        }

        // State the Appium Version.
        if (testToRun.equalsIgnoreCase("APPIUM_JAVA_JUNIT"))
            writeToLog(String.format("Using appium version: %s", appiumVersionJunit));
        else if (testToRun.equalsIgnoreCase("APPIUM_WEB_JAVA_JUNIT"))
            writeToLog(String.format("Using appium version: %s", appiumVersionJunit));
        else if (testToRun.equalsIgnoreCase("APPIUM_JAVA_TESTNG"))
            writeToLog(String.format("Using appium version: %s", appiumVersionTestng));
        else if (testToRun.equalsIgnoreCase("APPIUM_WEB_JAVA_TESTNG"))
            writeToLog(String.format("Using appium version: %s", appiumVersionTestng));
        else if (testToRun.equalsIgnoreCase("APPIUM_PYTHON"))
            writeToLog(String.format("Using appium version: %s", appiumVersionPython));
        else if (testToRun.equalsIgnoreCase("APPIUM_WEB_PYTHON"))
            writeToLog(String.format("Using appium version: %s", appiumVersionPython));

        // Upload the extra data.
        String extraDataArn = null;
        if (extraData != null && extraData) {
            writeToLog(String.format("Using Extra Data '%s'", env.expand(extraDataArtifact)));
            Upload extraDataUpload = adf.uploadExtraData(project, extraDataArtifact);
            extraDataArn = extraDataUpload.getArn();
        } else {
            writeToLog(String.format("NOT using Extra Data '%s' with boolean '%s'",
                    env.expand(extraDataArtifact), extraData));
        }

        // Schedule test run.
        TestType testType = TestType.fromValue(testToSchedule.getType());
        writeToLog(String.format("Scheduling '%s' run '%s'", testType, deviceFarmRunName));

        ScheduleRunConfiguration configuration = getScheduleRunConfiguration(isRunUnmetered, deviceLocation,
                radioDetails, locale);
        configuration.setExtraDataPackageArn(extraDataArn);

        ScheduleRunResult run = adf.scheduleRun(project.getArn(), deviceFarmRunName, appArn,
                devicePool.getArn(), testToSchedule, jobTimeoutMinutes, configuration);

        String runArn = run.getRun().getArn();
        try {
            writeToLog(String.format("View the %s run in the AWS Device Farm Console: %s", testType,
                    AWSDeviceFarmUtils.getRunUrlFromArn(runArn)));
        } catch (ArrayIndexOutOfBoundsException e) {
            writeToLog(String.format("Could not parse project ID and run ID from run ARN: %s", runArn));
        }

        // Attach AWS Device Farm action to poll periodically and update results UI.
        AWSDeviceFarmTestResultAction action = new AWSDeviceFarmTestResultAction(build, null, log);
        build.addAction(action);

        // Wait for test result to complete will updating status periodically.
        writeToLog("Waiting for test run to complete.");
        action.waitForRunCompletion(adf, run);
        writeToLog("Test run is complete.");

        // Download results archive and store it.
        if (storeResults) {
            // Create results storage directory which will contain the unzip logs/screenshots pulled from AWS Device Farm.
            FilePath resultsDir = new FilePath(artifactsDir, "AWS Device Farm Results");
            resultsDir.mkdirs();
            writeToLog(String.format("Storing AWS Device Farm results in directory %s", resultsDir));

            Map<String, FilePath> jobs = getJobs(adf, run, resultsDir);
            Map<String, FilePath> suites = getSuites(adf, run, jobs);
            Map<String, FilePath> tests = getTests(adf, run, suites);

            writeToLog("Downloading AWS Device Farm results archive...");
            // Iterating over all values in the Enum.
            for (ArtifactCategory category : new ArrayList<ArtifactCategory>(
                    Arrays.asList(ArtifactCategory.values()))) {
                ListArtifactsResult result = adf.listArtifacts(run.getRun().getArn(), category);
                for (Artifact artifact : result.getArtifacts()) {
                    String arn = artifact.getArn().split(":")[6];
                    String testArn = arn.substring(0, arn.lastIndexOf("/"));
                    String id = arn.substring(arn.lastIndexOf("/") + 1);
                    String extension = artifact.getExtension().replaceFirst("^\\.", "");
                    FilePath artifactFilePath = new FilePath(tests.get(testArn),
                            String.format("%s-%s.%s", artifact.getName(), id, extension));
                    URL url = new URL(artifact.getUrl());
                    artifactFilePath.write().write(IOUtils.toByteArray(url.openStream()));
                }
            }
            writeToLog(String.format("Results archive saved in %s", artifactsDir.getName()));
        }

        // Set Jenkins build result based on AWS Device Farm test result.
        build.setResult(action.getBuildResult(ignoreRunError));
    } catch (AWSDeviceFarmException e) {
        writeToLog(e.getMessage());
        return;
    }

    return;
}