Rowlogy
Rowlogy

Java

Learn how to interact with the Rowlogy API using Java.

You can interact with the Rowlogy API using Java's built-in networking capabilities or popular third-party HTTP client libraries. This guide provides examples using java.net.HttpURLConnection.

Authentication

API requests must be authenticated using an API key. Include your API key in the Authorization header.

Authorization: Bearer <YOUR_API_KEY>

It's highly recommended to store your API key securely, for example, using environment variables or a configuration file, rather than hardcoding it.

You can obtain your API key from your profile page.

Dependencies

For JSON processing, you might need a library like org.json or Jackson. This example will conceptually use string manipulation for simplicity in request bodies and assume a simple JSON library for parsing responses if needed.

If using Maven, you might add org.json:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version> <!-- Use the latest version -->
</dependency>

Or for Jackson:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest version -->
</dependency>

Examples

These examples demonstrate basic GET and POST requests.

1. Get Project Content

This function retrieves the content of a specific project.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
// For a real application, you'd use a proper JSON library (e.g., org.json.JSONObject or Jackson ObjectMapper)
// import org.json.JSONObject;

public class RowlogyApiClient {

    private static final String ROWLOGY_API_KEY = System.getenv("ROWLOGY_API_KEY"); // Get API key from environment variable
    private static final String API_BASE_URL = "https://rowlogy.com/api"; // Adjust if your API is hosted elsewhere

    public static String getProjectContent(String username, String projectId) throws Exception {
        if (ROWLOGY_API_KEY == null) {
            throw new RuntimeException("ROWLOGY_API_KEY environment variable not set.");
        }

        String urlString = String.format("%s/%s/%s/content", API_BASE_URL, username, projectId);
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Bearer " + ROWLOGY_API_KEY);
        connection.setRequestProperty("Accept", "application/json");

        int responseCode = connection.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // Print result or parse it using a JSON library
            System.out.println("Response: " + response.toString());
            // Example with org.json:
            // JSONObject jsonResponse = new JSONObject(response.toString());
            // System.out.println("Project Title: " + jsonResponse.optString("title", "N/A"));
            return response.toString();
        } else {
            System.out.println("GET request not worked");
            // Read error stream for more details
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String errorLine;
            StringBuilder errorResponse = new StringBuilder();
            while ((errorLine = errorReader.readLine()) != null) {
                errorResponse.append(errorLine);
            }
            errorReader.close();
            System.out.println("Error response: " + errorResponse.toString());
            throw new RuntimeException("Failed : HTTP error code : " + responseCode + " - " + errorResponse.toString());
        }
    }

    public static void main(String[] args) {
        try {
            // Replace with your actual username and project ID
            String username = "your-rowlogy-username";
            String projectId = "your-project-id";
            getProjectContent(username, projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. Update Project Content

This function updates the content of a specific project.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
// import org.json.JSONObject; // For creating JSON body

public class RowlogyApiClient { // Assuming this is part of the same class

    // ROWLOGY_API_KEY and API_BASE_URL defined as in the GET example
    // If this is a separate file, make sure to define them or pass them appropriately.
    private static final String ROWLOGY_API_KEY_POST = System.getenv("ROWLOGY_API_KEY");
    private static final String API_BASE_URL_POST = "https://rowlogy.com/api";

    public static String updateProjectContent(String username, String projectId, String jsonContent) throws Exception {
        if (ROWLOGY_API_KEY_POST == null) { // Using _POST to avoid conflict if in same file and main is run
            throw new RuntimeException("ROWLOGY_API_KEY environment variable not set for POST.");
        }

        String urlString = String.format("%s/%s/%s/content", API_BASE_URL_POST, username, projectId);
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + ROWLOGY_API_KEY_POST);
        connection.setRequestProperty("Content-Type", "application/json; utf-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonContent.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        StringBuilder response = new StringBuilder();
        BufferedReader reader = (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) ?
                                 new BufferedReader(new InputStreamReader(connection.getInputStream())) :
                                 new BufferedReader(new InputStreamReader(connection.getErrorStream()));

        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        System.out.println("Response: " + response.toString());

        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode + " - " + response.toString());
        }
        return response.toString();
    }

    public static void main(String[] args) { // Combined main for testing
        // Ensure ROWLOGY_API_KEY is defined as a static member if getProjectContent is in the same class
        // For this combined main, ensure ROWLOGY_API_KEY and API_BASE_URL are accessible
        // or pass them as parameters. Assuming they are static members of this class for now.

        try {
            String username = "your-rowlogy-username";
            String projectId = "your-project-id";

            // To use the getProjectContent from the first example, it should be in this class
            // or invoked on an instance of its class if it's not static / in a different class.
            // For now, let's assume the first RowlogyApiClient.getProjectContent is available.
            // If you split into two files, the main methods would be separate.

            // System.out.println("--- Testing GET ---");
            // RowlogyApiClient.getProjectContent(username, projectId); // Call assuming it's static from first example

            System.out.println("\n--- Testing POST from second example's main ---");
            // Example JSON content. In a real app, build this with a JSON library or object mapping.
            // String newContentJson = "{\"title\":\"My Java Updated Project\",\"items\":[{\"id\":1,\"name\":\"Java Item\"}]}";
            // Using org.json for robustness (ensure library is in classpath):
            // org.json.JSONObject newContent = new org.json.JSONObject();
            // newContent.put("title", "My Java Updated Project");
            // newContent.put("description", "Updated via Java client");
            // org.json.JSONArray items = new org.json.JSONArray();
            // org.json.JSONObject item1 = new org.json.JSONObject();
            // item1.put("id", "j1");
            // item1.put("name", "First Java Item");
            // items.put(item1);
            // newContent.put("items", items);
            // String newContentJson = newContent.toString();

            // For simplicity here, a raw string. Replace with proper JSON construction.
            String newContentJson = "{\"title\":\"My Java Project (Updated)\", \"description\":\"Content updated using Java.\", \"data\":[{\"id\": \"j1\", \"value\":\"Test from Java\"}]}";

            // Call the updateProjectContent from this second example
            updateProjectContent(username, projectId, newContentJson);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Remember to replace placeholder values and manage your API key securely. For more complex applications, consider using robust HTTP client libraries like Apache HttpClient, OkHttp, or Spring's RestTemplate, which offer more features and flexibility.