반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- GoogleCloudPlatfor
- 마인크래프트서버
- 마인크래프트스크립트
- 마크에러
- 면접을위한CS전공지식노트
- 구글 애널리틱스 api
- 마인크래프트서버설치
- 여성서버
- 마인크래프트
- 마크플러그인
- 공용창고
- 자동트윗봇
- 마인크래프트모딩
- CrashReports
- 마크서버
- Vue.js
- 스크립트
- TickingENtities
- 청년
- 앱 어플리케이션
- 러시안룰렛게임
- 플러그인
- 마크여성서버
- 닉네임변환
- app-release
- Google Analytics api
- 사회초년생
- NativeScript
- 마크모딩
- 1.14.4
Archives
- Today
- Total
일상일지
구글 애널리틱스 api chartjs 적용하기(실전예제) 본문
반응형
https://whoa0987.tistory.com/9
위 글에 이은 내용입니다.
Java로 ga api 통신하기 예제입니다.
jsp에 선언
<canvas id="siteUse"></canvas>
js에 애널리틱스 데이터 가져오는 queryReports함수, 차트를 그리는 drawChart함수
queryReports : function(startDate, endDate, expression, name, label) {
var key = new Array();
var value = new Array();
var param = {
startDate : startDate,
endDate : endDate,
metrics : expression,
dimensions : name
}
$.ajax({
method:'GET',
dataType:'json',
url:_ctx+"컨트롤러 호출",
data:param,
async:false,
success:function(result){
for(var i=0; i<result.length; i++){
key[i]=result[i].dimensions[0];
value[i]=result[i].metrics[0].values[0];
}
},
error:function(error){
}
})
main.drawChart(key,value,label);
},
drawChart : function(key, value, label_name){
for(var i=0; i<key.length; i++){
var year=key[i].substring(0,4);
var month=key[i].substring(4,6);
var date=key[i].substring(6,8);
key[i]=month+'-'+date;
}
/*차트*/
var ctx = document.getElementById('siteUse').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: key,
datasets: [{
label : label_name,
data: value,
backgroundColor: [
'rgba(255, 255, 255, 0)'
],
borderColor: [
'rgba(244, 121, 42, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
}]
}
}
});
},
컨트롤러에서 호출된 HelloAnalytics 클래스
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.google.api.services.analyticsreporting.v4.AnalyticsReportingScopes;
import com.google.api.services.analytics.model.FilterExpression;
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting;
import com.google.api.services.analyticsreporting.v4.model.ColumnHeader;
import com.google.api.services.analyticsreporting.v4.model.DateRange;
import com.google.api.services.analyticsreporting.v4.model.DateRangeValues;
import com.google.api.services.analyticsreporting.v4.model.GetReportsRequest;
import com.google.api.services.analyticsreporting.v4.model.GetReportsResponse;
import com.google.api.services.analyticsreporting.v4.model.Metric;
import com.google.api.services.analyticsreporting.v4.model.Dimension;
import com.google.api.services.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.api.services.analyticsreporting.v4.model.OrderBy;
import com.google.api.services.analyticsreporting.v4.model.Report;
import com.google.api.services.analyticsreporting.v4.model.ReportRequest;
import com.google.api.services.analyticsreporting.v4.model.ReportRow;
public class HelloAnalytics {
private static final String APPLICATION_NAME = "Hello Analytics Reporting";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
static String path = HelloAnalytics.class.getResource("").getPath();
private static final String KEY_FILE_LOCATION = "json 키 파일 경로";
private static final String VIEW_ID = "view아이디";
public static List<ReportRow> main(Map<String, Object> params) {
List<ReportRow> rows = null;
try {
//인증
AnalyticsReporting service = initializeAnalyticsReporting();
//매트릭스 디멘션 등등 적용
GetReportsResponse response = getReport(service,params);
//결과값
rows = printResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
//가져온 결과값을 컨트롤러로 리턴
return rows;
}
/**
* Initializes an Analytics Reporting API V4 service object.
*
* @return An authorized Analytics Reporting API V4 service object.
* @throws IOException
* @throws GeneralSecurityException
*/
private static AnalyticsReporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = null;
try{
credential = GoogleCredential
.fromStream(new FileInputStream(KEY_FILE_LOCATION))
.createScoped(AnalyticsReportingScopes.all());
}catch(IOException e){
System.out.println(e);
}finally {
}
// Construct the Analytics Reporting service object.
return new AnalyticsReporting.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
/**
* Queries the Analytics Reporting API V4.
*
* @param service An authorized Analytics Reporting API V4 service object.
* @return GetReportResponse The Analytics Reporting API V4 response.
* @throws IOException
*/
@SuppressWarnings("null")
private static GetReportsResponse getReport(AnalyticsReporting service, Map<String, Object> params) throws IOException {
// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate((String) params.get("startDate"));
dateRange.setEndDate((String) params.get("endDate"));
// Create the Metrics object.
Metric sessions = new Metric()
.setExpression((String) params.get("metrics"));
Dimension pageTitle = new Dimension().setName((String) params.get("dimensions"));
List<OrderBy> orderBys= null;
if(params.get("fieldName")!=null) {
orderBys= new ArrayList<>();
OrderBy orderBy= new OrderBy().setFieldName((String) params.get("fieldName")).setSortOrder((String) params.get("sortOrder")).setOrderType((String)params.get("orderType"));
orderBys.add(orderBy);
}
// Create the ReportRequest object.
ReportRequest request = new ReportRequest()
.setViewId(VIEW_ID)
.setDateRanges(Arrays.asList(dateRange))
.setMetrics(Arrays.asList(sessions))
.setDimensions(Arrays.asList(pageTitle))
.setFiltersExpression((String) params.get("filter"))
.setIncludeEmptyRows(true)
.setOrderBys(orderBys);
ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest()
.setReportRequests(requests);
// Call the batchGet method.
GetReportsResponse response = service.reports().batchGet(getReport).execute();
// Return the response.
return response;
}
/**
* Parses and prints the Analytics Reporting API V4 response.
*
* @param response An Analytics Reporting API V4 response.
* @return
*/
private static List<ReportRow> printResponse(GetReportsResponse response) {
for (Report report: response.getReports()) {
List<ReportRow> rows = report.getData().getRows();
return rows;
}
return null;
}
}
결과
잘나온다.
반응형
'개발' 카테고리의 다른 글
[log4j2] 특정 sql 쿼리 로그 filter 사용하여 제외하기 (0) | 2021.01.21 |
---|---|
[JBoss EAP 7.2] 소스 내 properties 대신 서버 JAVA_OPTS 환경변수 사용하는 법 (0) | 2021.01.05 |
EgovFrameWork 3.8에 JBoss 7.2 돌아가게 하기 (0) | 2020.09.17 |
tr태그에 링크 달기 (0) | 2020.07.30 |
구글 애널리틱스 api(Google Analytics api, ga api) 연동해서 별도의 로그인 없이 그래프 만들기 (10) | 2020.07.18 |
Comments