Useful snippets of coding information

Category: Technology

Clone Bit bucket repo

#!/bin/bash

# Configuration
BITBUCKET_URL="https://yourcompany.bitbucket.server"
PROJECT_KEY="CHE"  # Replace with your project key
USERNAME="your_username"  # Replace with your Bitbucket username
ACCESS_TOKEN="your_access_token"  # Replace with your personal access token

# Directory to clone repositories
CLONE_DIR="./${PROJECT_KEY}_repositories"
mkdir -p "$CLONE_DIR"

# Fetch repositories using the Bitbucket API
REPOS=$(curl -s -u "$USERNAME:$ACCESS_TOKEN" \
  "$BITBUCKET_URL/rest/api/1.0/projects/$PROJECT_KEY/repos?limit=100" | \
  jq -r '.values[].links.clone[] | select(.name == "http").href')

# Clone each repository
echo "Cloning repositories from project $PROJECT_KEY..."
for REPO in $REPOS; do
  REPO_NAME=$(basename "$REPO" .git)
  echo "Cloning $REPO_NAME..."
  git clone "$REPO" "$CLONE_DIR/$REPO_NAME"
done

echo "All repositories have been cloned into $CLONE_DIR."

curl -s -u "$USERNAME:$ACCESS_TOKEN" \
  "$BITBUCKET_URL/rest/api/1.0/projects/$PROJECT_KEY/repos?limit=100" > api_response.json

for REPO in $REPOS; do
  echo "Cloning from $REPO"
  REPO_NAME=$(basename "$REPO" .git)
  git clone "$REPO" "$CLONE_DIR/$REPO_NAME"
done


git -c http.sslVerify=false clone https://yourcompany.bitbucket.server/scm/project/repo1.git


Git clone and zip

This is how to clone and zip all sub repositories from bit bucket into a single zip fil

#!/bin/bash

# Configuration
WORKSPACE="your-workspace-name"          # Replace with your Bitbucket workspace name
PROJECT="CHE"                            # Replace with the project or folder name in Bitbucket
BITBUCKET_API="https://api.bitbucket.org/2.0"
ACCESS_TOKEN="your-access-token"         # Replace with your Bitbucket personal access token
DEST_FOLDER="CHE"                        # Destination folder for cloned repositories

# Create destination folder
mkdir -p "$DEST_FOLDER"

# Fetch repositories from Bitbucket
echo "Fetching repositories from Bitbucket workspace '$WORKSPACE', project '$PROJECT'..."
REPO_URLS=$(curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
    "$BITBUCKET_API/repositories/$WORKSPACE?q=project.key=\"$PROJECT\"" | \
    jq -r '.values[] | .links.clone[] | select(.name == "https") | .href')

# Check if any repositories were found
if [ -z "$REPO_URLS" ]; then
    echo "No repositories found for project '$PROJECT' in workspace '$WORKSPACE'."
    exit 1
fi

# Clone each repository
echo "Cloning repositories..."
for REPO_URL in $REPO_URLS; do
    REPO_NAME=$(basename "$REPO_URL" .git)
    echo "Cloning $REPO_NAME..."
    git clone "$REPO_URL" "$DEST_FOLDER/$REPO_NAME"
done

echo "All repositories have been cloned into the '$DEST_FOLDER' folder."

Java Selenium framework to save load times to a CSV file

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class PageLoadTimeToCSV {
    public static void main(String[] args) {
        // Set the path to your WebDriver executable
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        // List of URLs to test
        List<String> urls = Arrays.asList(
                "https://www.example.com",
                "https://www.google.com",
                "https://www.github.com"
        );

        // CSV file path
        String csvFile = "page_load_times.csv";

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();

        try (FileWriter writer = new FileWriter(csvFile)) {
            // Write CSV header
            writer.append("URL,Load Time (ms)\n");

            for (String url : urls) {
                // Start time before page load
                long startTime = System.currentTimeMillis();

                // Navigate to the URL
                driver.get(url);

                // Wait for the page to load completely (customize the wait condition as needed)
                WebDriverWait wait = new WebDriverWait(driver, 30);
                wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("body")));

                // End time after page load
                long endTime = System.currentTimeMillis();

                // Calculate the load time
                long loadTime = endTime - startTime;

                // Write result to CSV
                writer.append(url).append(",").append(String.valueOf(loadTime)).append("\n");

                System.out.println("Page Load Time for " + url + ": " + loadTime + " milliseconds");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the browser
            driver.quit();
        }
    }
}

Java code to work in M365

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class M365WordAutomation {
    public static void main(String[] args) {
        // Set the path to the chromedriver executable
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize a new WebDriver instance
        WebDriver driver = new ChromeDriver();

        // Maximize the browser window
        driver.manage().window().maximize();

        // Set a default implicit wait time
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        try {
            // Navigate to the Microsoft 365 login page
            driver.get("https://www.office.com/");

            // Click on the Sign in button
            WebElement signInButton = driver.findElement(By.linkText("Sign in"));
            signInButton.click();

            // Enter your email and password to log in
            // Note: You will need to replace these selectors and input values with the appropriate ones for your login page
            WebElement emailField = driver.findElement(By.id("i0116"));
            emailField.sendKeys("your-email@example.com");
            WebElement nextButton = driver.findElement(By.id("idSIButton9"));
            nextButton.click();

            // Wait for the password field to be visible and enter the password
            WebElement passwordField = driver.findElement(By.id("i0118"));
            passwordField.sendKeys("your-password");
            WebElement signInButtonPassword = driver.findElement(By.id("idSIButton9"));
            signInButtonPassword.click();

            // If there's a "Stay signed in?" prompt, handle it
            WebElement staySignedInButton = driver.findElement(By.id("idSIButton9"));
            staySignedInButton.click();

            // Navigate to Word
            WebElement wordApp = driver.findElement(By.cssSelector("a[data-task='Word']"));
            wordApp.click();

            // Wait for Word to open and click on 'New blank document'
            WebElement newBlankDocument = driver.findElement(By.cssSelector("div[aria-label='New blank document']"));
            newBlankDocument.click();

            // Switch to the editor frame
            driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Editor']")));

            // Enter some text into the Word document
            WebElement editorBody = driver.findElement(By.xpath("//body[@contenteditable='true']"));
            editorBody.click();
            editorBody.sendKeys("Hello, this is a test.");

        } finally {
            // Close the browser after a short wait
            try {
                Thread.sleep(5000); // Wait for 5 seconds to see the entered text
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            driver.quit();
        }
    }
}

Automation of Word M365

Navigate to the document

public class Microsoft365Automation {
    public static void main(String[] args) throws InterruptedException {
        // Login steps as shown above...

        // Navigate to OneDrive or directly to the document
        driver.get("https://onedrive.live.com/");
        
        // Wait for the page to load
        Thread.sleep(5000);
        
        // Open the specific document (you may need to adjust the selectors)
        WebElement documentLink = driver.findElement(By.linkText("DocumentName.docx"));
        documentLink.click();
        
        // Wait for the document to load
        Thread.sleep(5000);
        
        // Switch to the frame where the document is loaded if necessary
        // This step might be required to interact with the document editor
        // driver.switchTo().frame("officeFrame");

        // Perform the action to write in the document
    }
}

Edit the document using

public class Microsoft365Automation {
    public static void main(String[] args) throws InterruptedException {
        // Previous steps...

        // For example, to type into the Word document:
        WebElement editorBody = driver.findElement(By.cssSelector("div[contenteditable='true']"));
        editorBody.sendKeys("Hello, this is a test text.");
        
        // Or use Actions class to simulate typing
        Actions actions = new Actions(driver);
        actions.moveToElement(editorBody).click().sendKeys("Hello, this is a test text.").perform();
        
        // Add additional interactions as needed
    }
}