Java SDK

Prev Next

Classic/VPC 환경에서 이용 가능합니다.

openstack4j 라이브러리를 이용하여 네이버 클라우드 플랫폼[공공기관용] Archive Storage를 사용하는 방법을 설명합니다.

이 문서는 openstack4j 3.1.0 버전을 기준으로 작성되었습니다.

라이브러리를 직접 다운로드 받거나 Apache Maven을 이용하여 사용할 수 있습니다.

라이브러리 다운로드

Apache Maven으로 이용하기

pom.xml

<dependency>
  <groupId>org.pacesys</groupId>
  <artifactId>openstack4j</artifactId>
  <version>3.1.0</version>
</dependency>
Plain text

예제에서 사용하는 user, password는 포탈 마이페이지 > 계정 관리 > 인증키 관리에서 생성한 API 인증키를 사용합니다. (Access Key ID는 user, Secret Key는 password)

projectId와 domainId 정보는 Archive Storage 콘솔에서 이용 신청 후 [API 이용 정보 확인] 버튼을 통해 확인할 수 있습니다.

클라이언트 생성

인증정보를 통해 생성된 토큰 객체로 OS클라이언트를 생성합니다. 클라이언트에서 토큰이 유효하지 않거나 만료되면 자동으로 갱신합니다. 멀티 쓰레드 환경에서 토큰 객체를 공유하여 불필요한 인증 절차를 줄일 수 있습니다.

final String endpoint = "https://kr.archive.gov-ncloudstorage.com:5000/v3";
final String user = "ACCESS_KEY_ID";
final String password = "SECRET_KEY";
final String domainId = "DOMAIN_ID";
final String projectId = "PROJECT_ID";

Token token = OSFactory.builderV3()
    .endpoint(endpoint)
    .credentials(user, password, Identifier.byId(domainId))
    .scopeToProject(Identifier.byId(projectId), Identifier.byId(domainId))
    .authenticate()
    .getToken();

OSClientV3 client = OSFactory.clientFromToken(token);

Java
// Spawn off a thread giving it the access
myThreadExecutor.submit(new MyRunnableOrCallable(token));

// Example of the Runnable or other object invoked in a new thread
public class MyRunnable implements Runnable {
     private OSClientV3 client;

     public MyRunnable(Access access) {
          client = OSFactory.clientFromToken(token);
     }

    public void run() {
        // can now use the client :)
    }
}

Java

모든 오퍼레이션 예제는 위에서 생성한 토큰 객체를 이용합니다.

컨테이너(버킷) 목록 조회

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageContainerService containerService = client.objectStorage().containers();

List<? extends SwiftContainer> containers = containerService.list(ContainerListOptions.create().limit(100));

for (SwiftContainer container : containers) {
    System.out.println(container);
}

Java

컨테이너(버킷) 생성

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageContainerService containerService = client.objectStorage().containers();

String containerName = "sample-container";

// with metadata
// X-Container-Meta-Test-Meta-Key: test-meta-value
Map<String, String> metadata = new HashMap<>();
metadata.put("test-meta-key", "test-meta-value");

ActionResponse response containerService.create(containerName, CreateUpdateContainerOptions.create().metadata(metadata));
System.out.println(response);

Java

컨테이너(버킷) 삭제

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageContainerService containerService = client.objectStorage().containers();

String containerName = "sample-container";

ActionResponse response = containerService.delete(containerName);
System.out.println(response);

Java

오브젝트 업로드

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String objectName = "sample-object.txt";
String contentType = "text/plain";

File file = new File("/tmp/sample-object.txt");

// with metadata
// X-Object-Meta-Test-Meta-Key : test-meta-value
Map<String, String> metadata = new HashMap<>();
metadata.put("test-meta-key", "test-meta-value");

String etag = objectService.put(containerName, objectName, Payloads.create(file),
    ObjectPutOptions.create().contentType(contentType).metadata(metadata));
System.out.println(etag);

Java

디렉토리 오브젝트 생성

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageContainerService containerService = client.objectStorage().containers();

String containerName = "sample-container";
String directoryName = "sample-directory";

String etag = containerService.createPath(containerName, directoryName);
System.out.println(etag);

Java

오브젝트 목록 조회

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String directoryName = "sample-directory";

// simple
List<? extends SwiftObject> objects = objectService.list(containerName);
for (SwiftObject object : objects) {
    System.out.println(object);
}

// list for directory
List<? extends SwiftObject> objectsForDirectory = objectService.list(containerName,
    ObjectListOptions.create().path(directoryName));
for (SwiftObject object : objectsForDirectory) {
    System.out.println(object);
}

Java

오브젝트 다운로드

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String objectName = "sample-object.txt";
String downloadPath = "/tmp/sample-object.txt";

DLPayload payload = objectService.download(containerName, objectName);
File file = new File(downloadPath);
payload.writeToFile(file);

Java

오브젝트 삭제

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String objectName = "sample-object.txt";

ActionResponse response = objectService.delete(containerName, objectName);
System.out.println(response);

Java

대용량 파일 업로드(SLO)

OSClientV3 client = OSFactory.clientFromToken(getToken());
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String objectName = "sample-big-file.mp4";
String contentType = "video/mp4";

String segmentContainerName = "segment-container";
String segmentPrefix = "segments-for-sample-big-file.mp4/segment-";
List<Map<String, Object>> segmentInfoList = new ArrayList<>();

File file = new File("/tmp/sample.mp4");
FileInputStream fs = new FileInputStream(file);

int bufferSize = 1024 * 1024 * 10; // 10MB
byte[] buffer = new byte[bufferSize];

int segmentNo = 1;
int bytesRead;

while ((bytesRead = fs.read(buffer)) != -1) {
    Map<String, Object> segmentInfo = new HashMap<>();
    InputStreamPayload payload = new InputStreamPayload(new ByteArrayInputStream(buffer, 0, bytesRead));
    String etag = objectService.put(segmentContainerName, segmentPrefix + segmentNo, payload);

    segmentInfo.put("path", "/" + segmentContainerName + "/" + segmentPrefix + segmentNo);
    segmentInfo.put("etag", etag);
    segmentInfo.put("size_bytes", bytesRead);
    segmentInfoList.add(segmentInfo);

    segmentNo++;
}
fs.close();

String manifest = new ObjectMapper().writeValueAsString(segmentInfoList);

String etag = objectService.put(containerName, objectName,
    Payloads.create(new ByteArrayInputStream(manifest.getBytes())),
    ObjectPutOptions.create().queryParam("multipart-manifest", "put").contentType(contentType));

System.out.println(etag);

Java

대용량 파일 Segments 조회(SLO)

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String objectName = "sample-big-file.mp4";

ObjectListOptions options = ObjectListOptions.create();
options.getOptions().put("multipart-manifest", "get");

List<? extends SwiftObject> objects = objectService.list(containerName + "/" + objectName, options);
for (SwiftObject object : objects) {
    System.out.println(object);
}

Java

대용량 파일 삭제(SLO)

OSClientV3 client = OSFactory.clientFromToken(token);
ObjectStorageObjectService objectService = client.objectStorage().objects();

String containerName = "sample-container";
String objectName = "sample-big-file.mp4";

ActionResponse response = objectService.delete(ObjectLocation.create(containerName, objectName),
    ObjectDeleteOptions.create().queryParam("multipart-manifest", "delete"));

System.out.println(response);

Java