当前位置: 首页>>代码示例>>Java>>正文


Java ExceptionMapper类代码示例

本文整理汇总了Java中javax.ws.rs.ext.ExceptionMapper的典型用法代码示例。如果您正苦于以下问题:Java ExceptionMapper类的具体用法?Java ExceptionMapper怎么用?Java ExceptionMapper使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ExceptionMapper类属于javax.ws.rs.ext包,在下文中一共展示了ExceptionMapper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: toResponse

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@SuppressWarnings({ "unchecked", "rawtypes" })
private Response toResponse(final MinijaxRequestContext context, final Exception ex) {
    final MinijaxResourceMethod rm = context.getResourceMethod();
    final List<MediaType> mediaTypes;

    if (rm != null) {
        mediaTypes = rm.getProduces();
    } else {
        mediaTypes = context.getAcceptableMediaTypes();
    }

    for (final MediaType mediaType : mediaTypes) {
        final ExceptionMapper mapper = providers.getExceptionMapper(ex.getClass(), mediaType);
        if (mapper != null) {
            return mapper.toResponse(ex);
        }
    }

    return ExceptionUtils.toWebAppException(ex).getResponse();
}
 
开发者ID:minijax,项目名称:minijax,代码行数:21,代码来源:MinijaxApplication.java

示例2: register

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public void register(final Class<?> c) {
    if (MessageBodyReader.class.isAssignableFrom(c)) {
        readers.add((Class<MessageBodyReader<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Consumes.class)));
    }

    if (MessageBodyWriter.class.isAssignableFrom(c)) {
        writers.add((Class<MessageBodyWriter<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
    }

    if (ExceptionMapper.class.isAssignableFrom(c)) {
        exceptionMappers.add((Class<ExceptionMapper<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
    }

    if (ParamConverterProvider.class.isAssignableFrom(c)) {
        paramConverterProviders.add((ParamConverterProvider) application.get(c));
    }
}
 
开发者ID:minijax,项目名称:minijax,代码行数:19,代码来源:MinijaxProviders.java

示例3: doBatch

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
/**
 * Process the entries
 */
private void doBatch() {
	for (final B importEntry : task.getEntries()) {
		// Override previous status
		importEntry.setStatus(null);
		importEntry.setStatusText(null);
		try {
			doBatch(importEntry);

			// Success
			importEntry.setStatus(Boolean.TRUE);
			log.info("Import of {} succeed", importEntry);
		} catch (final Exception ne) {
			// The entry creation failed : entity itself of group membership
			log.info("Import of {} failed : {}", importEntry, ne.getMessage());
			importEntry.setStatus(Boolean.FALSE);
			final ExceptionMapper<Throwable> mapper = jaxrsFactory.createExceptionMapper(ne.getClass(), null);
			importEntry.setStatusText(mapper == null ? ne.getMessage() : mapper.toResponse(ne).getEntity().toString());
		}
		task.getStatus().setDone(task.getStatus().getDone() + 1);
	}
}
 
开发者ID:ligoj,项目名称:plugin-id,代码行数:25,代码来源:AbstractLdapBatchTask.java

示例4: configureMessage

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@Test
public void configureMessage() throws IllegalArgumentException, IllegalAccessException {
	final ServerProviderFactory instance = ServerProviderFactory.getInstance();
	@SuppressWarnings("unchecked")
	final List<ProviderInfo<ExceptionMapper<?>>> object = (List<ProviderInfo<ExceptionMapper<?>>>) FieldUtils
			.getField(ServerProviderFactory.class, "exceptionMappers", true).get(instance);
	final FailSafeExceptionMapper provider = new FailSafeExceptionMapper();
	object.add(new ProviderInfo<>(provider, null, true));
	final JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
	FieldUtils.getField(FailSafeExceptionMapper.class, "jacksonJsonProvider", true).set(provider, jacksonJsonProvider);

	final UserImportEntry entry = Mockito.mock(UserImportEntry.class);
	Mockito.when(entry.getId()).thenThrow(new RuntimeException());
	final BatchTaskVo<UserImportEntry> importTask = new BatchTaskVo<>();
	importTask.setEntries(Collections.singletonList(entry));
	task.configure(importTask);
	task.jaxrsFactory = instance;
	task.run();
	Assert.assertEquals(Boolean.TRUE, importTask.getStatus().getStatus());
	Assert.assertEquals(1, importTask.getStatus().getDone());
	Assert.assertEquals(1, importTask.getStatus().getEntries());
}
 
开发者ID:ligoj,项目名称:plugin-id,代码行数:23,代码来源:UserFullLdapTaskTest.java

示例5: toResponse

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@Override 
public Response toResponse(Exception ex) {
    if (Options.RETURN_EXCEPTION_BODY) {
        if (ex instanceof PersistenceException) {
            Throwable cause = ex.getCause();
            if (cause != null) { // The type of this exception is determined at runtime
                cause = cause.getCause();
                if (cause instanceof SQLIntegrityConstraintViolationException) {
                    return new RestErrorBuilder(cause).createResponse();
                }
            }
        }
    }
    
    ExceptionMapper exceptionMapper = providers.getExceptionMapper(ex.getClass());
    if (exceptionMapper == null || exceptionMapper == this) {
        return Response.serverError().build();
    }
    else {
        return exceptionMapper.toResponse(ex);
    }
}
 
开发者ID:codebulb,项目名称:crudlet,代码行数:23,代码来源:RestfulExceptionMapper.java

示例6: backstopperOnlyExceptionMapperFactory_removes_all_exception_mappers_except_Jersey2ApiExceptionHandler

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@Test
public void backstopperOnlyExceptionMapperFactory_removes_all_exception_mappers_except_Jersey2ApiExceptionHandler()
    throws NoSuchFieldException, IllegalAccessException {
    // given
    AbstractBinder lotsOfExceptionMappersBinder = new AbstractBinder() {
        @Override
        protected void configure() {
            bind(JsonMappingExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
            bind(JsonParseExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
            bind(generateJerseyApiExceptionHandler(projectApiErrors, utils)).to(ExceptionMapper.class);
        }
    };

    ServiceLocator locator = ServiceLocatorUtilities.bind(lotsOfExceptionMappersBinder);

    // when
    BackstopperOnlyExceptionMapperFactory overrideExceptionMapper = new BackstopperOnlyExceptionMapperFactory(locator);

    // then
    Set<Object> emTypesLeft = overrideExceptionMapper.getFieldObj(
        ExceptionMapperFactory.class, overrideExceptionMapper, "exceptionMapperTypes"
    );
    assertThat(emTypesLeft).hasSize(1);
    ServiceHandle serviceHandle = overrideExceptionMapper.getFieldObj(emTypesLeft.iterator().next(), "mapper");
    assertThat(serviceHandle.getService()).isInstanceOf(Jersey2ApiExceptionHandler.class);
}
 
开发者ID:Nike-Inc,项目名称:backstopper,代码行数:27,代码来源:Jersey2BackstopperConfigHelperTest.java

示例7: toResponse

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
public Response toResponse(EJBException exception)
{
   if (exception.getCausedByException() == null)
   {
      return Response.serverError().build();
   }
   Class cause = exception.getCausedByException().getClass();
   ExceptionMapper mapper = providers.getExceptionMapper(cause);
   if (mapper == null)
   {
      return Response.serverError().build();
   }
   else
   {
      return mapper.toResponse(exception.getCausedByException());
   }
}
 
开发者ID:resteasy,项目名称:resteasy-examples,代码行数:18,代码来源:EJBExceptionMapper.java

示例8: toResponse

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public Response toResponse(EJBException exception) {
    if (exception.getCausedByException() == null) {
        LOGGER.error(exception.getMessage(), exception);
        return Responses.errorResponse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(), "Internal Server Error", exception, LOGGER.isInfoEnabled());
    } else {
        Class cause = exception.getCausedByException().getClass();
        ExceptionMapper mapper = providers.getExceptionMapper(cause);
        if (mapper == null) {
            LOGGER.error(exception.getMessage(), exception);
            return Responses.errorResponse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(), "Internal Server Error", exception, LOGGER.isInfoEnabled());
        } else {
            return mapper.toResponse(exception.getCausedByException());
        }
    }
}
 
开发者ID:projectomakase,项目名称:omakase,代码行数:18,代码来源:EJBExceptionMapper.java

示例9: getClasses

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@Override
public Set<Class<?>> getClasses() {
	Set<Class<?>> s = new HashSet<Class<?>>();
	
	// rest Resources
	Set<Class<? extends RESTResource>> restResourceTypes = this.getRESTResourceTypes();
	if (CollectionUtils.hasData(restResourceTypes)) s.addAll(restResourceTypes);
	
	// Request received objects mappers: transforms Java->XML for REST methods param types
	Set<Class<? extends MessageBodyReader<?>>> reqReceivedTypesMappers = this.getRequestReceivedTypesMappers();
	if (CollectionUtils.hasData(reqReceivedTypesMappers)) s.addAll(reqReceivedTypesMappers);
	
	// Response sent objects mappers: transforms Java->XML for REST methods return types
	Set<Class<? extends MessageBodyWriter<?>>> respSentTypesMappers = this.getResponseSentTypesMappers();
	if (CollectionUtils.hasData(respSentTypesMappers)) s.addAll(respSentTypesMappers);
	
	// Exception Mappers
	Set<Class<? extends ExceptionMapper<?>>> expsMappers = this.getExceptionsMappers();
	if (CollectionUtils.hasData(expsMappers)) s.addAll(expsMappers);		
	
	return s;
}
 
开发者ID:opendata-euskadi,项目名称:r01fb,代码行数:23,代码来源:RESTAppBase.java

示例10: init

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
public void init() {

        for (Map.Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Path.class).entrySet()) {
            log.info("Deploying " + entry.getKey() + " bean as a resource");
            deploy(entry.getValue());
        }

        for (Map.Entry<String, ExceptionMapper> exceptionMapper :
                applicationContext.getBeansOfType(ExceptionMapper.class).entrySet()) {
            log.info("Adding " + exceptionMapper.getKey() + "  ExceptionMapper");
            addExceptionMapper(exceptionMapper.getValue());
        }

        configureTransport(applicationContext.getBeansOfType(ListenerConfiguration.class).values(),
                applicationContext.getBeansOfType(TransportConfig.class).values());

        start();
    }
 
开发者ID:wso2,项目名称:msf4j,代码行数:19,代码来源:SpringMicroservicesRunner.java

示例11: addExceptionMapper

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
public void addExceptionMapper(ExceptionMapper... mapper) {
    Arrays.stream(mapper).forEach(em -> {
        Arrays.stream(em.getClass().getMethods()).
                filter(method -> "toResponse".equals(method.getName()) && method.getParameterCount() == 1 &&
                        !Throwable.class.getName().equals(method.getParameterTypes()[0].getTypeName())).
                findAny().
                ifPresent(method -> {
                    try {
                        exceptionMappers.put(Class.forName(method.getParameterTypes()[0].getTypeName(), false,
                                em.getClass().getClassLoader()), em);
                    } catch (ClassNotFoundException e) {
                        log.error("Could not load class", e);
                    }
                });
    });
}
 
开发者ID:wso2,项目名称:msf4j,代码行数:17,代码来源:MicroservicesRegistryImpl.java

示例12: handleThrowable

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
private void handleThrowable(MicroservicesRegistryImpl currentMicroservicesRegistry, Throwable throwable,
                             Request request) {
    Optional<ExceptionMapper> exceptionMapper = currentMicroservicesRegistry.getExceptionMapper(throwable);
    if (exceptionMapper.isPresent()) {
        org.wso2.msf4j.Response msf4jResponse = new org.wso2.msf4j.Response(request);
        msf4jResponse.setEntity(exceptionMapper.get().toResponse(throwable));
        msf4jResponse.send();
    } else {
        log.warn("Unmapped exception", throwable);
        try {
            HTTPCarbonMessage response = HttpUtil.createTextResponse(
                    javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                    "Exception occurred :" + throwable.getMessage());
            response.addHttpContent(new DefaultLastHttpContent());
            request.respond(response);
        } catch (ServerConnectorException e) {
            log.error("Error while sending the response.", e);
        }
    }
}
 
开发者ID:wso2,项目名称:msf4j,代码行数:21,代码来源:MSF4JHttpConnectorListener.java

示例13: getExceptionProviderMap

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
/**
 * Finds the RESTEasy providers parameter and return its value as map of classes with its generic types.
 *
 * @param contextParams the map of all context parameters
 * @return a Map of RESTEasy exception-provider classes
 */
public static Map<Class<?>, Class<?>> getExceptionProviderMap(Map<String, String> contextParams) {
    Map<Class<?>, Class<?>> providerMap = new HashMap<Class<?>, Class<?>>();
    List<String> providers = getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS);
    if (providers != null) {
        for (String provider : providers) {
            Class<?> providerClass = Classes.forName(provider.trim());
            if (providerClass != null) {
                Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ExceptionMapper.class)[0];
                Class<?> exceptionClass = Types.getRawType(exceptionType);
                providerMap.put(exceptionClass, providerClass);
            }
        }
    }
    return providerMap;
}
 
开发者ID:jboss-switchyard,项目名称:switchyard,代码行数:22,代码来源:RESTEasyUtil.java

示例14: mapException

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
/**
 * Maps an ExceptionMapper for a given type of Exceptions. While this method
 * can be used for arbitrary exceptions, it is most useful to override the
 * default exception handlers defined in LinkRest for the following
 * exceptions: {@link LinkRestException}, {@link CayenneRuntimeException},
 * {@link ValidationException}.
 *
 * @since 1.1
 */
public <E extends Throwable> LinkRestBuilder mapException(Class<? extends ExceptionMapper<E>> mapper) {

    for (Type t : mapper.getGenericInterfaces()) {

        if (t instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) t;
            if (ExceptionMapper.class.equals(pt.getRawType())) {
                Type[] args = pt.getActualTypeArguments();
                exceptionMappers.put((Class<?>) args[0], mapper);
                return this;
            }
        }

    }

    throw new IllegalArgumentException("Failed to register ExceptionMapper: " + mapper.getName());
}
 
开发者ID:nhl,项目名称:link-rest,代码行数:27,代码来源:LinkRestBuilder.java

示例15: useAllExceptionMappers

import javax.ws.rs.ext.ExceptionMapper; //导入依赖的package包/类
@Test
public void useAllExceptionMappers() {
    final TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder
            .newBuilder()
            .configurationFactory(CONFIGURATION_FACTORY)
            .mapAllHystrixRuntimeExceptionsTo(429)
            .build();

    assertThat(bundle)
            .isEqualTo(new TenacityConfiguredBundle<>(
                    CONFIGURATION_FACTORY,
                    Optional.empty(),
                    ImmutableList.<ExceptionMapper<? extends Throwable>>of(
                            new TenacityExceptionMapper(429),
                            new TenacityContainerExceptionMapper(429))
            ));
}
 
开发者ID:yammer,项目名称:tenacity,代码行数:18,代码来源:TenacityConfiguredBundleBuilderTest.java


注:本文中的javax.ws.rs.ext.ExceptionMapper类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。