javax.ws.rs.core.Response.Status.Family Java Examples

The following examples show how to use javax.ws.rs.core.Response.Status.Family. 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: ManagementWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Loads an application template from a directory located on the DM's file system.
 * @param localFilePath the file path of a directory containing the application on the DM's machine
 * @throws ManagementWsException if a problem occurred with the applications management
 */
public void loadUnzippedApplicationTemplate( String localFilePath ) throws ManagementWsException {
	this.logger.finer( "Loading an application from a local directory: " + localFilePath );

	WebResource path = this.resource.path( UrlConstants.APPLICATIONS ).path( "templates" ).path( "local" );
	if( localFilePath != null )
		path = path.queryParam( "local-file-path", localFilePath );

	ClientResponse response = this.wsClient.createBuilder( path )
					.type( MediaType.APPLICATION_JSON )
					.post( ClientResponse.class );

	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new ManagementWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
}
 
Example #2
Source File: Foo.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
public FooResponse<Void> get(FooGETQueryParam queryParameters, FooGETHeader headers) {
    WebTarget target = this._client.target(getBaseUri());
    if (queryParameters.getQ()!= null) {
        target = target.queryParam("q", queryParameters.getQ());
    }
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    if (headers.getId()!= null) {
        invocationBuilder.header("id", headers.getId());
    }
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new FooException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    FooResponse<Void> apiResponse = new FooResponse<Void>(null, response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #3
Source File: ManagementWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a ZIP file and loads its application template.
 * @param applicationFile a ZIP archive file
 * @throws ManagementWsException if a problem occurred with the applications management
 * @throws IOException if the file was not found or is invalid
 */
public void uploadZippedApplicationTemplate( File applicationFile ) throws ManagementWsException, IOException {

	if( applicationFile == null
			|| ! applicationFile.exists()
			|| ! applicationFile.isFile())
		throw new IOException( "Expected an existing file as parameter." );

	this.logger.finer( "Loading an application from " + applicationFile.getAbsolutePath() + "..." );

	FormDataMultiPart part = new FormDataMultiPart();
	part.bodyPart( new FileDataBodyPart( "file", applicationFile, MediaType.APPLICATION_OCTET_STREAM_TYPE));

	WebResource path = this.resource.path( UrlConstants.APPLICATIONS ).path( "templates" );
	ClientResponse response = this.wsClient.createBuilder( path )
			.type( MediaType.MULTIPART_FORM_DATA_TYPE )
			.post( ClientResponse.class, part );

	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new ManagementWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
}
 
Example #4
Source File: DebugWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the DM is correctly connected with the messaging server.
 * @param message a customized message content
 * @return the content of the response
 */
public String checkMessagingConnectionForTheDm( String message )
throws DebugWsException {

	this.logger.finer( "Checking messaging connection with the DM: message=" + message );

	WebResource path = this.resource.path( UrlConstants.DEBUG ).path( "check-dm" );
	if( message != null )
		path = path.queryParam( "message", message );

	ClientResponse response = this.wsClient.createBuilder( path ).get( ClientResponse.class );
	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new DebugWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
	return response.getEntity( String.class );
}
 
Example #5
Source File: ImageCatalogProviderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpImageCatalogValid() throws CloudbreakImageCatalogException, IOException {
    String path = getPath(CB_IMAGE_CATALOG_VALID_JSON);
    String catalogUrl = "http";

    when(clientMock.target(catalogUrl)).thenReturn(webTargetMock);
    when(webTargetMock.request()).thenReturn(builderMock);
    when(builderMock.get()).thenReturn(responseMock);
    when(responseMock.getStatusInfo()).thenReturn(statusTypeMock);
    when(statusTypeMock.getFamily()).thenReturn(Family.SUCCESSFUL);
    when(responseMock.readEntity(String.class)).thenReturn(FileUtils.readFileToString(Paths.get(path, CB_IMAGE_CATALOG_V2_JSON).toFile()));

    ReflectionTestUtils.setField(underTest, "etcConfigDir", path);
    ReflectionTestUtils.setField(underTest, "enabledLinuxTypes", Collections.emptyList());

    CloudbreakImageCatalogV3 actualCatalog = underTest.getImageCatalogV3(catalogUrl);

    CloudbreakImageCatalogV3 expectedCatalog = objectMapper.readValue(Paths.get(path, CB_IMAGE_CATALOG_V2_JSON).toFile(), CloudbreakImageCatalogV3.class);

    assertEquals(mapToUuid(expectedCatalog.getImages().getBaseImages()), mapToUuid(actualCatalog.getImages().getBaseImages()));
    assertEquals(mapToUuid(expectedCatalog.getImages().getHdpImages()), mapToUuid(actualCatalog.getImages().getHdpImages()));
    assertEquals(mapToUuid(expectedCatalog.getImages().getHdfImages()), mapToUuid(actualCatalog.getImages().getHdfImages()));
    assertEquals(mapToUuid(expectedCatalog.getImages().getCdhImages()), mapToUuid(actualCatalog.getImages().getCdhImages()));

}
 
Example #6
Source File: ImageCatalogProviderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test(expected = CloudbreakImageCatalogException.class)
public void testHttpImageCatalogNotValidJson() throws CloudbreakImageCatalogException {
    String path = getPath(CB_IMAGE_CATALOG_VALID_JSON);
    String catalogUrl = "http";

    when(clientMock.target(catalogUrl)).thenReturn(webTargetMock);
    when(webTargetMock.request()).thenReturn(builderMock);
    when(builderMock.get()).thenReturn(responseMock);
    when(responseMock.getStatusInfo()).thenReturn(statusTypeMock);
    when(statusTypeMock.getFamily()).thenReturn(Family.SUCCESSFUL);
    when(responseMock.readEntity(String.class)).thenReturn("image catalog");

    ReflectionTestUtils.setField(underTest, "etcConfigDir", path);
    ReflectionTestUtils.setField(underTest, "enabledLinuxTypes", Collections.emptyList());

    underTest.getImageCatalogV3(catalogUrl);
}
 
Example #7
Source File: ResponseImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Response.StatusType createStatusType(int statusCode, String reasonPhrase) {
    return new Response.StatusType() {

        public Family getFamily() {
            return Response.Status.Family.familyOf(statusCode);
        }

        public String getReasonPhrase() {
            if (reasonPhrase != null) {
                return reasonPhrase;
            }
            Response.Status statusEnum = Response.Status.fromStatusCode(statusCode);
            return statusEnum != null ? statusEnum.getReasonPhrase() : "";
        }

        public int getStatusCode() {
            return statusCode;
        }

    };
}
 
Example #8
Source File: SnomedClientRest.java    From SNOMED-in-5-minutes with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the concept for the specified concept id.
 *
 * @param conceptId the concept id
 * @return the concept for id
 * @throws Exception the exception
 */
public Concept findByConceptId(String conceptId) throws Exception {
  Logger.getLogger(getClass()).debug(
      "Snomed Client - find concept by concept id " + conceptId);

  validateNotEmpty(conceptId, "conceptId");

  final Client client = ClientBuilder.newClient();
  final WebTarget target = client.target(getUrl() + "/concepts/" + conceptId);
  final Response response = target.request(MediaType.APPLICATION_JSON).get();
  final String resultString = response.readEntity(String.class);
  if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    // n/a
  } else {
    throw new Exception(response.toString());
  }

  // converting to object
  return Utility.getGraphForJson(resultString, Concept.class);
}
 
Example #9
Source File: SnomedClientRest.java    From SNOMED-in-5-minutes with Apache License 2.0 6 votes vote down vote up
/**
 * Returns description matches for the specified description id.
 *
 * @param descriptionId the description id
 * @return the matches for description id
 * @throws Exception the exception
 */
public MatchResults findByDescriptionId(String descriptionId)
  throws Exception {
  Logger.getLogger(getClass()).debug(
      "Snomed Client - find description matches by description id "
          + descriptionId);

  validateNotEmpty(descriptionId, "descriptionId");

  final Client client = ClientBuilder.newClient();
  final WebTarget target =
      client.target(getUrl() + "/descriptions/" + descriptionId);
  final Response response = target.request(MediaType.APPLICATION_JSON).get();
  final String resultString = response.readEntity(String.class);
  if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    // n/a
  } else {
    throw new Exception(response.toString());
  }

  // converting to object
  return Utility.getGraphForJson(resultString, MatchResults.class);
}
 
Example #10
Source File: Exec.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
public DataWeaveAPIResponse<Void> post(ExecPOSTBody body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    FormDataMultiPart multiPart = new FormDataMultiPart();
    if (body.getFile()!= null) {
        multiPart.bodyPart(new FileDataBodyPart("file", body.getFile()));
    }
    if (body.getFrom()!= null) {
        multiPart.field("From", body.getFrom().toString());
    }
    Response response = invocationBuilder.post(Entity.entity(multiPart, multiPart.getMediaType()));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new DataWeaveAPIException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    DataWeaveAPIResponse<Void> apiResponse = new DataWeaveAPIResponse<Void>(null, response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #11
Source File: DebugWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Runs a diagnostic for a given instance.
 * @return the instance
 * @throws DebugWsException
 */
public Diagnostic diagnoseInstance( String applicationName, String instancePath )
throws DebugWsException {

	this.logger.finer( "Diagnosing instance " + instancePath + " in application " + applicationName );

	WebResource path = this.resource.path( UrlConstants.DEBUG ).path( "diagnose-instance" );
	path = path.queryParam( "application-name", applicationName );
	path = path.queryParam( "instance-path", instancePath );

	ClientResponse response = this.wsClient.createBuilder( path )
					.accept( MediaType.APPLICATION_JSON )
					.get( ClientResponse.class );

	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new DebugWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
	return response.getEntity( Diagnostic.class );
}
 
Example #12
Source File: CustomStatus.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private static Response.StatusType buildStatusType(final int code, final String reasonPhrase, final Status.Family family) {
    return new Response.StatusType() {
        
        @Override
        public int getStatusCode() {
            return code;
        }
        
        @Override
        public String getReasonPhrase() {
            return reasonPhrase;
        }
        
        @Override
        public Family getFamily() {
            return family;
        }
    };
}
 
Example #13
Source File: VertxRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Try to determine response by status code, and send response.
 */
private void sendFailureRespDeterminedByStatus(RoutingContext context) {
  Family statusFamily = Family.familyOf(context.statusCode());
  if (Family.CLIENT_ERROR.equals(statusFamily) || Family.SERVER_ERROR.equals(statusFamily) || Family.OTHER
      .equals(statusFamily)) {
    context.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD)
        .setStatusCode(context.statusCode()).end();
  } else {
    // it seems the status code is not set properly
    context.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD)
        .setStatusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .setStatusMessage(Status.INTERNAL_SERVER_ERROR.getReasonPhrase())
        .end(wrapResponseBody(Status.INTERNAL_SERVER_ERROR.getReasonPhrase()));
  }
  context.response().close();
}
 
Example #14
Source File: DebugWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the DM can correctly exchange with an agent through the messaging server.
 *
 * @param applicationName  the name of the application holding the targeted agent
 * @param scopedInstancePath the identifier of the targeted agent
 * @param message          a customized message content
 * @return the response to the agent connection check
 */
public String checkMessagingConnectionWithAgent( String applicationName, String scopedInstancePath, String message )
throws DebugWsException {

	this.logger.finer( "Checking messaging connection with agent: applicationName=" + applicationName +
			", scoped instance path=" + scopedInstancePath + ", message=" + message );

	WebResource path = this.resource.path( UrlConstants.DEBUG ).path( "check-agent" );
	path = path.queryParam( "application-name", applicationName );
	path = path.queryParam( "scoped-instance-path", scopedInstancePath );
	if( message != null )
		path = path.queryParam( "message", message );

	ClientResponse response = this.wsClient.createBuilder( path ).get( ClientResponse.class );
	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new DebugWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
	return response.getEntity( String.class );
}
 
Example #15
Source File: FileName.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Creates or updates the given file
 * 
 */
public SimpleApiResponse<Void> put(Object body, FileNamePUTHeader headers) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    if (headers.getXBaseCommitId()!= null) {
        invocationBuilder.header("x-base-commit-id", headers.getXBaseCommitId());
    }
    if (headers.getXCommitMessage()!= null) {
        invocationBuilder.header("x-commit-message", headers.getXCommitMessage());
    }
    Response response = invocationBuilder.put(Entity.entity(body, "*/*"));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new SimpleApiException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    SimpleApiResponse<Void> apiResponse = new SimpleApiResponse<Void>(null, response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #16
Source File: Exec.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
public void post(ExecPOSTBody body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    FormDataMultiPart multiPart = new FormDataMultiPart();
    if (body.getFile()!= null) {
        multiPart.bodyPart(new FileDataBodyPart("file", body.getFile()));
    }
    if (body.getFrom()!= null) {
        multiPart.field("From", body.getFrom().toString());
    }
    Response response = invocationBuilder.post(Entity.entity(multiPart, multiPart.getMediaType()));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new DataWeaveAPIException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
}
 
Example #17
Source File: ImageCatalogValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    LOGGER.info("Image Catalog validation was called: {}", value);
    try {
        if (value == null || !HTTP_CONTENT_SIZE_VALIDATOR.isValid(value, context)) {
            return false;
        }
        Pair<StatusType, String> content = HTTP_HELPER.getContent(value);
        if (content.getKey().getFamily().equals(Family.SUCCESSFUL)) {
            return imageCatalogParsable(context, content.getValue());
        }
        String msg = String.format(FAILED_TO_GET_BY_FAMILY_TYPE, value, content.getKey().getReasonPhrase());
        context.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
    } catch (Throwable throwable) {
        context.buildConstraintViolationWithTemplate(String.format(FAILED_TO_GET_WITH_EXCEPTION, value)).addConstraintViolation();
        LOGGER.debug("Failed to validate the specified image catalog URL: " + value, throwable);
    }
    return false;
}
 
Example #18
Source File: ImageCatalogV4BaseTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testContentNotAvailable() {
    String url = "http://protocol.com";
    String reasonPhrase = "Invalid reason phrase";
    when(statusType.getFamily()).thenReturn(Family.OTHER);
    when(statusType.getReasonPhrase()).thenReturn(reasonPhrase);
    when(httpHelper.getContent(anyString())).thenReturn(new ImmutablePair<>(statusType, ""));

    ImageCatalogV4Base i = new ImageCatalogV4Base();
    i.setName("testname");
    i.setUrl(url);

    Set<ConstraintViolation<ImageCatalogV4Base>> violations = validator.validate(i);

    assertEquals(2L, violations.size());
    String failedToGetMessage = String.format(FAILED_TO_GET_BY_FAMILY_TYPE, url, reasonPhrase);
    assertTrue(violations.stream().allMatch(cv -> cv.getMessage().equals(INVALID_MESSAGE) || cv.getMessage().equals(failedToGetMessage)));
}
 
Example #19
Source File: HttpContentSizeValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    LOGGER.info("content size validation was called. Value: {}", value);
    if (value == null) {
        return true;
    } else if (!value.startsWith("http")) {
        context.buildConstraintViolationWithTemplate(INVALID_URL_MSG).addConstraintViolation();
        return false;
    }
    try {
        Pair<StatusType, Integer> contentLength = httpHelper.getContentLength(value);
        if (!contentLength.getKey().getFamily().equals(Family.SUCCESSFUL)) {
            String msg = String.format(FAILED_TO_GET_BY_FAMILY_TYPE, value, contentLength.getKey().getReasonPhrase());
            context.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
            return false;
        }
        return contentLength.getValue() > 0 && contentLength.getValue() <= MAX_IN_BYTES;
    } catch (Throwable throwable) {
        LOGGER.info("content size validation failed.", throwable);
        context.buildConstraintViolationWithTemplate(FAILED_TO_GET_WITH_EXCEPTION).addConstraintViolation();
    }
    return false;
}
 
Example #20
Source File: Provider.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns combined provider details
 * 
 */
public CoreServicesAPIReferenceResponse<library.resource.provider.model.ProviderGETResponseBody> get() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new CoreServicesAPIReferenceException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    CoreServicesAPIReferenceResponse<library.resource.provider.model.ProviderGETResponseBody> apiResponse = new CoreServicesAPIReferenceResponse<library.resource.provider.model.ProviderGETResponseBody>(response.readEntity(library.resource.provider.model.ProviderGETResponseBody.class), response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #21
Source File: Myapi.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
/**
 * some description.
 * 
 */
public TResponse<Object> put(Object body, MyapiPUTQueryParam queryParameters) {
    WebTarget target = this._client.target(getBaseUri());
    if (queryParameters.getSomeName()!= null) {
        target = target.queryParam("someName", queryParameters.getSomeName());
    }
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.put(Entity.entity(body, "application/xml"));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new TException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    TResponse<Object> apiResponse = new TResponse<Object>(response.readEntity(Object.class), response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #22
Source File: AzureRoleManager.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(value = InteractiveLoginException.class, maxAttempts = 15, backoff = @Backoff(delay = 1000))
public void assignRole(String accessToken, String subscriptionId, String roleDefinitionId, String principalObjectId) throws InteractiveLoginException {
    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target(AZURE_MANAGEMENT);
    Builder request = resource.path("subscriptions/" + subscriptionId + "/providers/Microsoft.Authorization/roleAssignments/"
            + UUID.randomUUID()).queryParam("api-version", "2015-07-01").request();
    request.accept(MediaType.APPLICATION_JSON);

    request.header("Authorization", "Bearer " + accessToken);

    JsonObject properties = new JsonObject();
    properties.addProperty("roleDefinitionId", roleDefinitionId);
    properties.addProperty("principalId", principalObjectId);

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("properties", properties);

    try (Response response = request.put(Entity.entity(jsonObject.toString(), MediaType.APPLICATION_JSON))) {
        if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
            String errorResponse = response.readEntity(String.class);
            LOGGER.info("Assign role request error - status code: {} - error message: {}", response.getStatus(), errorResponse);
            if (response.getStatusInfo().getStatusCode() == Status.FORBIDDEN.getStatusCode()) {
                throw new InteractiveLoginException("You don't have enough permissions to assign roles, please contact with your administrator");
            } else {
                try {
                    String errorMessage = new ObjectMapper().readTree(errorResponse).get("error").get("message").asText();
                    throw new InteractiveLoginException("Failed to assing role: " + errorMessage);
                } catch (IOException e) {
                    throw new InteractiveLoginException("Failed to assing role (status " + response.getStatus() + "): " + errorResponse);
                }
            }
        } else {
            LOGGER.debug("Role assigned successfully. subscriptionId '{}', roleDefinitionId {}, principalObjectId {}",
                    subscriptionId, roleDefinitionId, principalObjectId);
        }
    }
}
 
Example #23
Source File: Id.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public BuyosExperienceLayerResponse<securedby_with_uses.resource.users.id.model.IdGETResponseBody> get() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new BuyosExperienceLayerException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    BuyosExperienceLayerResponse<securedby_with_uses.resource.users.id.model.IdGETResponseBody> apiResponse = new BuyosExperienceLayerResponse<securedby_with_uses.resource.users.id.model.IdGETResponseBody>(response.readEntity(securedby_with_uses.resource.users.id.model.IdGETResponseBody.class), response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #24
Source File: Login.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public List<AuthorizationJson> post() {
        WebTarget target = this._client.target(getBaseUri());
        final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
        Response response = invocationBuilder.post(null);
        if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
            Response.StatusType statusInfo = response.getStatusInfo();
            throw new FooException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
        }
        return response.readEntity((
new javax.ws.rs.core.GenericType<java.util.List<include_schema.resource.cs.login.model.AuthorizationJson>>() {}));
    }
 
Example #25
Source File: Login.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
public FooResponse<String> post() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.post(null);
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new FooException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    FooResponse<String> apiResponse = new FooResponse<String>(((String) response.readEntity(Object.class)), response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #26
Source File: SchedulerWsDelegate.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
private void handleResponse( ClientResponse response ) throws SchedulerWsException {

		if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
			String value = response.getEntity( String.class );
			this.logger.finer( response.getStatusInfo() + ": " + value );
			throw new SchedulerWsException( response.getStatusInfo().getStatusCode(), value );
		}
	}
 
Example #27
Source File: Bar.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
/**
 * SomeDescriptionValue
 * 
 */
public LocationsResponse<recursive_type.model.Foo> get() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new LocationsException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    LocationsResponse<recursive_type.model.Foo> apiResponse = new LocationsResponse<recursive_type.model.Foo>(response.readEntity(recursive_type.model.Foo.class), response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #28
Source File: Rename.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Rename a project
 * 
 */
public DesignCenterProjectsServicewithsubresourceonsamelineResponse<Void> put(Object body) {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.put(Entity.json(body));
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new DesignCenterProjectsServicewithsubresourceonsamelineException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    DesignCenterProjectsServicewithsubresourceonsamelineResponse<Void> apiResponse = new DesignCenterProjectsServicewithsubresourceonsamelineResponse<Void>(null, response.getStringHeaders(), response);
    return apiResponse;
}
 
Example #29
Source File: Provider.java    From raml-java-client-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns combined provider details
 * 
 */
public library.resource.provider.model.ProviderGETResponse get() {
    WebTarget target = this._client.target(getBaseUri());
    final javax.ws.rs.client.Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response response = invocationBuilder.get();
    if (response.getStatusInfo().getFamily()!= Family.SUCCESSFUL) {
        Response.StatusType statusInfo = response.getStatusInfo();
        throw new CoreServicesAPIReferenceException(statusInfo.getStatusCode(), statusInfo.getReasonPhrase(), response.getStringHeaders(), response);
    }
    return response.readEntity(library.resource.provider.model.ProviderGETResponse.class);
}
 
Example #30
Source File: BaseService.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected static void checkImageTargetingResponse(final String id, final Response.StatusType statusInfo) {
    if (statusInfo.getFamily() == Family.SUCCESSFUL) {
        // no error
        return;
    }

    switch (statusInfo.getStatusCode()) {
        case 404:
            throw new ImageNotFoundException(id);
        default:
            throw new DockerException(statusInfo.getReasonPhrase());
    }
}