Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ dependencies {
testImplementation 'org.springframework.security:spring-security-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

implementation 'com.google.apis:google-api-services-sheets:v4-rev516-1.23.0'
implementation 'com.google.auth:google-auth-library-oauth2-http:0.20.0'


implementation 'io.jsonwebtoken:jjwt-api:0.12.6'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.6'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.6'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package dmu.dasom.api.domain.google.controller;

import dmu.dasom.api.domain.google.service.GoogleApiService;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/google")
@RequiredArgsConstructor
public class GoogleController {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 컨트롤러 클래스는 어디에 사용되는 건가요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아직 지원자 컨트롤러가 없어서 만들었습니다. 추후 recruit 컨트롤러 만들어지면 그쪽으로 옮길예정입니다.


private final GoogleApiService googleApiService;

private static final String SPREADSHEET_ID = "1Vpu6_2raNvJN_GGg7aGBmzV4cXG1rCoizHl9v7kbG2o";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SPREADSHEET_ID도 .yml로 관리하세요

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확인이여

private static final String RANGE = "A1";

@PostMapping("/write")
public ResponseEntity<String> writeToSheet(@RequestParam String word){
try{
List<List<Object>> values = List.of(Collections.singletonList(word));

googleApiService.writeToSheet(SPREADSHEET_ID, RANGE, values);
return ResponseEntity.ok("Data written successfully to the spreadsheet" + word);
} catch (Exception e){
e.printStackTrace();
return ResponseEntity.internalServerError().body("Failed to write data to the spreadsheet" + e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package dmu.dasom.api.domain.google.service;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Value;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

@Service
public class GoogleApiService {

private static final Logger logger = LoggerFactory.getLogger(GoogleApiService.class);
private static final String APPLICATION_NAME = "Recruit Form";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
@Value("${google.credentials.file.path}")
private String credentialsFilePath;
private Sheets sheetsService;

// 해당 메소드는 sheets의 인스턴스를 얻는데 사용
private Sheets getSheetsService() throws IOException, GeneralSecurityException{
if(sheetsService == null){
GoogleCredentials credentials = GoogleCredentials
.fromStream(new ClassPathResource(credentialsFilePath).getInputStream())
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/spreadsheets"));
sheetsService = new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, new HttpCredentialsAdapter(credentials))
.setApplicationName(APPLICATION_NAME)
.build();
}
return sheetsService;
}

public void writeToSheet(String spreadsheetId, String range, List<List<Object>> values) {
try {
Sheets service = getSheetsService();
ValueRange body = new ValueRange().setValues(values);
UpdateValuesResponse result = service.spreadsheets().values()
.update(spreadsheetId, range, body)
.setValueInputOption("USER_ENTERED")
.execute();
logger.info("Updated rows: {}", result.getUpdatedRows());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logger는 @Slf4j 사용하면 간편할듯요

} catch (IOException e) {
logger.error("Failed to write data to the spreadsheet", e);
throw new RuntimeException("Failed to write data to the spreadsheet: " + e.getMessage(), e);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}

}
3 changes: 3 additions & 0 deletions src/main/resources/application-credentials.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ jwt:
secret: ${JWT_SECRET}
access-token-expiration: ${JWT_ACCESS_TOKEN_EXPIRATION}
refresh-token-expiration: ${JWT_REFRESH_TOKEN_EXPIRATION}
google:
credentials:
path: ${GOOGLE_CREDENTIALS_PATH}