Need help to find error causing extract from alm

81 views Asked by At

this is java program created to extract testcases from alm using api key but not sure how to configure API key in HP ALM can someone explain me setting up api key is java program created to extract testcases from alm using api key but not sure how to configure API key in HP ALM can someone explain me setting up api keyis java program created to extract testcases from alm using api key but not sure how to configure API key in HP ALM can someone explain me setting up api keyis java program created to extract testcases from alm using api key but not sure how to configure API key in HP ALM can someone explain me setting up api keyis java program created to extract testcases from alm using api key but not sure how to configure API key in HP ALM can someone explain me setting up api key

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ALMTestCaseExtractor {

    public static void main(String[] args) {
        String almURL = "http://your_alm_server:port/qcbin";
        String almDomain = "your_domain";
        String almProject = "your_project";
        String almAPIKey = "your_api_key";
        String almFolderPath = "your_folder_path"; // Example: "Subject\Folder1\Folder2"
        String excelFilePath = "path/to/excel/file.xlsx";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Set ALM API key
            String authorizationHeader = "Bearer " + almAPIKey;

            // Retrieve test cases from ALM
            String testCasesUrl = almURL + "/rest/domains/" + almDomain + "/projects/" + almProject
                    + "/test-instances?query=" + almFolderPath;
            HttpGet httpGet = new HttpGet(testCasesUrl);
            httpGet.setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
            httpGet.setHeader(HttpHeaders.ACCEPT, "application/json");

            String responseString = EntityUtils.toString(httpClient.execute(httpGet).getEntity());
            List<Map<String, Object>> testCases = extractTestCasesFromResponse(responseString);

            // Create Excel workbook
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Test Cases");

            // Create headers
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("Test Case Name");
            headerRow.createCell(1).setCellValue("Description");
            headerRow.createCell(2).setCellValue("Steps");
            headerRow.createCell(3).setCellValue("Expected Results");

            // Populate test case data
            int rowIndex = 1;
            for (Map<String, Object> testCase : testCases) {
                Row row = sheet.createRow(rowIndex++);
                row.createCell(0).setCellValue((String) testCase.get("name"));
                row.createCell(1).setCellValue((String) testCase.get("description"));
                row.createCell(2).setCellValue((String) testCase.get("steps"));
                row.createCell(3).setCellValue((String) testCase.get("expected-results"));
            }

            // Save Excel file
            try (OutputStream outputStream = new FileOutputStream(excelFilePath)) {
                workbook.write(outputStream);
                System.out.println("Test cases exported to Excel successfully.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<Map<String, Object>> extractTestCasesFromResponse(String responseString) {
        // Parse the JSON response and extract the relevant test case information
        // You can use your preferred JSON parsing library for this task
        // Here, we're assuming the response is in a specific JSON structure
        // Modify the code accordingly if your ALM API response structure is different
        // This is just a sample implementation
        // You may need to adjust it to fit your requirements
        // ...
        // Your JSON parsing logic goes here
        // ...
        return null; // Modify the return statement to return the actual test case data
    }
}


this is java program created to extract testcases from alm using api key
but not sure how to configure API key in HP ALM
can someone explain me setting up api key
is java program created to extract testcases from alm using api key
but not sure how to configure API key in HP ALM
can someone explain me setting up api keyis java program created to extract testcases from alm using api key
but not sure how to configure API key in HP ALM
can someone explain me setting up api keyis java program created to extract testcases from alm using api key
but not sure how to configure API key in HP ALM
can someone explain me setting up api keyis java program created to extract testcases from alm using api key
but not sure how to configure API key in HP ALM
can someone explain me setting up api key
4

There are 4 answers

1
Shricode On
        import org.apache.http.HttpEntity;
        import org.apache.http.HttpHeaders;
        import org.apache.http.HttpResponse;
        import org.apache.http.auth.AuthScope;
        import org.apache.http.auth.UsernamePasswordCredentials;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.impl.client.CloseableHttpClient;
        import org.apache.http.impl.client.HttpClients;
        import org.apache.http.util.EntityUtils;
        import org.json.JSONArray;
        import org.json.JSONObject;
        
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.nio.charset.StandardCharsets;
        import java.util.ArrayList;
        import java.util.Base64;
        import java.util.List;
        
        public class ExtractTestCasesFromALM {
        
            private static final String ALM_URL = "http://your_alm_server:port/qcbin";
            private static final String ALM_DOMAIN = "your_domain";
            private static final String ALM_PROJECT = "your_project";
            private static final String ALM_FOLDER_PATH = "your_folder_path"; // Example: "Subject\Folder1\Folder2"
            private static final String ALM_USERNAME = "your_username";
            private static final String ALM_PASSWORD = "your_password";
            private static final String EXCEL_FILE_PATH = "path/to/excel/file.xlsx";
        
            public static void main(String[] args) throws IOException {
                // Create an HTTP client with basic authentication
                CloseableHttpClient httpClient = HttpClients.custom()
                        .setDefaultCredentialsProvider(createCredentialsProvider())
                        .build();
        
                // Set up the request
                String url = ALM_URL + "/rest/domains/" + ALM_DOMAIN + "/projects/" + ALM_PROJECT + "/test-instances";
                String query = "{test-set.folder-path[" + ALM_FOLDER_PATH + "]}";
                url += "?query=" + query;
        
                HttpGet request = new HttpGet(url);
                request.setHeader(HttpHeaders.ACCEPT, "application/json");
        
                // Send the request and process the response
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
        
                if (statusCode == 200) {
                    String responseBody = EntityUtils.toString(response.getEntity());
                    List<TestInstance> testInstances = extractTestInstances(responseBody);
        
                    // Export the test instances to Excel
                    exportToExcel(testInstances);
                } else {
                    System.out.println("Failed to retrieve test instances. Status code: " + statusCode);
                }
        
                // Close the HTTP client
                httpClient.close();
            }
        
            private static CredentialsProvider createCredentialsProvider() {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(ALM_USERNAME, ALM_PASSWORD));
                return credentialsProvider;
            }
        
            private static List<TestInstance> extractTestInstances(String responseBody) {
                List<TestInstance> testInstances = new ArrayList<>();
        
                JSONObject responseJson = new JSONObject(responseBody);
                JSONArray entities = responseJson.getJSONArray("entities");
        
                for (int i = 0; i < entities.length(); i++) {
                    JSONObject entity = entities.getJSONObject(i);
                    JSONObject fields = entity.getJSONObject("Fields");
        
                    String name = fields.getJSONObject("name").getString("values");
                    String description = fields.getJSONObject("description").getString("values");
                    String steps = fields.getJSONObject("steps").getString("values");
                    String expectedResults = fields.getJSONObject("expected-results").getString("values");
        
                    TestInstance testInstance = new TestInstance(name, description, steps, expectedResults);
                    testInstances.add(testInstance);
                }
        
                return testInstances;
            }
        
            private static void exportToExcel(List<TestInstance> testInstances, String filePath) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Test Cases");
    
            // Create headers
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("Name");
            headerRow.createCell(1).setCellValue("Description");
            headerRow.createCell(2).setCellValue("Steps");
            headerRow.createCell(3).setCellValue("Expected Results");
    
            // Populate data
            int rowNum = 1;
            for (TestInstance testInstance : testInstances) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(testInstance.getName());
                row.createCell(1).setCellValue(testInstance.getDescription());
                row.createCell(2).setCellValue(testInstance.getSteps());
                row.createCell(3).setCellValue(testInstance.getExpectedResults());
            }
    
            // Auto-size columns
            for (int i = 0; i < 4; i++) {
                sheet.autoSizeColumn(i);
            }
    
            // Write the workbook to the Excel file
            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                workbook.write(outputStream);
            }
    
            System.out.println("Test cases exported to Excel successfully!");
        } catch (IOException e) {
            System.out.println("Error exporting test cases to Excel: " + e.getMessage());
        }
    }
    In this implementation, we create a new XSSFWorkbook instance to represent the Excel workbook. Then, we create a sheet named "Test Cases" and add headers for the test case fields. We iterate over the list of TestIns


public class TestInstance {
    private String name;
    private String description;
    private String steps;
    private String expectedResults;

    public TestInstance(String name, String description, String steps, String expectedResults) {
        this.name = name;
        this.description = description;
        this.steps = steps;
        this.expectedResults = expectedResults;
    }

    // Getters and setters

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSteps() {
        return steps;
    }

    public void setSteps(String steps) {
        this.steps = steps;
    }

    public String getExpectedResults() {
        return expectedResults;
    }

    public void setExpectedResults(String expectedResults) {
        this.expectedResults = expectedResults;
    }
}
0
Shricode On
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExtractTestCasesFromALM {

    private static final String ALM_URL = "http://your_alm_server:port/qcbin";
    private static final String ALM_DOMAIN = "your_domain";
    private static final String ALM_PROJECT = "your_project";
    private static final String ALM_FOLDER_PATH = "your_folder_path"; // Example: "Subject\Folder1\Folder2"
    private static final String API_KEY = "your_api_key";
    private static final String API_SECRET = "your_api_secret";
    private static final String EXCEL_FILE_PATH = "path/to/excel/file.xlsx";

    public static void main(String[] args) throws IOException {
        // Create an HTTP client
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // Set up the request
        String url = ALM_URL + "/rest/domains/" + ALM_DOMAIN + "/projects/" + ALM_PROJECT + "/test-instances";
        String query = "{test-set.folder-path[" + ALM_FOLDER_PATH + "]}";
        url += "?query=" + query;

        HttpGet request = new HttpGet(url);
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodeCredentials(API_KEY, API_SECRET));

        // Send the request and process the response
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {
            String responseBody = EntityUtils.toString(response.getEntity());
            List<TestInstance> testInstances = extractTestInstances(responseBody);

            // Export the test instances to Excel
            exportToExcel(testInstances);
        } else {
            System.out.println("Failed to retrieve test instances. Status code: " + statusCode);
        }

        // Close the HTTP client
        httpClient.close();
    }

    private static String encodeCredentials(String apiKey, String apiSecret) {
        String credentials = apiKey + ":" + apiSecret;
        return java.util.Base64.getEncoder().encodeToString(credentials.getBytes());
    }

    private static List<TestInstance> extractTestInstances(String responseBody) {
        List<TestInstance> testInstances = new ArrayList<>();

        JSONObject responseJson = new JSONObject(responseBody);
        JSONArray entities = responseJson.getJSONArray("entities");

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entity = entities.getJSONObject(i);
            JSONObject fields = entity.getJSONObject("Fields");

            String name = fields.getJSONObject("name").getString("values");
            String description = fields.getJSONObject("description").getString("values");
            String steps = fields.getJSONObject("steps").getString("values");
            String expectedResults = fields.getJSONObject("expected-results").getString("values");

            TestInstance testInstance = new TestInstance(name, description, steps, expectedResults);
            testInstances.add(testInstance);
        }

        return testInstances;
    }

    private static void exportToExcel(List<TestInstance> testInstances) {
        // Code to export the test instances to Excel
        // You can use a library like Apache PO
1
Shricode On
latest

Sub ConnectToALM()
    ' Create an OTA object
    Dim tdc As Object
    Set tdc = CreateObject("TDApiOle80.TDConnection")
    
    ' Set the ALM server URL
    tdc.InitConnectionEx "https://my-alm-server-url.com/qcbin/"
    
    ' Login to ALM
    tdc.Login "my-username", "my-password"
    
    ' Connect to a project
    tdc.Connect "my-domain", "my-project"
    
    ' Check if the connection was successful
   If tdc.Connected Then
        MsgBox "Connected to ALM successfully!"
    Else
        MsgBox "Failed to connect to ALM."
    End If
    
    ' Disconnect from ALM and logout
    tdc.Disconnect
    tdc.Logout
End Sub



Sub DownloadTestCasesFromALM()
    ' Create an OTA object and connect to ALM
    Dim tdc As Object
    Set tdc = CreateObject("TDApiOle80.TDConnection")
    tdc.InitConnectionEx "https://my-alm-server-url.com/qcbin/"
    tdc.Login "my-username", "my-password"
    tdc.Connect "my-domain", "my-project"
    
    ' Get the test case factory
    Dim testSetFact As Object
    Set testSetFact = tdc.TestSetFactory
    
    ' Get the test case tree manager
    Dim treeMgr As Object
    Set treeMgr = tdc.TestSetTreeManager
    
    ' Get the root folder of the test cases
    Dim rootNode As Object
    Set rootNode = treeMgr.NodeByPath("Root\Test Cases")
    
    ' Get all test cases under the root folder
    Dim testCases As Object
    Set testCases = rootNode.FindTestInstances("", False, "")
    
    ' Create a new Excel worksheet
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ThisWorkbook
    Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
    
    ' Write the test case data to the worksheet
    Dim row As Long
    row = 1
    ws.Cells(row, 1).Value = "Test Case ID"
    ws.Cells(row, 2).Value = "Test Case Name"
    row = row + 1
    For Each testCase In testCases
        ws.Cells(row, 1).Value = testCase.Field("TS_TEST_ID")
        ws.Cells(row, 2).Value = testCase.Field("TS_NAME")
        row = row + 1
    Next testCase
    
    ' Disconnect from ALM and logout
    tdc.Disconnect
    tdc.Logout
    
    ' Autofit columns
    ws.Columns.AutoFit
End Sub


Sub DownloadTestCasesWithStepsFromALM()
    ' Create an OTA object and connect to ALM
    Dim tdc As Object
    Set tdc = CreateObject("TDApiOle80.TDConnection")
    tdc.InitConnectionEx "https://my-alm-server-url.com/qcbin/"
    tdc.Login "my-username", "my-password"
    tdc.Connect "my-domain", "my-project"
    
    ' Get the test case factory
    Dim testSetFact As Object
    Set testSetFact = tdc.TestSetFactory
    
    ' Get the test case tree manager
    Dim treeMgr As Object
    Set treeMgr = tdc.TestSetTreeManager
    
    ' Get the root folder of the test cases
    Dim rootNode As Object
    Set rootNode = treeMgr.NodeByPath("Root\Test Cases")
    
    ' Get all test cases under the root folder
    Dim testCases As Object
    Set testCases = rootNode.FindTestInstances("", False, "")
    
    ' Create a new Excel worksheet
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ThisWorkbook
    Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
    
    ' Write the test case and step data to the worksheet
    Dim row As Long
    row = 1
    ws.Cells(row, 1).Value = "Test Case ID"
    ws.Cells(row, 2).Value = "Test Case Name"
    ws.Cells(row, 3).Value = "Step ID"
    ws.Cells(row, 4).Value = "Step Description"
    ws.Cells(row, 5).Value = "Expected Result"
    row = row + 1
    For Each testCase In testCases
        ' Get the test case details
        Dim tcDetails As Object
        Set tcDetails = testCase.Detail
        
        ' Write the test case data to the worksheet
        ws.Cells(row, 1).Value = tcDetails.Field("TS_TEST_ID")
        ws.Cells(row, 2).Value = tcDetails.Field("TS_NAME")
        row = row + 1
        
        ' Get the test case steps
        Dim tsFact As Object
        Set tsFact = tcDetails.StepFactory
        Dim steps As Object
        Set steps = tsFact.NewList("")
        
        ' Write the test case steps to the worksheet
        For Each step In steps
            ws.Cells(row, 1).Value = tcDetails.Field("TS_TEST_ID")
            ws.Cells(row, 2).Value = tcDetails.Field("TS_NAME")
            ws.Cells(row, 3).Value = step.Field("ST_STEP_ID")
            ws.Cells(row, 4).Value = step.Field("ST_DESCRIPTION")
            ws.Cells(row, 5).Value = step.Field("ST_EXPECTED")
            row = row + 1
        Next step
    Next testCase
    
    ' Disconnect from ALM and logout
    tdc.Disconnect
    tdc.Logout
    
    ' Autofit columns
    ws.Columns.AutoFit
End Sub
0
Shricode On
package test;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class EntitlementReview {
    private static final String USER_AGENT = "Mozilla/5.0";
    private static final String ARTIFACTORY_API_KEY = "MMMMMMMAaA"; // Replace with your API key
    private static final String ARTIFACTORY_BASE_URL = "https://artifactory/api/security/";

    static ArrayList<String> groupNames = new ArrayList<>();
    static List<Users> groupMemberNames = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        getGroupNames();
        getAllMembers();
        generateReport();
    }

    private static JsonObject artifactoryApiCall(String url) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("X-JFrog-Art-Api", ARTIFACTORY_API_KEY);
        int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(in);
            in.close();
            return jsonElement.getAsJsonObject();
        } else {
            throw new IOException("API call failed with response code: " + responseCode);
        }
    }

    private static void getGroupNames() throws IOException {
        JsonObject groups = artifactoryApiCall(ARTIFACTORY_BASE_URL + "groups");
        JsonArray groupArray = groups.getAsJsonArray("groups");

        for (JsonElement groupElement : groupArray) {
            JsonObject group = groupElement.getAsJsonObject();
            groupNames.add(group.get("name").getAsString());
        }
    }

    private static void getMembers(String groupName) throws IOException {
        JsonObject members = artifactoryApiCall(ARTIFACTORY_BASE_URL + "groups/" + groupName + "?includeUsers=true");
        JsonArray memberArray = members.getAsJsonArray("users");

        for (JsonElement memberElement : memberArray) {
            JsonObject member = memberElement.getAsJsonObject();
            String username = member.get("name").getAsString();
            boolean isAdmin = member.get("admin").getAsBoolean();
            String userType = isAdmin ? "Service Account" : "Human";
            groupMemberNames.add(new Users("", username, "", "", username, userType, "", isAdmin));
        }
    }

    private static void getAllMembers() throws IOException {
        JsonObject members = artifactoryApiCall(ARTIFACTORY_BASE_URL + "users");
        JsonArray memberArray = members.getAsJsonArray("users");

        for (JsonElement memberElement : memberArray) {
            JsonObject member = memberElement.getAsJsonObject();
            String username = member.get("name").getAsString();

            // Skip members that are already added to groupMemberNames
            boolean isExistingMember = groupMemberNames.stream()
                    .anyMatch(existingMember -> existingMember.getAccountID().equals(username));

            if (!isExistingMember) {
                boolean isAdmin = member.get("admin").getAsBoolean();
                String userType = isAdmin ? "Service Account" : "Human";
                groupMemberNames.add(new Users("", username, "", "", username, userType, "", isAdmin));
            }
        }
    }

    private static void generateReport() {
        // Implement your report generation logic here
    }
}