Java Code Examples for com.google.api.client.http.HttpResponse#isSuccessStatusCode()

The following examples show how to use com.google.api.client.http.HttpResponse#isSuccessStatusCode() . 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: Policy.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public boolean create(String name, String rules) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("rules", rules);

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example 2
Source File: VaultEndpoint.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected Secret getSecret(String path, String method, HttpContent content) throws VaultException {
  try {
    HttpRequest request = getRequestFactory().buildRequest(
        method,
        new GenericUrl(getConf().getAddress() + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.parseAs(Secret.class);
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example 3
Source File: GitHubRequest.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
@Override
public T execute() throws IOException {
    HttpResponse response = super.executeUnparsed();
    ObjectParser parser = response.getRequest().getParser();
    // This will degrade parsing performance but is an inevitable workaround
    // for the inability to parse JSON arrays.
    String content = response.parseAsString();
    if (response.isSuccessStatusCode()
            && !TextUtils.isEmpty(content)
            && content.charAt(0) == '[') {
        content = TextUtils.concat("{\"", GitHubResponse.KEY_DATA, "\":", content, "}")
                .toString();
    }
    Reader reader = new StringReader(content);
    T parsedResponse = parser.parseAndClose(reader, getResponseClass());

    // parse pagination from Link header
    if (parsedResponse instanceof GitHubResponse) {
        Pagination pagination =
                new Pagination(response.getHeaders().getFirstHeaderStringValue("Link"));
        ((GitHubResponse) parsedResponse).setPagination(pagination);
    }

    return parsedResponse;
}
 
Example 4
Source File: TwitterRequest.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
@Override
public T execute() throws IOException {
    HttpResponse response = super.executeUnparsed();
    ObjectParser parser = response.getRequest().getParser();
    // This will degrade parsing performance but is an inevitable workaround
    // for the inability to parse JSON arrays.
    String content = response.parseAsString();
    if (response.isSuccessStatusCode()
            && !TextUtils.isEmpty(content)
            && content.charAt(0) == '[') {
        content = TextUtils.concat("{\"", TwitterResponse.KEY_DATA, "\":", content, "}")
                .toString();
    }
    Reader reader = new StringReader(content);
    return parser.parseAndClose(reader, getResponseClass());
}
 
Example 5
Source File: NullCredentialInitializer.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(
    HttpRequest httpRequest, HttpResponse httpResponse, boolean supportsRetry)
    throws IOException {
  if (!httpResponse.isSuccessStatusCode() && httpResponse.getStatusCode() == ACCESS_DENIED) {
    throwNullCredentialException();
  }
  return supportsRetry;
}
 
Example 6
Source File: TaskQueueNotificationServlet.java    From abelana with Apache License 2.0 5 votes vote down vote up
@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
    throws IOException {
  HttpTransport httpTransport;
  try {
    Map<Object, Object> params = new HashMap<>();
    params.putAll(req.getParameterMap());
    params.put("task", req.getHeader("X-AppEngine-TaskName"));

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault()
        .createScoped(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"));
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    GenericUrl url = new GenericUrl(ConfigurationConstants.IMAGE_RESIZER_URL);

    HttpRequest request = requestFactory.buildPostRequest(url, new UrlEncodedContent(params));
    credential.initialize(request);

    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      log("Call to the imageresizer failed: " + response.getContent().toString());
      resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
    } else {
      resp.setStatus(response.getStatusCode());
    }

  } catch (GeneralSecurityException | IOException e) {
    log("Http request error: " + e.getMessage());
    resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
  }
}
 
Example 7
Source File: Auth.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public boolean enable(String path, String type, String description) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/auth/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example 8
Source File: Mounts.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public boolean mount(String path, String type, String description, Map<String, String> config) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  if (config != null) {
    data.put("config", config);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/mounts/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
 
Example 9
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the metadata request using the given request method to the server and returns the raw
 * metadata {@link HttpResponse}.
 */
private HttpResponse executeUnparsed(boolean usingHead) throws IOException {
  HttpResponse response;
  if (uploader == null) {
    // normal request (not upload)
    response = buildHttpRequest(usingHead).execute();
  } else {
    // upload request
    GenericUrl httpRequestUrl = buildHttpRequestUrl();
    HttpRequest httpRequest = getAbstractGoogleClient()
        .getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent);
    boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError();

    response = uploader.setInitiationHeaders(requestHeaders)
        .setDisableGZipContent(disableGZipContent).upload(httpRequestUrl);
    response.getRequest().setParser(getAbstractGoogleClient().getObjectParser());
    // process any error
    if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) {
      throw newExceptionOnError(response);
    }
  }
  // process response
  lastResponseHeaders = response.getHeaders();
  lastStatusCode = response.getStatusCode();
  lastStatusMessage = response.getStatusMessage();
  return response;
}
 
Example 10
Source File: TokenResponseException.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link TokenResponseException}.
 *
 * <p>
 * If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be
 * inspected using {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 *
 * @param jsonFactory JSON factory
 * @param response HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) {
  HttpResponseException.Builder builder = new HttpResponseException.Builder(
      response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
  // details
  Preconditions.checkNotNull(jsonFactory);
  TokenErrorResponse details = null;
  String detailString = null;
  String contentType = response.getContentType();
  try {
    if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null
        && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
      details = new JsonObjectParser(jsonFactory).parseAndClose(
          response.getContent(), response.getContentCharset(), TokenErrorResponse.class);
      detailString = details.toPrettyString();
    } else {
      detailString = response.parseAsString();
    }
  } catch (IOException exception) {
    // it would be bad to throw an exception while throwing an exception
    exception.printStackTrace();
  }
  // message
  StringBuilder message = HttpResponseException.computeMessageBuffer(response);
  if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
    message.append(StringUtils.LINE_SEPARATOR).append(detailString);
    builder.setContent(detailString);
  }
  builder.setMessage(message.toString());
  return new TokenResponseException(builder, details);
}
 
Example 11
Source File: SplunkEventWriter.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/**
 * Utility method to flush a batch of requests via {@link HttpEventPublisher}.
 *
 * @param receiver Receiver to write {@link SplunkWriteError}s to
 */
private void flush(
    OutputReceiver<SplunkWriteError> receiver,
    @StateId(BUFFER_STATE_NAME) BagState<SplunkEvent> bufferState,
    @StateId(COUNT_STATE_NAME) ValueState<Long> countState) throws IOException {

  if (!bufferState.isEmpty().read()) {

    HttpResponse response = null;
    List<SplunkEvent> events = Lists.newArrayList(bufferState.read());
    try {
      // Important to close this response to avoid connection leak.
      response = publisher.execute(events);

      if (!response.isSuccessStatusCode()) {
        flushWriteFailures(
            events, response.getStatusMessage(), response.getStatusCode(), receiver);
        logWriteFailures(countState);

      } else {
        LOG.info("Successfully wrote {} events", countState.read());
        SUCCESS_WRITES.inc(countState.read());
      }

    } catch (HttpResponseException e) {
      LOG.error(
          "Error writing to Splunk. StatusCode: {}, content: {}, StatusMessage: {}",
          e.getStatusCode(), e.getContent(), e.getStatusMessage());
      logWriteFailures(countState);

      flushWriteFailures(events, e.getStatusMessage(), e.getStatusCode(), receiver);

    } catch (IOException ioe) {
      LOG.error("Error writing to Splunk: {}", ioe.getMessage());
      logWriteFailures(countState);

      flushWriteFailures(events, ioe.getMessage(), null, receiver);

    } finally {
      // States are cleared regardless of write success or failure since we
      // write failed events to an output PCollection.
      bufferState.clear();
      countState.clear();

      if (response != null) {
        response.disconnect();
      }
    }
  }
}
 
Example 12
Source File: SplunkEventWriter.java    From beam with Apache License 2.0 4 votes vote down vote up
/**
 * Flushes a batch of requests via {@link HttpEventPublisher}.
 *
 * @param receiver Receiver to write {@link SplunkWriteError}s to
 */
private void flush(
    OutputReceiver<SplunkWriteError> receiver,
    BagState<SplunkEvent> bufferState,
    ValueState<Long> countState)
    throws IOException {

  if (!bufferState.isEmpty().read()) {

    HttpResponse response = null;
    List<SplunkEvent> events = Lists.newArrayList(bufferState.read());
    try {
      // Important to close this response to avoid connection leak.
      response = publisher.execute(events);

      if (!response.isSuccessStatusCode()) {
        flushWriteFailures(
            events, response.getStatusMessage(), response.getStatusCode(), receiver);
        logWriteFailures(countState);

      } else {
        LOG.info("Successfully wrote {} events", countState.read());
        SUCCESS_WRITES.inc(countState.read());
      }

    } catch (HttpResponseException e) {
      LOG.error(
          "Error writing to Splunk. StatusCode: {}, content: {}, StatusMessage: {}",
          e.getStatusCode(),
          e.getContent(),
          e.getStatusMessage());
      logWriteFailures(countState);

      flushWriteFailures(events, e.getStatusMessage(), e.getStatusCode(), receiver);

    } catch (IOException ioe) {
      LOG.error("Error writing to Splunk: {}", ioe.getMessage());
      logWriteFailures(countState);

      flushWriteFailures(events, ioe.getMessage(), null, receiver);

    } finally {
      // States are cleared regardless of write success or failure since we
      // write failed events to an output PCollection.
      bufferState.clear();
      countState.clear();

      if (response != null) {
        response.disconnect();
      }
    }
  }
}
 
Example 13
Source File: DicomWebRetrieveInstance.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void dicomWebRetrieveInstance(String dicomStoreName, String dicomWebPath)
    throws IOException {
  // String dicomStoreName =
  //    String.format(
  //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");
  // String dicomWebPath = String.format(DICOMWEB_PATH, "your-study-id", "your-series-id",
  // "your-instance-id");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  // Create request and configure any parameters.
  Instances.RetrieveInstance request =
      client
          .projects()
          .locations()
          .datasets()
          .dicomStores()
          .studies()
          .series()
          .instances()
          .retrieveInstance(dicomStoreName, dicomWebPath);

  // Execute the request and process the results.
  HttpResponse response = request.executeUnparsed();

  String outputPath = "instance.dcm";
  OutputStream outputStream = new FileOutputStream(new File(outputPath));
  try {
    response.download(outputStream);
    System.out.println("DICOM instance written to file " + outputPath);
  } finally {
    outputStream.close();
  }

  if (!response.isSuccessStatusCode()) {
    System.err.print(
        String.format("Exception retrieving DICOM instance: %s\n", response.getStatusMessage()));
    throw new RuntimeException();
  }
}
 
Example 14
Source File: DicomWebRetrieveStudy.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void dicomWebRetrieveStudy(String dicomStoreName, String studyId)
    throws IOException {
  // String dicomStoreName =
  //    String.format(
  //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");
  // String studyId = "your-study-id";

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  // Create request and configure any parameters.
  Studies.RetrieveStudy request =
      client
          .projects()
          .locations()
          .datasets()
          .dicomStores()
          .studies()
          .retrieveStudy(dicomStoreName, "studies/" + studyId);

  // Execute the request and process the results.
  HttpResponse response = request.executeUnparsed();

  // When specifying the output file, use an extension like ".multipart".
  // Then, parse the downloaded multipart file to get each individual
  // DICOM file.
  String outputPath = "study.multipart";
  OutputStream outputStream = new FileOutputStream(new File(outputPath));
  try {
    response.download(outputStream);
    System.out.println("DICOM study written to file " + outputPath);
  } finally {
    outputStream.close();
  }

  if (!response.isSuccessStatusCode()) {
    System.err.print(
        String.format("Exception retrieving DICOM study: %s\n", response.getStatusMessage()));
    throw new RuntimeException();
  }
}
 
Example 15
Source File: DicomWebRetrieveRendered.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void dicomWebRetrieveRendered(String dicomStoreName, String dicomWebPath)
    throws IOException {
  // String dicomStoreName =
  //    String.format(
  //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");
  // String dicomWebPath = String.format(DICOMWEB_PATH, "your-study-id", "your-series-id",
  // "your-instance-id");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  // Create request and configure any parameters.
  Instances.RetrieveRendered request =
      client
          .projects()
          .locations()
          .datasets()
          .dicomStores()
          .studies()
          .series()
          .instances()
          .retrieveRendered(dicomStoreName, dicomWebPath);

  // Execute the request and process the results.
  HttpResponse response = request.executeUnparsed();

  String outputPath = "image.png";
  OutputStream outputStream = new FileOutputStream(new File(outputPath));
  try {
    response.download(outputStream);
    System.out.println("DICOM rendered PNG image written to file " + outputPath);
  } finally {
    outputStream.close();
  }

  if (!response.isSuccessStatusCode()) {
    System.err.print(
        String.format(
            "Exception retrieving DICOM rendered image: %s\n", response.getStatusMessage()));
    throw new RuntimeException();
  }
}
 
Example 16
Source File: GoogleJsonResponseException.java    From google-api-java-client with Apache License 2.0 3 votes vote down vote up
/**
 * Executes an HTTP request using {@link HttpRequest#execute()}, but throws a
 * {@link GoogleJsonResponseException} on error instead of {@link HttpResponseException}.
 *
 * <p>
 * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is
 * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the
 * response stream is properly closed. Example usage:
 * </p>
 *
 * <pre>
   HttpResponse response = GoogleJsonResponseException.execute(jsonFactory, request);
   try {
     // process the HTTP response object
   } finally {
     response.disconnect();
   }
 * </pre>
 *
 * @param jsonFactory JSON factory
 * @param request HTTP request
 * @return HTTP response for an HTTP success code (or error code if
 *         {@link HttpRequest#getThrowExceptionOnExecuteError()})
 * @throws GoogleJsonResponseException for an HTTP error code (only if not
 *         {@link HttpRequest#getThrowExceptionOnExecuteError()})
 * @throws IOException some other kind of I/O exception
 * @since 1.7
 */
public static HttpResponse execute(JsonFactory jsonFactory, HttpRequest request)
    throws GoogleJsonResponseException, IOException {
  Preconditions.checkNotNull(jsonFactory);
  boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError();
  if (originalThrowExceptionOnExecuteError) {
    request.setThrowExceptionOnExecuteError(false);
  }
  HttpResponse response = request.execute();
  request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError);
  if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) {
    return response;
  }
  throw GoogleJsonResponseException.from(jsonFactory, response);
}