Add/Update Hadoop SQL operation is used to add given Hadoop SQL Query to the database or perform an update operation if the query already exists.
Following code will add/update a Hadoop SQL Query to the database.
java.net.HttpURLConnection is used to create a PUT request to add/update a Hadoop SQL Query to the database. A request property (hadoopsql-properties) is set to Hadoop SQL JSON which will be saved in database.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpStatus;
public class QueryOperations {
/*
* This program will add or update a Hadoop SQL Query to database.
* @param serverURL: URL of s3 server.
* @param token: authorization token.
* @param queryJSON: JSON of the query to be added or updated
*/
public void PUTHadoopSQL(String serverURL, String token, String queryJSON)
throws Exception {
URL url = null;
HttpURLConnection httpCon = null;
InputStream is = null;
try {
/* append "/" at end of serverURL */
if (!serverURL.endsWith("/")) {
serverURL = serverURL + "/";
}
url = new URL(serverURL + "hadoopsql"); //append "hadoopsql" to the serverURL and create a new URL object
//Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true); // to use the URL connection for output
httpCon.setRequestMethod("PUT"); //PUT request is used
httpCon.setRequestProperty("authorization", token); //provides authorization token for authentication
httpCon.setRequestProperty("hadoopsql-properties", queryJSON); //set queryJSON property
httpCon.connect(); //Opens a communications link to the resource reference by the URL
if (httpCon.getResponseCode() == HttpStatus.SC_OK) { //check for OK response
is = httpCon.getInputStream();
// Process response here
}
} finally {
try {
if (is != null)
is.close(); //close stream
} catch (IOException e) {
e.printStackTrace();
}
if (httpCon != null) {
httpCon.disconnect(); //close connection
}
}
}
}