Java Code Examples for com.google.api.client.http.HttpRequest#setHeaders()

The following examples show how to use com.google.api.client.http.HttpRequest#setHeaders() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Posts an RDF model to a Solid server. **/
public String postContent(
    String url,
    String slug,
    String type,
    Model model)
    throws IOException {
  StringWriter stringWriter = new StringWriter();
  model.write(stringWriter, "TURTLE");
  HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes());

  HttpRequest postRequest = factory.buildPostRequest(
      new GenericUrl(url), content);
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.set("Link", "<" + type + ">; rel=\"type\"");
  headers.set("Slug", slug);
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(response, 201);
  return response.getHeaders().getLocation();
}
 
Example 2
Source File: MockHttpServerTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests behavior when URL validation is disabled.
 */
@Test
public void testUrlMismatch_verifyDisabled() throws IOException {
  MockResponse mockResponse = new MockResponse("test response");
  mockResponse.setValidateUrlMatches(false);
  HttpRequest request =
      mockHttpServer
          .getHttpTransport()
          .createRequestFactory()
          .buildGetRequest(
              new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url"));
  request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8)));
  HttpHeaders headers = new HttpHeaders();
  headers.set("one", "1");
  headers.set("two", "2");
  request.setHeaders(headers);
  mockHttpServer.setMockResponse(mockResponse);
  HttpResponse response = request.execute();
  ActualResponse actualResponse = mockHttpServer.getLastResponse();
  assertEquals("Incorrect response code", 200, response.getStatusCode());
  assertEquals(
      "Request header 'one' incorrect", "1", actualResponse.getRequestHeader("one").get(0));
  assertEquals(
      "Request header 'two' incorrect", "2", actualResponse.getRequestHeader("two").get(0));
}
 
Example 3
Source File: MastodonHttpUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Posts a new status for the user, initially marked as private.**/
public void postStatus(String content, String idempotencyKey) throws IOException {
  ImmutableMap<String, String> formParams = ImmutableMap.of(
      "status", content,
      // Default everything to private to avoid a privacy incident
      "visibility", "private"
  );
  UrlEncodedContent urlEncodedContent = new UrlEncodedContent(formParams);
  HttpRequest postRequest = TRANSPORT.createRequestFactory()
      .buildPostRequest(
          new GenericUrl(baseUrl + POST_URL),
          urlEncodedContent)
      .setThrowExceptionOnExecuteError(false);
  HttpHeaders headers = new HttpHeaders();
  headers.setAuthorization("Bearer " + accessToken);
  if (!Strings.isNullOrEmpty(idempotencyKey)) {
    // This prevents the same post from being posted twice in the case of network errors
    headers.set("Idempotency-Key", idempotencyKey);
  }
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(postRequest, response, 200);
}
 
Example 4
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private void delete(String url)  {
  HttpHeaders headers = new HttpHeaders();
  headers.setAccept("text/turtle");
  headers.setCookie(authCookie);

  try {
    HttpRequest deleteRequest = factory.buildDeleteRequest(new GenericUrl(url))
        .setThrowExceptionOnExecuteError(false);
    deleteRequest.setHeaders(headers);

    validateResponse(deleteRequest.execute(), 200);
    logger.debug("Deleted: %s", url);
  } catch (IOException e) {
    throw new IllegalStateException("Couldn't delete: " + url, e);
  }
}
 
Example 5
Source File: MastodonHttpUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private String requestRaw(String path) throws IOException {
  HttpRequest getRequest = TRANSPORT.createRequestFactory().buildGetRequest(
      new GenericUrl(baseUrl + path));
  HttpHeaders headers = new HttpHeaders();
  headers.setAuthorization("Bearer " + accessToken);
  getRequest.setHeaders(headers);

  HttpResponse response = getRequest.execute();

  validateResponse(getRequest, response, 200);
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  IOUtils.copy(response.getContent(), byteArrayOutputStream, true);
  return byteArrayOutputStream.toString();
}
 
Example 6
Source File: GoogleVideosInterface.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
<T> T makePostRequest(
    String url, Optional<Map<String, String>> parameters, HttpContent httpContent, Class<T> clazz)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest postRequest =
      requestFactory.buildPostRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)), httpContent);

  // TODO: Figure out why this is necessary for videos but not for photos
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType("application/octet-stream");
  headers.setAuthorization("Bearer " + this.credential.getAccessToken());
  headers.set("X-Goog-Upload-Protocol", "raw");
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  if (clazz.isAssignableFrom(String.class)) {
    return (T) result;
  } else {
    return objectMapper.readValue(result, clazz);
  }
}
 
Example 7
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
public void initMfa() throws IOException {

		// any simple get request can be used to - we just need to get an access token
		// whilst the mfatoken is still valid

		// trying to construct the URL like
		// https://api.enterprise.apigee.com/v1/organizations/apigee-cs/apis/taskservice/
		// success response is ignored
		if (accessToken == null) {
			log.info("initialising MFA");

			GenericUrl url = new GenericUrl(
					format("%s/%s/organizations/%s",
							profile.getHostUrl(),
							profile.getApi_version(),
							profile.getOrg()));

			HttpRequest restRequest = requestFactory.buildGetRequest(url);
			restRequest.setReadTimeout(0);
			HttpHeaders headers = new HttpHeaders();
			headers.setAccept("application/json");
			restRequest.setHeaders(headers);

			try {
				executeAPI(profile, restRequest);
				//ignore response - we just wanted the MFA initialised
				log.info("initialising MFA completed");
			} catch (HttpResponseException e) {
				log.error(e.getMessage());
				//throw error as there is no point in continuing
				throw e;
			}
		}
	}
 
Example 8
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the last revision of a given apiproxy or sharedflow.
 *
 * @param bundle the application bundle to check
 *
 * @return the highest revision number of the deployed bundle regardless of environment
 *
 * @throws IOException exception if something went wrong communicating with the rest endpoint
 */
public Long getLatestRevision(Bundle bundle) throws IOException {

	// trying to construct the URL like
	// https://api.enterprise.apigee.com/v1/organizations/apigee-cs/apis/taskservice/
	// response is like
	// {
	// "name" : "taskservice1",
	// "revision" : [ "1" ]
	// }

	GenericUrl url = new GenericUrl(
			format("%s/%s/organizations/%s/%s/%s/",
					profile.getHostUrl(),
					profile.getApi_version(),
					profile.getOrg(),
					bundle.getType().getPathName(),
					bundle.getName()));

	HttpRequest restRequest = requestFactory.buildGetRequest(url);
	restRequest.setReadTimeout(0);
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	restRequest.setHeaders(headers);

	Long revision = null;

	try {
		HttpResponse response = executeAPI(profile, restRequest);
		AppRevision apprev = response.parseAs(AppRevision.class);
		Collections.sort(apprev.revision, new StringToIntComparator());
		revision = Long.parseLong(apprev.revision.get(0));
		log.info(PrintUtil.formatResponse(response, gson.toJson(apprev)));
	} catch (HttpResponseException e) {
		log.error(e.getMessage());
	}
	return revision;
}
 
Example 9
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 5 votes vote down vote up
public Long deleteBundle(Bundle bundle) throws IOException {
	Long deployedRevision = getDeployedRevision(bundle);

	if (deployedRevision == bundle.getRevision()) { // the same version is the active bundle deactivate first
		deactivateBundle(bundle);
	}

	GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/%s/%s/revisions/%d",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName(),
			bundle.getRevision()));

	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	headers.setContentType("application/octet-stream");
	HttpRequest deleteRestRequest = requestFactory.buildDeleteRequest(url);
	deleteRestRequest.setReadTimeout(0);
	deleteRestRequest.setHeaders(headers);

	HttpResponse response = null;
	response = executeAPI(profile, deleteRestRequest);

	//		String deleteResponse = response.parseAsString();
	AppConfig deleteResponse = response.parseAs(AppConfig.class);
	if (log.isInfoEnabled())
		log.info(PrintUtil.formatResponse(response, gson.toJson(deleteResponse).toString()));
	applyDelay();
	return deleteResponse.getRevision();
}
 
Example 10
Source File: SolidUtilities.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the contents of a URL to produce an RDF model.
 */
public Model getModel(String url) throws IOException {
  HttpRequestFactory factory = TRANSPORT.createRequestFactory();

  HttpRequest rootGetRequest = factory.buildGetRequest(
      new GenericUrl(url));
  HttpHeaders headers = new HttpHeaders();
  headers.setCookie(authCookie);
  headers.setAccept("text/turtle");
  rootGetRequest.setHeaders(headers);

  HttpResponse response = rootGetRequest.execute();
  if (response.getStatusCode() != 200) {
    throw new IOException("Unexpected return code: "
        + response.getStatusCode()
        + "\nMessage:\n"
        + response.getStatusMessage());

  }
  StringWriter writer = new StringWriter();
  IOUtils.copy(response.getContent(), writer, "UTF-8");
  String fixedString = fixProblematicPeriods(writer.toString());
  Model defaultModel = ModelFactory.createDefaultModel();
  return defaultModel.read(
      new StringReader(fixedString),
      url,
      "TURTLE");
}
 
Example 11
Source File: IcannHttpReporter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */
public boolean send(byte[] reportBytes, String reportFilename) throws XmlException, IOException {
  validateReportFilename(reportFilename);
  GenericUrl uploadUrl = new GenericUrl(makeUrl(reportFilename));
  HttpRequest request =
      httpTransport
          .createRequestFactory()
          .buildPutRequest(uploadUrl, new ByteArrayContent(CSV_UTF_8.toString(), reportBytes));

  HttpHeaders headers = request.getHeaders();
  headers.setBasicAuthentication(getTld(reportFilename) + "_ry", password);
  headers.setContentType(CSV_UTF_8.toString());
  request.setHeaders(headers);
  request.setFollowRedirects(false);

  HttpResponse response = null;
  logger.atInfo().log(
      "Sending report to %s with content length %d", uploadUrl, request.getContent().getLength());
  boolean success = true;
  try {
    response = request.execute();
    byte[] content;
    try {
      content = ByteStreams.toByteArray(response.getContent());
    } finally {
      response.getContent().close();
    }
    logger.atInfo().log(
        "Received response code %d with content %s",
        response.getStatusCode(), new String(content, UTF_8));
    XjcIirdeaResult result = parseResult(content);
    if (result.getCode().getValue() != 1000) {
      success = false;
      logger.atWarning().log(
          "PUT rejected, status code %s:\n%s\n%s",
          result.getCode(), result.getMsg(), result.getDescription());
    }
  } finally {
    if (response != null) {
      response.disconnect();
    } else {
      success = false;
      logger.atWarning().log("Received null response from ICANN server at %s", uploadUrl);
    }
  }
  return success;
}
 
Example 12
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a dataset.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, String labelKey, String labelValue) throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
 
Example 13
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a table.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(
    String projectId, String datasetId, String tableId, String labelKey, String labelValue)
    throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Table table = new Table();
  table.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, table);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(
          String.format(urlFormat, projectId, datasetId, tableId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Table responseTable = response.parseAs(Table.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseTable.getLabels().get(labelKey));
}
 
Example 14
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void getConfig(
    String urlPath,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId,
    String version)
    throws IOException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  urlPath = urlPath + devicePath + "/config?local_version=" + version;

  HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(
          new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) {
              request.setParser(new JsonObjectParser(JSON_FACTORY));
            }
          });

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  HttpHeaders heads = new HttpHeaders();

  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  req.setHeaders(heads);
  ExponentialBackOff backoff =
      new ExponentialBackOff.Builder()
          .setInitialIntervalMillis(500)
          .setMaxElapsedTimeMillis(900000)
          .setMaxIntervalMillis(6000)
          .setMultiplier(1.5)
          .setRandomizationFactor(0.5)
          .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
  InputStream in = res.getContent();

  System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8.name())));
}
 
Example 15
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void publishMessage(
    String payload,
    String urlPath,
    String messageType,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId)
    throws IOException, JSONException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  String urlSuffix = "event".equals(messageType) ? "publishEvent" : "setState";

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();

  String encPayload = encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8.name()));

  urlPath = urlPath + devicePath + ":" + urlSuffix;

  final HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(
          new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) {
              request.setParser(new JsonObjectParser(JSON_FACTORY));
            }
          });

  HttpHeaders heads = new HttpHeaders();
  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  // Add post data. The data sent depends on whether we're updating state or publishing events.
  JSONObject data = new JSONObject();
  if ("event".equals(messageType)) {
    data.put("binary_data", encPayload);
  } else {
    JSONObject state = new JSONObject();
    state.put("binary_data", encPayload);
    data.put("state", state);
  }

  ByteArrayContent content =
      new ByteArrayContent(
          "application/json", data.toString().getBytes(StandardCharsets.UTF_8.name()));

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  req.setHeaders(heads);
  req.setContent(content);
  req.setRequestMethod("POST");
  ExponentialBackOff backoff =
      new ExponentialBackOff.Builder()
          .setInitialIntervalMillis(500)
          .setMaxElapsedTimeMillis(900000)
          .setMaxIntervalMillis(6000)
          .setMultiplier(1.5)
          .setRandomizationFactor(0.5)
          .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));

  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
}
 
Example 16
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Import a bundle into the Apigee gateway.
 *
 * @param bundleFile reference to the local bundle file
 * @param bundle     the bundle descriptor to use
 *
 * @return the revision of the uploaded bundle
 *
 * @throws IOException exception if something went wrong communicating with the rest endpoint
 */
public Long uploadBundle(String bundleFile, Bundle bundle) throws IOException {

	FileContent fContent = new FileContent("application/octet-stream",
			new File(bundleFile));
	//testing
	log.debug("URL parameters API Version {}", (profile.getApi_version()));
	log.debug("URL parameters URL {}", (profile.getHostUrl()));
	log.debug("URL parameters Org {}", (profile.getOrg()));
	log.debug("URL parameters App {}", bundle.getName());

	StringBuilder url = new StringBuilder();

	url.append(format("%s/%s/organizations/%s/%s?action=import&name=%s",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName()));

	if (getProfile().isValidate()) {
		url.append("&validate=true");
	}

	HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent);
	restRequest.setReadTimeout(0);
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	restRequest.setHeaders(headers);

	Long result;
	try {
		HttpResponse response = executeAPI(profile, restRequest);
		AppConfig apiResult = response.parseAs(AppConfig.class);
		result = apiResult.getRevision();
		if (log.isInfoEnabled())
			log.info(PrintUtil.formatResponse(response, gson.toJson(apiResult)));
		applyDelay();
	} catch (HttpResponseException e) {
		log.error(e.getMessage(), e);
		throw new IOException(e.getMessage(), e);
	}

	return result;

}
 
Example 17
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Update a revsion of a bunlde with the supplied content.
 *
 * @param bundleFile reference to the local bundle file
 * @param bundle     the bundle descriptor to use
 *
 * @return the revision of the uploaded bundle
 *
 * @throws IOException exception if something went wrong communicating with the rest endpoint
 */
public Long updateBundle(String bundleFile, Bundle bundle) throws IOException {

	FileContent fContent = new FileContent("application/octet-stream",
			new File(bundleFile));
	//System.out.println("\n\n\nFile path: "+ new File(bundleFile).getCanonicalPath().toString());
	log.debug("URL parameters API Version {}", profile.getApi_version());
	log.debug("URL parameters URL {}", profile.getHostUrl());
	log.debug("URL parameters Org {}", profile.getOrg());
	log.debug("URL parameters App {}", bundle.getName());

	StringBuilder url = new StringBuilder();

	url.append(format("%s/%s/organizations/%s/%s/%s/revisions/%d",
			profile.getHostUrl(),
			profile.getApi_version(),
			profile.getOrg(),
			bundle.getType().getPathName(),
			bundle.getName(),
			bundle.getRevision()));

	if (getProfile().isValidate()) {
		url.append("?validate=true");
	}

	HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent);
	restRequest.setReadTimeout(0);
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept("application/json");
	restRequest.setHeaders(headers);
	Long result;
	try {
		HttpResponse response = executeAPI(profile, restRequest);
		AppConfig appconf = response.parseAs(AppConfig.class);
		result = appconf.getRevision();
		if (log.isInfoEnabled())
			log.info(PrintUtil.formatResponse(response, gson.toJson(appconf)));
		applyDelay();
	} catch (HttpResponseException e) {
		log.error(e.getMessage());
		throw new IOException(e.getMessage());
	}

	return result;

}
 
Example 18
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 4 votes vote down vote up
public String activateBundleRevision(Bundle bundle) throws IOException {

		BundleActivationConfig deployment2 = new BundleActivationConfig();

		try {

			HttpHeaders headers = new HttpHeaders();
			headers.setAccept("application/json");

			GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/environments/%s/%s/%s/revisions/%d/deployments",
					profile.getHostUrl(),
					profile.getApi_version(),
					profile.getOrg(),
					profile.getEnvironment(),
					bundle.getType().getPathName(),
					bundle.getName(),
					bundle.getRevision()));

			GenericData data = new GenericData();
			data.set("override", Boolean.valueOf(getProfile().isOverride()).toString());

			//Fix for https://github.com/apigee/apigee-deploy-maven-plugin/issues/18
			if (profile.getDelayOverride() != 0) {
				data.set("delay", profile.getDelayOverride());
			}

			HttpRequest deployRestRequest = requestFactory.buildPostRequest(url, new UrlEncodedContent(data));
			deployRestRequest.setReadTimeout(0);
			deployRestRequest.setHeaders(headers);


			HttpResponse response = null;
			response = executeAPI(profile, deployRestRequest);

			if (getProfile().isOverride()) {
				SeamLessDeploymentStatus deployment3 = response.parseAs(SeamLessDeploymentStatus.class);
				Iterator<BundleActivationConfig> iter = deployment3.environment.iterator();
				while (iter.hasNext()) {
					BundleActivationConfig config = iter.next();
					if (config.environment.equalsIgnoreCase(profile.getEnvironment())) {
						if (!config.state.equalsIgnoreCase("deployed")) {
							log.info("Waiting to assert bundle activation.....");
							Thread.sleep(10);
							Long deployedRevision = getDeployedRevision(bundle);
							if (bundle.getRevision() != null && bundle.getRevision().equals(deployedRevision)) {
								log.info("Deployed revision is: " + bundle.getRevision());
								return "deployed";
							} else
								log.error("Deployment failed to activate");
							throw new MojoExecutionException("Deployment failed: Bundle did not activate within expected time. Please check deployment status manually before trying again");
						} else {
							log.info(PrintUtil.formatResponse(response, gson.toJson(deployment3)));
						}
					}
				}

			}

			deployment2 = response.parseAs(BundleActivationConfig.class);
			if (log.isInfoEnabled()) {
				log.info(PrintUtil.formatResponse(response, gson.toJson(deployment2)));
				log.info("Deployed revision is:{}", deployment2.revision);
			}
			applyDelay();

		} catch (Exception e) {
			log.error(e.getMessage());
			throw new IOException(e);
		}

		return deployment2.state;

	}