Java Rest API 클라이언트의 예
Java 사용을 기반으로 하는 Rest API 클라이언트의 예
이 문서에서는 Rest API를 통해 Codebeamer에 작업 항목 데이터를 삽입할 수 있도록 JAVA로 작성된 Rest Client 예제를 보여줍니다.
프로젝트 및 소스 코드는 ImportWorkItemsDemo-sources.zip에서 다운로드할 수 있습니다.
실행 가능한 응용 프로그램은 importWorkItemsDemoexecuteable.zip에서 다운로드할 수 있습니다.
* 
최소 요구 사항: 지원되는 Java SE 프레임워크 버전입니다.
* 
이 응용 프로그램은 Windows 10에서 구현 및 테스트되었지만 Linux와 호환됩니다.
사용
java -jar importWorkItemsDemo.jar -e [Endpoint] -u [Username] -p [Password] -t [TrackerId] -f [Filename]
-e [Endpoint]: the codeBeamer endpoint server address (eg. https://codebeamer.com/cb)
-u [Username]: login user account name
-p [Password]: login user password
-pr [ProjectId]: Target project id where the application should inject the input data
-tr [TrackerId]: Target tacker id where the application should inject the input data
-f [Filename]: Input file data in csv format


Example:
java -jar importWorkItemsDemo.jar -e https://codebeamer.com/cb -u cbprojectadmin -p cbpass -pr 12 -tr 1234 -f input.csv

CSV 파일의 예
ID
이름
설명
첨부 파일
새 항목의 요약입니다.
새 항목에 대한 설명입니다.
c:/testAttachment.txt
1234
기존 항목 1의 새로운 요약입니다.
기존 항목 1의 새로운 설명입니다.
5432
기존 항목 2의 새로운 요약입니다.
기존 항목 2의 새로운 설명입니다.
c:/testAttachment2.txt
값은 쉼표로 구분해야 합니다.
첫 번째 행에는 머리글이 포함되어 있습니다. 순서를 수정할 수 있습니다.
ID가 설정된 경우 - 응용 프로그램에서 기존 작업 항목을 업데이트합니다.
ID가 설정되지 않은 경우 - 응용 프로그램에서 새 작업 항목을 작성합니다.
첨부 파일이 설정된 경우 - 파일이 작업 항목에 업로드됩니다.
첨부 파일에는 파일의 절대 경로가 포함되어야 합니다.
Rest Client 코드 예제
기본 인터페이스 및 클래스
Codebeamer Service Rest 인터페이스에는 작업 항목을 작성하거나 업데이트하고 첨부 파일을 업로드하는 데 필요한 모든 메소드가 포함되어 있습니다.
/**
* Use this method to obtain item schema.
*
* @param projectId is the id of the project
* @param trackerId is the id of the tracker
* @param config is the necessary data for connection
* @return item schema
* @throws ServiceException
*/
public Map obtainItemSchema(String projectId, String trackerId, RestClientConfig config) throws ServiceException;

/**
* Use this method to create new item.
*
* @param item is the item object
* @param config is the necessary data for connection
* @return response from codeBeamer
* @throws ServiceException
*/
public Map createItem(Map<String, Object> item, RestClientConfig config) throws ServiceException;

/**
* Use this method to obtain schema of an existing item.
*
* @param itemId is the id of the item
* @param config is the necessary data for connection
* @return response from codeBeamer
* @throws ServiceException
*/
public Map getItem(String itemId, RestClientConfig config) throws ServiceException;

/**
* Use this method to update an existing item.
*
* @param item is the item object
* @param config is the necessary data for connection
* @return response from codeBeamer
* @throws ServiceException
*/
public Map updateItem(Map<String, Object> item, RestClientConfig config) throws ServiceException;

/**
* Use this method to upload an attachment.
*
* @param itemId is the id of the item
* @param file is the uploaded file
* @param config is the necessary data for connection
* @returnresponse from codeBeamer
* @throws ServiceException
*/
public Map uploadAttachmentToItem(String itemId, File file, RestClientConfig config) throws ServiceException;
CodebeamerServiceImpl은 일반적인 Rest Client를 사용하여 Codebeamer와 통신합니다.
public Map createItem(Map<String, Object> item, RestClientConfig config) throws ServiceException {
try {
Response<Map> response = RestClient.CLIENT.executePost(
String.format(ITEM_URL_PATTERN, config.getHost()), new StringEntity(mapper.writeValueAsString(item)), config, Map.class);
if (!checkStatusCode(response.getHttpStatus())) {
throw new ServiceException(
String.format("Error occurred when tried to create item, http status: %s, response: %s", response.getHttpStatus(), response.getContent()));
}
return response.getContent();
} catch (Exception ex) {
throw new ServiceException(ex);
}
}
RestClient는 일반적인 Rest Client의 구현입니다. 여기에는 POST, PUT, GET 요청을 보내는 메소드가 포함되어 있습니다.
POST 요청 구현의 예:
/**
* Use this method to send POST request.
*
* @param url is the target url
* @param entity contains the body of the request
* @param config contains the necessary data for connection
* @param clazz is the type of the response
* @return POST request response with http status code
* @throws RestClientException
*/
public <T> Response<T> executePost(String url, HttpEntity entity, RestClientConfig config, Class<T> clazz) throws RestClientException {
Response<T> result = null;
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
response = client.execute(httpPost, createContext(config));
HttpEntity responseEntity = response.getEntity();
String content = IOUtils.toString(entity.getContent());
result = new Response<T>(response.getStatusLine().getStatusCode(), StringUtils.isNotEmpty(content) ? mapper.readValue(responseEntity.getContent(), clazz) : null);
EntityUtils.consume(responseEntity);
return result;
} catch (Exception ex) {
throw new RestClientException(ex);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException ex) {
throw new RestClientException(ex);
}
}
}
CodebeamerService Rest 인터페이스를 사용하는 예
새 항목 작성
1. 새 항목을 작성하려면 먼저 Codebeamer에서 항목 스키마를 가져옵니다. 항목 스키마는 Codebeamer Service 클래스의 obtainItemSchema(String projectId, String trackerId, RestClientConfig config) 메소드를 사용하여 다운로드할 수 있습니다.
2. 이 스키마를 템플릿으로 사용하여 템플릿을 복제해 서버에서 새 항목을 작성할 수 있습니다.
3. 필드가 설정되면 CodebeamerService 클래스의 createItem(Map<String, Object> item, RestClientConfig config) 메소드를 호출합니다.
예:
// set project id and tracker id to download the schema
Map<String, Object> schema = service.obtainItemSchema(
String.valueOf(options.get(Option.PROJECT_ID)),
String.valueOf(options.get(Option.TRACKER_ID)),
config);

// item schema is under the "item" attribute, so get it
Map<String, Object> itemSchema = (Map<String, Object>) schema.get("item");

// clone it to use this schema as template to create new items
Map<String, Object> itemSchemaClone = cloner.deepClone(itemSchema)

// set new field values ...
// for ex.: itemSchemaClone.put("description", "Test description");

// create new item on server
service.createItem(itemSchemaClone, config);
기존 항목 업데이트
1. 무엇보다 항목의 스키마가 필요합니다. Codebeamer Service 클래스의 getItem(String itemId, RestClientConfig config) 메소드를 호출하여 기존 항목 스키마를 값과 함께 가져올 수 있습니다.
응답은 JSON 형식이며 현재 값은 item 속성 아래에서 찾을 수 있습니다. 이 속성에는 이 항목에 대해 이전에 설정된 모든 필드가 포함되어 있습니다.
2. 이제 항목 속성의 필드가 업데이트, 추가 또는 삭제될 수 있습니다(항목에 사용 가능한 필드는 스키마의 유형/등록 정보 속성에서 찾을 수 있음).
3. 필드가 설정되면 Codebeamer Service 클래스의 updateItem(Map<String, Object> item, RestClientConfig config) 메소드를 호출합니다. 그러면 서버에서 항목이 업데이트됩니다.
예:
// obtain existing item schema with field values
Map<String, Object> itemSchema = (Map<String, Object>) service.getItem(record.get(ID_FIELD), config).get("item");


// update field values ...
// for ex.: itemSchema.put("description", "Test description");


//update item on server
service.updateItem(itemSchemaClone, config);
첨부 파일 업로드
파일을 항목에 업로드하려면 Codebeamer Service 클래스의 uploadAttachmentToItem(id, file, config) 메소드를 호출합니다.
service.uploadAttachmentToItem(id, file, config);
CSV 파일 읽기
예제 구현에서는 CSV 파일에서 항목 및 항목 필드 값을 읽습니다.
첫 번째 행은 항목의 필드를 포함하는 머리글이고 다른 행에는 항목 필드 값이 포함되어 있습니다.
여기서는 CSV 기록을 반복하고 항목 스키마에 필드 값을 설정합니다.
항목을 작성, 업데이트하는 코드 조각:
// clone the item schema template and it will be used if this is a new item
Map<String, Object> itemSchemaClone = cloner.deepClone(itemSchema)
if (!newItem) {
// obtain existing item schema with field values, because the ID field is set for this item
itemSchemaClone = (Map<String, Object>) service.getItem(record.get(ID_FIELD), config).get("item");
}
// read field values
for (String field : fields) { // iterate over available fields for items
if (record.isMapped(field)) { // is this field set in CSV file?
// get the field value
String value = record.get(field);
if (StringUtils.isNotEmpty(value)) {
itemSchemaClone.put(field, value); // set new field value in the item
}
}
}

도움이 되셨나요?