Qiniu Java SDK

repository·master·Indexed 20 days ago

https://github.com/qiniu/java-sdk

A programmatic interface for interacting with Qiniu's cloud services. It provides tools for resource storage (including file uploads via UploadManager and automatic region selection via AutoRegion), IoT Video Cloud device management using LinkingDeviceManager, and QVS Cloud Server-Side operations via NameSpaceManager, StreamManager, DeviceManager, and TemplateManager. Requires JDK 7 or higher.

Tokens
4.9K
Snippets
14
Records
17
Agent score
69%

What's inside qiniu-java-sdk

  1. Install the Qiniu Java SDK

    master

    You can install the Qiniu Java SDK using Maven or Gradle. Ensure your environment meets the requirement of JDK 7 or higher.

    ### Maven
    ```xml
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>qiniu-java-sdk</artifactId>
      <version>[7.19.0, 7.19.99]</version>
    </dependency>

    Gradle

    implementation 'com.qiniu:qiniu-java-sdk:7.19.+'
  2. Run tests and generate Eclipse project files

    master

    If you are contributing to the SDK or working with the source code, you can use the included Gradle wrapper to run tests or generate Eclipse configuration files.

    ### Run Tests
    ```bash
    $ ./gradlew build

    Generate Eclipse Project Files

    $ ./gradlew gen_eclipse
  3. Upload files using UploadManager

    master

    To upload files to Qiniu, use the UploadManager class. You must first authenticate using Auth.create(accessKey, secretKey) to generate an upload token for a specific bucket.

    There are two versions of the resumable upload API available via Configuration:

    1. V1 (Default): Standard resumable upload.
    2. V2: Set cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2 to use the newer version of the resumable upload API.
    // Resumable Upload v2 Example
    import com.qiniu.storage.UploadManager;
    import com.qiniu.util.Auth;
    import com.qiniu.storage.Configuration;
    import com.qiniu.http.Response;
    
    String accessKey = "Your AccessKey";
    String secretKey = "Your SecretKey";
    String bucketName = "upload to bucket";
    
    Configuration cfg = Configuration.create();
    // Enable V2 API
    cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
    
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(accessKey, secretKey);
    String token = auth.uploadToken(bucketName);
    String key = "file save key";
    
    // Perform the upload
    Response r = uploadManager.put("hello world".getBytes(), key, token);
  4. Initialize the QVS Cloud Server-Side Library

    master

    To use the QVS SDK, you must first authenticate using your Qiniu AccessKey and SecretKey. Use the Auth.create method to generate an Auth object, which is then passed to the various manager classes (e.g., NameSpaceManager, StreamManager, DeviceManager, TemplateManager).

    String accessKey = "<QINIU ACCESS KEY>"; // Replace with your Qiniu AccessKey
    String secretKey = "<QINIU SECRET KEY>"; // Replace with your Qiniu SecretKey
    Auth auth = Auth.create(accessKey, secretKey);
    
    // Initialize managers with the auth object
    NameSpaceManager nameSpaceManager = new NameSpaceManager(auth);
    // StreamManager streamManager = new StreamManager(auth);
    // TemplateManager templateManager = new TemplateManager(auth);
  5. Use AutoRegion for automatic region selection

    master

    The AutoRegion class allows the SDK to automatically determine the optimal Qiniu storage region (machine room) for a specific bucket. Instead of manually specifying a fixed region, AutoRegion queries the Qiniu User Center (UC) to find the best upload and download hosts based on your accessKey and bucket name. This ensures low latency and high availability by dynamically resolving hostnames for:

    • Source upload hosts (getSrcUpHost)
    • Accelerated upload hosts (getAccUpHost)
    • Download hosts (getIovipHost, getIoSrcHost)
    • Resource management and list hosts (getRsHost, getRsfHost)
    • API hosts (getApiHost)

    AutoRegion uses an internal cache to avoid redundant network calls to the UC service.

  6. Handle QiniuException for error debugging

    master
    When an API request fails, the SDK throws a QiniuException. This exception preserves the request and response information, which is useful for debugging and troubleshooting issues with Qiniu services.
  7. Manage devices with LinkingDeviceManager

    master

    The LinkingDeviceManager class provides methods to manage IoT devices, including creating, querying, updating, and deleting devices and their access keys (DAK).

    // Create a simple device
    deviceManager.createDevice(appid, deviceName);
    
    // Create a gateway device
    Device device = new Device();
    device.setDeviceName("testName");
    device.setType(1);
    device.setMaxChannel(64);
    deviceManager.createDevice(appid, device);
    
    // Query a specific device
    Device device = deviceManager.getDevice(appid, deviceName);
    
    // Update device information using PatchOperations
    PatchOperation[] operations = {new PatchOperation("replace", "segmentExpireDays", 9)};
    Device updatedDevice = deviceManager.updateDevice(appid, deviceName, operations);
    
    // List devices
    DeviceListing deviceslist = deviceManager.listDevice(appid, prefix, marker, limit, online);
    Device[] devices = deviceslist.items;
    String marker = deviceslist.marker;
  8. Manage QVS Streams

    master

    Streams exist within a namespace. Use StreamManager to manage the lifecycle of a stream, including creation, deletion, and status control (enable/disable/stop). You can also retrieve stream URLs in either static or dynamic modes and query publishing/recording histories.

    // Create a stream
    Stream stream = new Stream("teststream004");
    String namespaceId = "2akrarsj8zp0w";
    streamManager.createStream(namespaceId, stream);
    
    // Get stream URL (Static Mode)
    StaticLiveRoute staticLiveRoute = new StaticLiveRoute("qvs-publish.qtest.com", "publishRtmp", 3600);
    streamManager.staticPublishPlayURL(namespaceId, stream.getStreamID(), staticLiveRoute);
    
    // Get stream URL (Dynamic Mode)
    DynamicLiveRoute dynamicLiveRoute = new DynamicLiveRoute("127.0.0.1", "127.0.0.1", 0);
    streamManager.dynamicPublishPlayURL(namespaceId, stream.getStreamID(), dynamicLiveRoute);
    
    // Stream lifecycle and history
    streamManager.queryStream(namespaceId, stream.getStreamID());
    streamManager.stopStream(namespaceId, stream.getStreamID());
    streamManager.queryStreamPubHistories(namespaceId, stream.getStreamID(), start, end, offset, line);
  9. Manage QVS Recording and Snapshots

    master

    The StreamManager provides interfaces to query recording history, retrieve stream cover images, and fetch lists of snapshots (screenshots) for a specific stream.

    // Query recording history
    streamManager.queryStreamRecordHistories(namespaceId, stream.getStreamID(), start, end, line, maker);
    
    // Get stream cover image
    streamManager.queryStreamCover(namespaceId, stream.getStreamID());
    
    // Get snapshot/screenshot list
    streamManager.streamsSnapshots(namespaceId, stream.getStreamID(), start, end, type, line, maker);
  10. Manage QVS Templates

    master

    Templates define recording and processing rules. Use TemplateManager to create, query, update, list, and delete templates.

    // Create a template
    Template template = new Template();
    template.setName("testtemplate001");
    template.setBucket("Testforhugo");
    template.setTemplateType(1);
    template.setJpgOverwriteStatus(true);
    template.setRecordType(2);
    templateManager.createTemplate(template);
    
    // Update a template
    PatchOperation[] patchOperation = {new PatchOperation("replace", "name","testtemplate002")};
    templateManager.updateTemplate(templateId, patchOperation);
  11. Manage Device Access Keys (DAK)

    master

    You can manage DAKs (Device Access Keys) to control device access and identity. This includes adding, querying, deleting, and moving keys between devices.

    // Add a DAK to a device
    DeviceKey[] keys = deviceManager.addDeviceKey(appid, deviceName);
    
    // Query a device using its DAK
    Device device = deviceManager.getDeviceByAccessKey(dak);
    
    // Get all DAKs for a specific device
    DeviceKey[] keys = deviceManager.queryDeviceKey(appid, deviceName);
    
    // Delete a specific DAK
    deviceManager.deleteDeviceKey(appid, deviceName, dak);
    
    // Move (clone) a DAK from one device to another
    // Parameters: appid, fromDeviceName, toDeviceName, cleanSelfKeys, deleteDevice, dak
    deviceManager.cloneDeviceKey(appid, fromDeviceName, toDeviceName2, true, false, dak);