Java Code Examples for javax.ws.rs.WebApplicationException

The following examples show how to use javax.ws.rs.WebApplicationException. These examples are extracted from open source projects. 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 Project: cxf   Source File: SimpleTypeJsonProvider.java    License: 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 2
Source Project: olingo-odata2   Source File: ODataExceptionMapperImpl.java    License: 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 3
Source Project: development   Source File: DefinitionRepresentationTest.java    License: 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 4
Source Project: TranskribusCore   Source File: JaxbTest.java    License: 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 5
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 6
Source Project: jrestless-examples   Source File: ApiResource.java    License: 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 7
Source Project: Baragon   Source File: AlbResource.java    License: 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 8
Source Project: activemq-artemis   Source File: SubscriptionsResource.java    License: 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 9
Source Project: ranger   Source File: TestRangerServiceDefServiceBase.java    License: 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 10
Source Project: pulsar   Source File: PersistentTopics.java    License: 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 11
Source Project: ranger   Source File: TestXUserREST.java    License: 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 12
Source Project: ranger   Source File: TestServiceREST.java    License: 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 Project: metrics   Source File: FastJsonProvider.java    License: 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 14
Source Project: cxf   Source File: JAXRSXmlSecTest.java    License: 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 15
Source Project: Web-API   Source File: ErrorHandler.java    License: 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 16
@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 17
Source Project: javaee-docker   Source File: Cafe.java    License: 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 18
Source Project: cloudbreak   Source File: LdapTestDto.java    License: 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 19
Source Project: quarkus   Source File: PanacheMockingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Order(1)
public void testPanacheMocking() {
    PanacheMock.mock(Person.class);

    Assertions.assertEquals(0, Person.count());

    Mockito.when(Person.count()).thenReturn(23l);
    Assertions.assertEquals(23, Person.count());

    Mockito.when(Person.count()).thenReturn(42l);
    Assertions.assertEquals(42, Person.count());

    Mockito.when(Person.count()).thenCallRealMethod();
    Assertions.assertEquals(0, Person.count());

    PanacheMock.verify(Person.class, Mockito.times(4)).count();

    Person p = new Person();
    Mockito.when(Person.findById(12l)).thenReturn(p);
    Assertions.assertSame(p, Person.findById(12l));
    Assertions.assertNull(Person.findById(42l));

    Mockito.when(Person.findById(12l)).thenThrow(new WebApplicationException());
    try {
        Person.findById(12l);
        Assertions.fail();
    } catch (WebApplicationException x) {
    }

    Mockito.when(Person.findOrdered()).thenReturn(Collections.emptyList());
    Assertions.assertTrue(Person.findOrdered().isEmpty());

    PanacheMock.verify(Person.class).findOrdered();
    PanacheMock.verify(Person.class, Mockito.atLeastOnce()).findById(Mockito.any());
    PanacheMock.verifyNoMoreInteractions(Person.class);

    Assertions.assertEquals(0, Person.methodWithPrimitiveParams(true, (byte) 0, (short) 0, 0, 2, 2.0f, 2.0, 'c'));
}
 
Example 20
public Service createService(Service service) throws KubernetesClientException {
    try {
        return api.createService(service);
    } catch (WebApplicationException e) {
        throw new KubernetesClientException(e);
    }
}
 
Example 21
Source Project: ranger   Source File: TestServiceREST.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test30getPolicyFromEventTime() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

	String strdt = new Date().toString();
	String userName="Admin";
	Set<String> userGroupsList = new HashSet<String>();
	userGroupsList.add("group1");
	userGroupsList.add("group2");
	Mockito.when(request.getParameter("eventTime")).thenReturn(strdt);
	Mockito.when(request.getParameter("policyId")).thenReturn("1");
	Mockito.when(request.getParameter("versionNo")).thenReturn("1");
	RangerPolicy policy=new RangerPolicy();
	Map<String, RangerPolicyResource> resources=new HashMap<String, RangerPolicy.RangerPolicyResource>();
	policy.setService("services");
	policy.setResources(resources);
	Mockito.when(svcStore.getPolicyFromEventTime(strdt, 1l)).thenReturn(policy);
	Mockito.when(bizUtil.isAdmin()).thenReturn(false);
	Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName);

	Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()))
			.thenThrow(new WebApplicationException());
	thrown.expect(WebApplicationException.class);

	RangerPolicy dbRangerPolicy = serviceREST
			.getPolicyFromEventTime(request);
	Assert.assertNull(dbRangerPolicy);
	Mockito.verify(request).getParameter("eventTime");
	Mockito.verify(request).getParameter("policyId");
	Mockito.verify(request).getParameter("versionNo");
}
 
Example 22
Source Project: streamline   Source File: JsonClientUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> T getEntity(WebTarget target, MediaType mediaType, Class<T> clazz) {
    try {
        String response = target.request(mediaType).get(String.class);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response);
        return mapper.treeToValue(node, clazz);
    }  catch (WebApplicationException e) {
        throw WrappedWebApplicationException.of(e);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 23
Source Project: hadoop-ozone   Source File: ContainerEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return
 * {@link org.apache.hadoop.ozone.recon.api.types.MissingContainerMetadata}
 * for all missing containers.
 *
 * @return {@link Response}
 */
@GET
@Path("/missing")
public Response getMissingContainers() {
  List<MissingContainerMetadata> missingContainers = new ArrayList<>();
  containerDBServiceProvider.getMissingContainers().forEach(container -> {
    long containerID = container.getContainerId();
    try {
      ContainerInfo containerInfo =
          containerManager.getContainer(new ContainerID(containerID));
      long keyCount = containerInfo.getNumberOfKeys();
      UUID pipelineID = containerInfo.getPipelineID().getId();

      List<ContainerHistory> datanodes =
          containerSchemaManager.getLatestContainerHistory(
              containerID, containerInfo.getReplicationFactor().getNumber());
      missingContainers.add(new MissingContainerMetadata(containerID,
          container.getInStateSince(), keyCount, pipelineID, datanodes));
    } catch (IOException ioEx) {
      throw new WebApplicationException(ioEx,
          Response.Status.INTERNAL_SERVER_ERROR);
    }
  });
  MissingContainersResponse response =
      new MissingContainersResponse(missingContainers.size(),
          missingContainers);
  return Response.ok(response).build();
}
 
Example 24
Source Project: keycloak   Source File: KeycloakErrorHandler.java    License: Apache License 2.0 5 votes vote down vote up
private int getStatusCode(Throwable throwable) {
    int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    if (throwable instanceof WebApplicationException) {
        WebApplicationException ex = (WebApplicationException) throwable;
        status = ex.getResponse().getStatus();
    }
    if (throwable instanceof Failure) {
        Failure f = (Failure) throwable;
        status = f.getErrorCode();
    }
    if (throwable instanceof JsonParseException) {
        status = Response.Status.BAD_REQUEST.getStatusCode();
    }
    return status;
}
 
Example 25
Source Project: dremio-oss   Source File: TableauMessageBodyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(DatasetConfig datasetConfig, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
    throws IOException, WebApplicationException {
  final String hostname;
  if (httpHeaders.containsKey(WebServer.X_DREMIO_HOSTNAME)) {
    hostname = (String) httpHeaders.getFirst(WebServer.X_DREMIO_HOSTNAME);
  } else {
    hostname = masterNode;
  }

  // Change headers to force download and suggest a filename.
  String fullPath = Joiner.on(".").join(datasetConfig.getFullPathList());
  httpHeaders.putSingle(HttpHeaders.CONTENT_DISPOSITION, format("attachment; filename=\"%s.tds\"", fullPath));

  try {
    final XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(entityStream, "UTF-8");

    xmlStreamWriter.writeStartDocument("utf-8", "1.0");
    writeDatasource(xmlStreamWriter, datasetConfig, hostname, mediaType);
    xmlStreamWriter.writeEndDocument();

    xmlStreamWriter.close();
  } catch (XMLStreamException e) {
    throw UserExceptionMapper.withStatus(
      UserException.dataWriteError(e)
        .message("Cannot generate TDS file")
        .addContext("Details", e.getMessage()),
      Status.INTERNAL_SERVER_ERROR
    ).build(logger);
  }
}
 
Example 26
Source Project: presto   Source File: ExecutingStatementResource.java    License: Apache License 2.0 5 votes vote down vote up
private static WebApplicationException badRequest(Status status, String message)
{
    throw new WebApplicationException(
            Response.status(status)
                    .type(TEXT_PLAIN_TYPE)
                    .entity(message)
                    .build());
}
 
Example 27
Source Project: catnap   Source File: CatnapMessageBodyWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(Object obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    //Check to see if Catnap processing has been disabled for this method
    for (Annotation annotation : annotations) {
        if (annotation instanceof CatnapDisabled) {
            RequestUtil.disableCatnap(request);
            break;
        }
    }

    try {
        //Transfer headers onto the response object that will be processed by Catnap
        if (httpHeaders != null) {
            for (Map.Entry<String, List<Object>> entry : httpHeaders.entrySet()) {
                for (Object value : entry.getValue()) {
                    response.addHeader(entry.getKey(), value.toString());
                }
            }
        }

        response.setContentType(getContentType());
        response.setCharacterEncoding(getCharacterEncoding());

        view.render(request, response, obj);
    } catch (Exception e) {
        logger.error("Exception encountered during view rendering!", e);
        throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example 28
@Test
public void client_handles_jetty_errors_404() throws Exception {
    try {
        SchedulerRestClient client = new SchedulerRestClient("http://localhost:" + port + "/" +
                                                             "rest/a_path_that_does_not_exist");

        client.getScheduler().login("demo", "demo");
        fail("Should have throw an exception");
    } catch (WebApplicationException e) {
        assertTrue(e instanceof NotFoundException);
        assertEquals(404, e.getResponse().getStatus());
    }
}
 
Example 29
Source Project: conductor   Source File: WebAppExceptionMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception) {
       logger.error(String.format("Error %s url: '%s'", exception.getClass().getSimpleName(),
               uriInfo.getPath()), exception);

       Response response = exception.getResponse();
       this.code = Code.forValue(response.getStatus());
       Map<String, Object> entityMap = new LinkedHashMap<>();
       entityMap.put("instance", host);
       entityMap.put("code", Optional.ofNullable(code).map(Code::name).orElse(null));
       entityMap.put("message", exception.getCause());
       entityMap.put("retryable", false);

       return Response.status(response.getStatus()).entity(entityMap).build();
}
 
Example 30
Source Project: resteasy-examples   Source File: OrderResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("{id}")
@Produces("application/xml")
public Response getOrder(@PathParam("id") int id, @Context UriInfo uriInfo)
{
   Order order = orderDB.get(id);
   if (order == null)
   {
      throw new WebApplicationException(Response.Status.NOT_FOUND);
   }
   Response.ResponseBuilder builder = Response.ok(order);
   if (!order.isCancelled()) addCancelHeader(uriInfo, builder);
   return builder.build();
}