This repository has been archived on 2025-12-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
tdi-studio-se/main/plugins/org.talend.designer.components.localprovider/components/tBigQuerySQLRow/tBigQuerySQLRow_begin.javajet
2020-02-12 13:36:06 +02:00

185 lines
8.5 KiB
Plaintext

<%@ jet
imports="
org.talend.core.model.process.INode
org.talend.core.model.process.ElementParameterParser
org.talend.designer.codegen.config.CodeGeneratorArgument
java.util.List
"
%>
<%@ include file="@{org.talend.designer.components.localprovider}/components/templates/Log4j/Log4jFileUtil.javajet"%>
<%
CodeGeneratorArgument codeGenArgument = (CodeGeneratorArgument) argument;
INode node = (INode)codeGenArgument.getArgument();
String cid = node.getUniqueName();
String authMode = ElementParameterParser.getValue(node,"__AUTH_MODE__");
String credentialsFile = ElementParameterParser.getValue(node, "__SERVICE_ACCOUNT_CREDENTIALS_FILE__");
String clientId = ElementParameterParser.getValue(node,"__CLIENT_ID__");
String clientSecret = ElementParameterParser.getValue(node,"__CLIENT_SECRET__");
String projectId = ElementParameterParser.getValue(node,"__PROJECT_ID__");
String authorizationCode = ElementParameterParser.getValue(node,"__AUTHORIZATION_CODE__");
String query = ElementParameterParser.getValue(node,"__QUERY__");
boolean useLegacySql = ElementParameterParser.getBooleanValue(node,"__USE_LEGACY_SQL__");
String basePackage = "";
query = query.replaceAll("\n"," ").replaceAll("\r", " ");
String tokenFile = ElementParameterParser.getValue(node,"__TOKEN_NAME__");
boolean isLog4jEnabled = ("true").equals(ElementParameterParser.getValue(node.getProcess(), "__LOG4J_ACTIVATE__"));
if (authMode.equals("OAUTH")) {
String passwordFieldName = "__CLIENT_SECRET__";
%>
<%@ include file="@{org.talend.designer.components.localprovider}/components/templates/password.javajet"%>
final String CLIENT_SECRET_<%=cid%> = "{\"web\": {\"client_id\": \""+<%=clientId%>+"\",\"client_secret\": \"" +decryptedPassword_<%=cid%>+ "\",\"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\"token_uri\": \"https://accounts.google.com/o/oauth2/token\"}}";
final String PROJECT_ID_<%=cid %> = <%=projectId %>;
// Static variables for API scope, callback URI, and HTTP/JSON functions
final List<String> SCOPES_<%=cid%> = java.util.Arrays.asList("https://www.googleapis.com/auth/bigquery");
final String REDIRECT_URI_<%=cid%> = "urn:ietf:wg:oauth:2.0:oob";
final com.google.api.client.http.HttpTransport TRANSPORT_<%=cid %> = new com.google.api.client.http.javanet.NetHttpTransport();
final com.google.api.client.json.JsonFactory JSON_FACTORY_<%=cid %> = new com.google.api.client.json.jackson2.JacksonFactory();
com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets clientSecrets_<%=cid%> = com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.load(
JSON_FACTORY_<%=cid %>, new java.io.InputStreamReader(new java.io.ByteArrayInputStream(
CLIENT_SECRET_<%=cid%>.getBytes())));
com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow flow_<%=cid%> = null;
com.google.api.services.bigquery.Bigquery bigqueryclient_<%=cid%> = null;
long nb_line_<%=cid%> = 0;
<%
if(isLog4jEnabled){
%>
log.info("<%=cid%> - Service Account Scopes [https://www.googleapis.com/auth/bigquery]");
log.info("<%=cid%> - Redirect uris [urn:ietf:wg:oauth:2.0:oob]");
log.info("<%=cid%> - Attempt to load existing refresh token.");
<%
}
%>
// Attempt to load existing refresh token
String tokenFile_<%=cid %> = <%=tokenFile%>;
java.util.Properties properties_<%=cid%> = new java.util.Properties();
try(java.io.FileInputStream inputStream_<%=cid%> = new java.io.FileInputStream(tokenFile_<%=cid %>)) {
properties_<%=cid%>.load(inputStream_<%=cid%>);
} catch (java.io.IOException ee) {
<%
if(isLog4jEnabled){
%>
log.warn("<%=cid%> - "+ee.getMessage());
<%
}
%>
}
String storedRefreshToken_<%=cid%> = (String) properties_<%=cid%>.get("refreshtoken");
// Check to see if the an existing refresh token was loaded.
// If so, create a credential and call refreshToken() to get a new
// access token.
if (storedRefreshToken_<%=cid%> != null) {
// Request a new Access token using the refresh token.
com.google.api.client.googleapis.auth.oauth2.GoogleCredential credential_<%=cid%> = new com.google.api.client.googleapis.auth.oauth2. GoogleCredential.Builder().setTransport(TRANSPORT_<%=cid%>)
.setJsonFactory(JSON_FACTORY_<%=cid%>).setClientSecrets(clientSecrets_<%=cid%>)
.build().setFromTokenResponse(new com.google.api.client.auth.oauth2.TokenResponse().setRefreshToken(storedRefreshToken_<%=cid%>));
credential_<%=cid%>.refreshToken();
<%
if(isLog4jEnabled){
%>
log.info("<%=cid%> - An existing refresh token was loaded.");
<%
}
%>
bigqueryclient_<%=cid%> = new com.google.api.services.bigquery.Bigquery.Builder(new com.google.api.client.http.javanet.NetHttpTransport(),new com.google.api.client.json.jackson2.JacksonFactory(),credential_<%=cid%>).setApplicationName("Talend").build();
} else {
<%
if(isLog4jEnabled){
%>
log.info("<%=cid%> - The refresh token does not exist.");
<%
}
%>
String authorizationCode_<%=cid%> = <%=authorizationCode%>;
if(authorizationCode_<%=cid%> == null || "".equals(authorizationCode_<%=cid%>) || "\"\"".equals(authorizationCode_<%=cid%>)) {
String authorizeUrl_<%=cid%> = new com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl(
clientSecrets_<%=cid%>, REDIRECT_URI_<%=cid%>, SCOPES_<%=cid%>).setState("").build();
<%
if(isLog4jEnabled){
%>
log.warn("<%=cid%> - Paste this URL into a web browser to authorize BigQuery Access:\n"
+ authorizeUrl_<%=cid%>);
<%
} else {
%>
System.out
.println("Paste this URL into a web browser to authorize BigQuery Access:\n"
+ authorizeUrl_<%=cid%>);
<%
}
%>
throw new Exception("Authorization Code error");
} else {
<%
if(isLog4jEnabled){
%>
log.info("<%=cid%> - Exchange the auth code for an access token and refesh token.");
<%
}
%>
// Exchange the auth code for an access token and refesh token
flow_<%=cid%> = new com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow.Builder(new com.google.api.client.http.javanet.NetHttpTransport(),
new com.google.api.client.json.jackson2.JacksonFactory(), clientSecrets_<%=cid%>, SCOPES_<%=cid%>)
.setAccessType("offline").setApprovalPrompt("force")
.build();
com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse response_<%=cid%> = flow_<%=cid%>.newTokenRequest(authorizationCode_<%=cid%>).setRedirectUri(REDIRECT_URI_<%=cid%>).execute();
com.google.api.client.auth.oauth2.Credential credential_<%=cid%> = flow_<%=cid%>.createAndStoreCredential(response_<%=cid%>, null);
<%
if(isLog4jEnabled){
%>
log.info("<%=cid%> - Store the refresh token for future use.");
<%
}
%>
// Store the refresh token for future use.
java.util.Properties storeProperties_<%=cid%> = new java.util.Properties();
storeProperties_<%=cid%>.setProperty("refreshtoken", credential_<%=cid%>.getRefreshToken());
try(java.io.FileOutputStream outputStream_<%=cid%> = new java.io.FileOutputStream(tokenFile_<%=cid %>)) {
storeProperties_<%=cid%>.store(outputStream_<%=cid%>,null);
}
bigqueryclient_<%=cid%> = new com.google.api.services.bigquery.Bigquery.Builder(new com.google.api.client.http.javanet.NetHttpTransport(),new com.google.api.client.json.jackson2.JacksonFactory(),credential_<%=cid%>).build();
}
}
<%
String resultSizeType = ElementParameterParser.getValue(node,"__RESULT_SIZE__");
%>
<%@ include file="@{org.talend.designer.components.localprovider}/components/tBigQueryInput/BigQueryInputQueryHelper.javajet"%>
BigQueryUtil_<%=cid%> bigQueryUtil_<%=cid%> = new BigQueryUtil_<%=cid%>(PROJECT_ID_<%=cid%>, bigqueryclient_<%=cid%>, tokenFile_<%=cid%>);
<%
} else if (authMode.equals("SERVICEACCOUNT")) {
%>
com.google.auth.oauth2.GoogleCredentials credentials_<%=cid%>;
java.io.File credentialsFile_<%=cid%> = new java.io.File(<%=credentialsFile%>);
try(java.io.FileInputStream credentialsStream_<%=cid%> = new java.io.FileInputStream(credentialsFile_<%=cid%>)) {
credentials_<%=cid%> = com.google.auth.oauth2.ServiceAccountCredentials.fromStream(credentialsStream_<%=cid%>);
}
com.google.cloud.bigquery.BigQuery bigquery_<%=cid%> = com.google.cloud.bigquery.BigQueryOptions.newBuilder()
.setCredentials(credentials_<%=cid%>)
.setProjectId(<%=projectId%>)
.build()
.getService();
<%
} else {
throw new IllegalArgumentException("authentication mode should be either \"SERVICEACCOUNT\" or \"OAUTH\", but it is " + authMode);
}
%>