gautamp8

PostNewTarget.java

Aug 30th, 2016
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.44 KB | None | 0 0
  1. package VuforiaWeb;
  2.  
  3. import org.apache.commons.codec.binary.Base64;
  4. import org.apache.commons.io.FileUtils;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.ClientProtocolException;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.client.methods.HttpUriRequest;
  10. import org.apache.http.entity.StringEntity;
  11. import org.apache.http.impl.client.DefaultHttpClient;
  12. import org.apache.http.impl.cookie.DateUtils;
  13. import org.apache.http.message.BasicHeader;
  14. import org.apache.http.util.EntityUtils;
  15. import org.json.JSONException;
  16. import org.json.JSONObject;
  17.  
  18. import java.io.*;
  19. import java.net.URI;
  20. import java.net.URISyntaxException;
  21. import java.util.Date;
  22.  
  23. //import com.qualcomm.vuforia.CloudRecognition.utils.SignatureBuilder;
  24.  
  25.  
  26. // See the Vuforia Web Services Developer API Specification - https://developer.vuforia.com/resources/dev-guide/adding-target-cloud-database-api
  27.  
  28. public class PostNewTarget implements TargetStatusListener {
  29.  
  30. //Server Keys
  31. private String accessKey = Keys.accessKey;
  32. private String secretKey = Keys.secretKey;
  33.  
  34. private String url = "https://vws.vuforia.com";
  35. private String targetName = "two";
  36. private String imageLocation = "/home/brainbreaker/2.png";
  37.  
  38. private TargetStatusPoller targetStatusPoller;
  39.  
  40. private final float pollingIntervalMinutes = 60;//poll at 1-hour interval
  41.  
  42. private String postTarget() throws URISyntaxException, ClientProtocolException, IOException, JSONException {
  43. HttpPost postRequest = new HttpPost();
  44. HttpClient client = new DefaultHttpClient();
  45. postRequest.setURI(new URI(url + "/targets"));
  46. JSONObject requestBody = new JSONObject();
  47.  
  48. setRequestBody(requestBody);
  49. postRequest.setEntity(new StringEntity(requestBody.toString()));
  50. setHeaders(postRequest); // Must be done after setting the body
  51.  
  52. HttpResponse response = client.execute(postRequest);
  53. String responseBody = EntityUtils.toString(response.getEntity());
  54. System.out.println(responseBody);
  55.  
  56. JSONObject jobj = new JSONObject(responseBody);
  57.  
  58. String uniqueTargetId = jobj.has("target_id") ? jobj.getString("target_id") : "";
  59. System.out.println("\nCreated target with id: " + uniqueTargetId);
  60.  
  61. return uniqueTargetId;
  62. }
  63.  
  64. private void setRequestBody(JSONObject requestBody) throws IOException, JSONException {
  65. File imageFile = new File(imageLocation);
  66. if(!imageFile.exists()) {
  67. System.out.println("File location does not exist!");
  68. System.exit(1);
  69. }
  70. byte[] image = FileUtils.readFileToByteArray(imageFile);
  71. requestBody.put("name", targetName); // Mandatory
  72. requestBody.put("width", 320.0); // Mandatory
  73. requestBody.put("image", Base64.encodeBase64(image)); // Mandatory
  74. requestBody.put("active_flag", 1); // Optional
  75. requestBody.put("application_metadata", Base64.encodeBase64(readFile())); // Optional
  76. }
  77.  
  78. private byte[] readFile() throws IOException {
  79. String everything = "";
  80. try (BufferedReader br = new BufferedReader(new FileReader("/home/brainbreaker/file.txt"))) {
  81. StringBuilder sb = new StringBuilder();
  82. String line = br.readLine();
  83.  
  84. while (line != null) {
  85. sb.append(line);
  86. sb.append(System.lineSeparator());
  87. line = br.readLine();
  88. }
  89. everything = sb.toString();
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. return everything.getBytes();
  94. }
  95.  
  96. private void setHeaders(HttpUriRequest request) {
  97. SignatureBuilder sb = new SignatureBuilder();
  98. System.out.println("TIME ---> "+ DateUtils.formatDate(new Date()).replaceFirst("[+]00:00$", ""));
  99. request.setHeader(new BasicHeader("Date", DateUtils.formatDate(new Date()).replaceFirst("[+]00:00$", "")));
  100. request.setHeader(new BasicHeader("Content-Type", "application/json"));
  101. request.setHeader("Authorization", "VWS " + accessKey + ":" + sb.tmsSignature(request, secretKey));
  102. }
  103.  
  104. /**
  105. * Posts a new target to the Cloud database;
  106. * then starts a periodic polling until 'status' of created target is reported as 'success'.
  107. */
  108. public void postTargetThenPollStatus() {
  109. String createdTargetId = "";
  110. try {
  111. createdTargetId = postTarget();
  112. } catch (URISyntaxException | IOException | JSONException e) {
  113. e.printStackTrace();
  114. return;
  115. }
  116.  
  117. // Poll the target status until the 'status' is 'success'
  118. // The TargetState will be passed to the OnTargetStatusUpdate callback
  119. if (createdTargetId != null && !createdTargetId.isEmpty()) {
  120. targetStatusPoller = new TargetStatusPoller(pollingIntervalMinutes, createdTargetId, accessKey, secretKey, this );
  121. targetStatusPoller.startPolling();
  122. }
  123. }
  124.  
  125. // Called with each update of the target status received by the TargetStatusPoller
  126. @Override
  127. public void OnTargetStatusUpdate(TargetState target_state) {
  128. if (target_state.hasState) {
  129.  
  130. String status = target_state.getStatus();
  131.  
  132. System.out.println("Target status is: " + (status != null ? status : "unknown"));
  133.  
  134. if (target_state.getActiveFlag() == true && "success".equalsIgnoreCase(status)) {
  135.  
  136. targetStatusPoller.stopPolling();
  137.  
  138. System.out.println("Target is now in 'success' status");
  139. }
  140. }
  141. }
  142.  
  143. public static void post(){
  144. PostNewTarget p = new PostNewTarget();
  145. p.postTargetThenPollStatus();
  146. }
  147. public static void main(String[] args) throws URISyntaxException, ClientProtocolException, IOException, JSONException {
  148. PostNewTarget p = new PostNewTarget();
  149. p.postTargetThenPollStatus();
  150. }
  151.  
  152. }
Add Comment
Please, Sign In to add comment