javax.ws.rs.WebApplicationException Java Examples

The following examples show how to use javax.ws.rs.WebApplicationException. 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: JAXRSXmlSecTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostBookWithNoSig() throws Exception {
    if (test.streaming) {
        // Only testing the endpoints, not the clients here
        return;
    }
    String address = "https://localhost:" + test.port + "/xmlsig";

    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = JAXRSXmlSecTest.class.getResource("client.xml");
    Bus springBus = bf.createBus(busFile.toString());
    bean.setBus(springBus);

    bean.setServiceClass(BookStore.class);

    BookStore store = bean.create(BookStore.class);
    try {
        store.addBook(new Book("CXF", 126L));
        fail("Failure expected on no Signature");
    } catch (WebApplicationException ex) {
        // expected
    }
}
 
Example #2
Source File: SimpleTypeJsonProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                  MultivaluedMap<String, String> headers, InputStream is)
    throws IOException, WebApplicationException {
    if (!supportSimpleTypesOnly && !InjectionUtils.isPrimitive(type)) {
        MessageBodyReader<T> next =
            providers.getMessageBodyReader(type, genericType, annotations, mediaType);
        JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
        try {
            return next.readFrom(type, genericType, annotations, mediaType, headers, is);
        } finally {
            JAXRSUtils.getCurrentMessage().put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
        }
    }
    String data = IOUtils.toString(is).trim();
    int index = data.indexOf(':');
    data = data.substring(index + 1, data.length() - 1).trim();
    if (data.startsWith("\"")) {
        data = data.substring(1, data.length() - 1);
    }
    return primitiveHelper.readFrom(type, genericType, annotations, mediaType, headers,
                                    new ByteArrayInputStream(StringUtils.toBytesUTF8(data)));
}
 
Example #3
Source File: Cafe.java    From javaee-docker with MIT License 6 votes vote down vote up
@PostConstruct
private void init() {
	try {
		InetAddress inetAddress = InetAddress.getByName(
				((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest())
						.getServerName());

		baseUri = FacesContext.getCurrentInstance().getExternalContext().getRequestScheme() + "://"
				+ inetAddress.getHostName() + ":"
				+ FacesContext.getCurrentInstance().getExternalContext().getRequestServerPort()
				+ "/javaee-cafe/rest/coffees";
		this.client = ClientBuilder.newClient();
		this.getAllCoffees();
	} catch (IllegalArgumentException | NullPointerException | WebApplicationException | UnknownHostException ex) {
		logger.severe("Processing of HTTP response failed.");
		ex.printStackTrace();
	}
}
 
Example #4
Source File: StandardNiFiServiceFacade.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public NodeDTO updateNode(final NodeDTO nodeDTO) {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new WebApplicationException(new Throwable("Unable to access details for current user."));
    }
    final String userDn = user.getIdentity();

    final NodeIdentifier nodeId = clusterCoordinator.getNodeIdentifier(nodeDTO.getNodeId());
    if (nodeId == null) {
        throw new UnknownNodeException("No node exists with ID " + nodeDTO.getNodeId());
    }


    if (NodeConnectionState.CONNECTING.name().equalsIgnoreCase(nodeDTO.getStatus())) {
        clusterCoordinator.requestNodeConnect(nodeId, userDn);
    } else if (NodeConnectionState.DISCONNECTING.name().equalsIgnoreCase(nodeDTO.getStatus())) {
        clusterCoordinator.requestNodeDisconnect(nodeId, DisconnectionCode.USER_DISCONNECTED,
                "User " + userDn + " requested that node be disconnected from cluster");
    }

    return getNode(nodeId);
}
 
Example #5
Source File: ErrorHandler.java    From Web-API with MIT License 6 votes vote down vote up
@Override
public Response toResponse(Throwable exception) {
    int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();

    if (exception instanceof WebApplicationException) {
        status = ((WebApplicationException)exception).getResponse().getStatus();
    } else if (exception instanceof UnrecognizedPropertyException) {
        status = Response.Status.BAD_REQUEST.getStatusCode();
    } else {
        // Print the stack trace as this is an "unexpected" exception,
        // and we want to make sure we can track it down
        exception.printStackTrace();
    }

    return Response
            .status(status)
            .entity(new ErrorMessage(status, exception.getMessage()))
            .build();
}
 
Example #6
Source File: ODataExceptionMapperImpl.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(final Exception exception) {
  ODataResponse response;
  try {
    if (exception instanceof WebApplicationException) {
      response = handleWebApplicationException(exception);
    } else {
      response = handleException(exception);
    }
  } catch (Exception e) {
    response = ODataResponse.entity("Exception during error handling occured!")
        .contentHeader(ContentType.TEXT_PLAIN.toContentTypeString())
        .status(HttpStatusCodes.INTERNAL_SERVER_ERROR).build();
  }
  // Convert OData response to JAX-RS response.
  return RestUtil.convertResponse(response);
}
 
Example #7
Source File: DefinitionRepresentationTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidationNegativeSuspend() throws Exception {

    DefinitionRepresentation trigger = new DefinitionRepresentation();
    trigger.setAction("SUBSCRIBE_TO_SERVICE");
    trigger.setTargetURL("<http://");
    trigger.setDescription("abc");
    trigger.setType("REST_SERVICE");
    trigger.setAction("SUBSCRIBE_TO_SERVICE");

    try {
        trigger.validateContent();
        fail();
    } catch (WebApplicationException e) {
        assertEquals(Status.BAD_REQUEST.getStatusCode(), e.getResponse()
                .getStatus());
    }
}
 
Example #8
Source File: JaxbTest.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
@Test
	public void testJson() throws JAXBException, WebApplicationException, IOException {
		HtrTrainConfig config = new HtrTrainConfig();
		
		ParameterMap map = new ParameterMap();
		map.addParameter("test", "testValue");
		config.setCustomParams(map);
		
//		Properties props = new Properties();
//		props.setProperty("test", "testValue");
//		config.setParams(props);
		
		logger.info(JaxbUtils.marshalToString(config));
		
		String moxyStr = JaxbUtils.marshalToJsonString(config, true);
		logger.info("MOXy says:\n" + moxyStr);
		
		String jacksonStr = marshalToJacksonJsonString(config);
		logger.info("Jackson says:\n" + jacksonStr);
	}
 
Example #9
Source File: FastJsonProvider.java    From metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Method that JAX-RS container calls to deserialize given value.
 */
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                       MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    String input = null;
    try {
        input = inputStreamToString(entityStream);
    } catch (Exception e) {

    }
    if (input == null) {
        return null;
    }
    if (fastJsonConfig.features == null)
        return JSON.parseObject(input, type, fastJsonConfig.parserConfig, JSON.DEFAULT_PARSER_FEATURE);
    else
        return JSON.parseObject(input, type, fastJsonConfig.parserConfig, JSON.DEFAULT_PARSER_FEATURE,
                fastJsonConfig.features);
}
 
Example #10
Source File: WebActionBase64ReadInterceptorTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
public void testWrapsInputStream(String contentType) throws WebApplicationException, IOException {
	ReaderInterceptorContext context = mockContext(contentType);
	InputStream is = mock(InputStream.class);
	when(context.getInputStream()).thenReturn(is);

	readInterceptor.aroundReadFrom(context);

	verifyZeroInteractions(is);

	ArgumentCaptor<InputStream> updatedIsCapture = ArgumentCaptor.forClass(InputStream.class);
	verify(context).setInputStream(updatedIsCapture.capture());
	verify(context).getMediaType();
	verify(context).getInputStream();
	verify(context).proceed();
	verifyNoMoreInteractions(context);

	InputStream updatedIs = updatedIsCapture.getValue();

	// just make sure we have some wrapper
	assertNotSame(is, updatedIs);
	updatedIs.close();
	verify(is).close();
}
 
Example #11
Source File: ApiResource.java    From jrestless-examples with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/cat-streaming-output")
@Produces("image/gif")
public StreamingOutput getRandomCatAsStreamingOutput() {
	return new StreamingOutput() {
		@Override
		public void write(OutputStream os) throws IOException, WebApplicationException {
			try (InputStream is = loadRandomCatGif()) {
				byte[] buffer = new byte[BUFFER_LENGTH];
				int bytesRead;
				while ((bytesRead = is.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
				}
			}
		}
	};
}
 
Example #12
Source File: TestServiceREST.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test58getSecureServicePoliciesIfUpdatedAllowedFail() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

	Long lastKnownVersion = 1L;
	String pluginId = "1";
	XXService xService = xService();
	XXServiceDef xServiceDef = serviceDef();
	xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS");
	String serviceName = xService.getName();
	RangerService rs = rangerService();
	XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class);
	Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true);
	Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
	Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService);
	Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao);
	Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef);
	Mockito.when(svcStore.getServiceByNameForDP(serviceName)).thenReturn(rs);
	Mockito.when(bizUtil.isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke)).thenReturn(true);
	Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()))
			.thenThrow(new WebApplicationException());
	thrown.expect(WebApplicationException.class);

	serviceREST.getSecureServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request);
}
 
Example #13
Source File: TestXUserREST.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test50getXAuditMapVXAuditMapNull() {
	VXAuditMap testvXAuditMap =  createVXAuditMapObj();
	Mockito.when(xUserMgr.getXAuditMap(testvXAuditMap.getResourceId())).thenReturn(testvXAuditMap);

	Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())).thenThrow(new WebApplicationException());
	thrown.expect(WebApplicationException.class);
	
	VXAuditMap retVXAuditMap=xUserRest.getXAuditMap(testvXAuditMap.getResourceId());
	
	assertEquals(testvXAuditMap.getId(),retVXAuditMap.getId());
	assertEquals(testvXAuditMap.getClass(),retVXAuditMap.getClass());
	assertNotNull(retVXAuditMap);
	
	Mockito.verify(xUserMgr).getXAuditMap(testvXAuditMap.getResourceId());
	Mockito.verify(xResourceService).readResource(null);
	Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any()));
	
}
 
Example #14
Source File: AlbResource.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/target-groups/{targetGroup}/targets/{instanceId}")
public AgentCheckInResponse removeFromTargetGroup(@PathParam("targetGroup") String targetGroup,
                                                  @PathParam("instanceId") String instanceId) {
  if (instanceId == null) {
    throw new BaragonWebException("Must provide instance ID to remove target from group");
  } else if (config.isPresent()) {
    AgentCheckInResponse result = applicationLoadBalancer.removeInstance(instanceId, targetGroup);
    if (result.getExceptionMessage().isPresent()) {
      throw new WebApplicationException(result.getExceptionMessage().get(), Status.INTERNAL_SERVER_ERROR);
    }
    return result;
  } else {
    throw new BaragonWebException("ElbSync and related actions not currently enabled");
  }
}
 
Example #15
Source File: PersistentTopics.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{property}/{cluster}/{namespace}/{topic}/subscription/{subName}/expireMessages/{expireTimeInSeconds}")
@ApiOperation(hidden = true, value = "Expire messages on a topic subscription.")
@ApiResponses(value = {
        @ApiResponse(code = 307, message = "Current broker doesn't serve the namespace of this topic"),
        @ApiResponse(code = 403, message = "Don't have admin permission"),
        @ApiResponse(code = 404, message = "Topic or subscription does not exist") })
public void expireTopicMessages(@Suspended final AsyncResponse asyncResponse,
        @PathParam("property") String property, @PathParam("cluster") String cluster,
        @PathParam("namespace") String namespace, @PathParam("topic") @Encoded String encodedTopic,
        @PathParam("subName") String encodedSubName, @PathParam("expireTimeInSeconds") int expireTimeInSeconds,
        @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    try {
        validateTopicName(property, cluster, namespace, encodedTopic);
        internalExpireMessages(asyncResponse, decode(encodedSubName), expireTimeInSeconds, authoritative);
    } catch (WebApplicationException wae) {
        asyncResponse.resume(wae);
    } catch (Exception e) {
        asyncResponse.resume(new RestException(e));
    }
}
 
Example #16
Source File: SubscriptionsResource.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private QueueConsumer recreateTopicConsumer(String subscriptionId, boolean autoAck) {
   QueueConsumer consumer;
   if (subscriptionExists(subscriptionId)) {
      QueueConsumer tmp = null;
      try {
         tmp = createConsumer(true, autoAck, subscriptionId, null, consumerTimeoutSeconds * 1000L, false);
      } catch (ActiveMQException e) {
         throw new RuntimeException(e);
      }
      consumer = queueConsumers.putIfAbsent(subscriptionId, tmp);
      if (consumer == null) {
         consumer = tmp;
         serviceManager.getTimeoutTask().add(this, subscriptionId);
      } else {
         tmp.shutdown();
      }
   } else {
      throw new WebApplicationException(Response.status(405).entity("Failed to find subscriber " + subscriptionId + " you will have to reconnect").type("text/plain").build());
   }
   return consumer;
}
 
Example #17
Source File: TestRangerServiceDefServiceBase.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Test
public void test17populateRangerEnumDefToXXnullValue() {
	RangerEnumDef rangerEnumDefObj = null;
	XXEnumDef enumDefObj = null;
	XXServiceDef serviceDefObj = null;

	Mockito.when(
			restErrorUtil.createRESTException(
					"RangerServiceDef cannot be null.",
					MessageEnums.DATA_NOT_FOUND)).thenThrow(
			new WebApplicationException());

	thrown.expect(WebApplicationException.class);

	XXEnumDef dbEnumDef = rangerServiceDefService
			.populateRangerEnumDefToXX(rangerEnumDefObj, enumDefObj,
					serviceDefObj, 1);
	Assert.assertNull(dbEnumDef);

}
 
Example #18
Source File: NoFileEntityProvider.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public File readFrom(Class<File> type,
                     Type genericType,
                     Annotation[] annotations,
                     MediaType mediaType,
                     MultivaluedMap<String, String> httpHeaders,
                     InputStream entityStream) throws IOException {
    throw new WebApplicationException(Response.status(BAD_REQUEST).entity(
            "File is not supported as method's parameter.").type(TEXT_PLAIN).build());
}
 
Example #19
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBookWithExceptionsNoMapper() throws Exception {
    BookStore store = JAXRSClientFactory.create("http://localhost:" + PORT,
                                                BookStore.class);
    try {
        store.getBookWithExceptions(true);
        fail();
    } catch (WebApplicationException ex) {
        assertEquals("notReturned", ex.getResponse().getHeaderString("Status"));
    }
}
 
Example #20
Source File: KubernetesApiClient.java    From KubernetesAPIJavaClient with Apache License 2.0 5 votes vote down vote up
public ReplicationController createReplicationController(ReplicationController controller)
        throws KubernetesClientException {
    try {
        return api.createReplicationController(controller);
    } catch (WebApplicationException e) {
        throw new KubernetesClientException(e);
    }
}
 
Example #21
Source File: AbstractParam.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Given an input value from a client, creates a parameter wrapping its parsed value.
 *
 * @param input an input value from a client request
 */
@SuppressWarnings({"AbstractMethodCallInConstructor", "OverriddenMethodCallDuringObjectConstruction"})
protected AbstractParam(String input) {
    try {
        this.value = parse(input);
    } catch (Exception e) {
        throw new WebApplicationException(error(input, e));
    }
}
 
Example #22
Source File: RoleServiceImpl.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
public Response addRole(UriInfo ui, Role role) {
    if (role.getEntitlements() != null && !role.getEntitlements().isEmpty()) {
        LOG.warn("Role resource contains sub resource 'entitlements'");
        throw new WebApplicationException(Status.BAD_REQUEST);
    }
    Role createdRole = roleDAO.addRole(role);

    UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
    uriBuilder.path("{index}");
    URI location = uriBuilder.build(createdRole.getName());

    LOG.debug("Role '" + role.getName() + "' added");
    return Response.created(location).entity(role).build();
}
 
Example #23
Source File: RestServiceImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public void cleanupEnvironment( final EnvironmentId environmentId )
{
    try
    {
        Preconditions.checkNotNull( environmentId );

        localPeer.cleanupEnvironment( environmentId );
    }
    catch ( Exception e )
    {
        LOGGER.error( e.getMessage(), e );
        throw new WebApplicationException( Response.serverError().entity( e.getMessage() ).build() );
    }
}
 
Example #24
Source File: EntityUpdateCollectionReader.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<EntityUpdate<T>> readFrom(
        Class<Collection<EntityUpdate<T>>> type,
        Type genericType,
        Annotation[] annotations,
        MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders,
        InputStream entityStream) throws WebApplicationException {

    Type entityUpdateType = Types.unwrapTypeArgument(genericType)
            .orElseThrow(() -> new AgException(Status.INTERNAL_SERVER_ERROR,
                    "Invalid request entity collection type: " + genericType));

    return reader.read(entityUpdateType, entityStream);
}
 
Example #25
Source File: PulsarWebResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
protected NamespaceBundle validateNamespaceBundleOwnership(NamespaceName fqnn, BundlesData bundles,
        String bundleRange, boolean authoritative, boolean readOnly) {
    try {
        NamespaceBundle nsBundle = validateNamespaceBundleRange(fqnn, bundles, bundleRange);
        validateBundleOwnership(nsBundle, authoritative, readOnly);
        return nsBundle;
    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        log.error("[{}] Failed to validate namespace bundle {}/{}", clientAppId(), fqnn.toString(), bundleRange, e);
        throw new RestException(e);
    }
}
 
Example #26
Source File: BufferPublisherMessageBodyReaderWriter.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Buffer> readFrom(final Class<Publisher<Buffer>> type,
                                  final Type genericType,
                                  final Annotation[] annotations,
                                  final MediaType mediaType,
                                  final MultivaluedMap<String, String> httpHeaders,
                                  final InputStream entityStream) throws WebApplicationException {
    return readFrom(entityStream, (p, a) -> p, PublisherSource::new);
}
 
Example #27
Source File: Oauth2LoginStreamingOutput.java    From gitlab4j-api with MIT License 5 votes vote down vote up
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {

    Writer writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
    writer.write("{ ");
    writer.write("\"grant_type\": \"password\", ");
    writer.write("\"username\": \"" + username + "\", ");
    writer.write("\"password\": ");

    // Output the quoted password
    writer.write('"');
    for (int i = 0, length = password.length(); i < length; i++) {

        char c = password.charAt(i);
        if (c == '"' || c == '\\') {
            writer.write('\\');
        }

        writer.write(c);
    }

    writer.write('"');

    writer.write(" }");
    writer.flush();
    writer.close();
}
 
Example #28
Source File: AgreementXmlMessageBodyWriter.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(IAgreement agreement, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> multivaluedMap, OutputStream entityStream)
        throws IOException, WebApplicationException {
    if (catchedException!=null) 
        throw new WebApplicationException(catchedException, Response.Status.INTERNAL_SERVER_ERROR);
    else
        entityStream.write(serializedData);        
}
 
Example #29
Source File: LdapTestDto.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public void cleanUp(TestContext context, CloudbreakClient cloudbreakClient) {
    LOGGER.info("Cleaning up ldapconfig with name: {}", getName());
    try {
        when(ldapTestClient.deleteV1());
    } catch (WebApplicationException ignore) {
        LOGGER.info("Something happend.");
    }
}
 
Example #30
Source File: SearchResourceTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testSearchAndDownload_SpecificAssetParam_NotFound_404_HTTP_RESPONSE() {
  when(searchHits.hits()).thenReturn(new SearchHit[]{searchHitNpm});
  when(searchQueryService.search(queryBuilderArgumentCaptor.capture(), eq(0), eq(50)))
      .thenReturn(searchResponse);
  try {
    underTest.searchAndDownloadAssets(null, null, null, uriInfo("?format=npm&sha1=notfound"));
  }
  catch (WebApplicationException webEx) {
    assertThat(webEx.getResponse().getStatus(), equalTo(404));
  }
}