Java Examples for javax.ws.rs.core.Application

The following java examples will help you to understand the usage of javax.ws.rs.core.Application. These source code samples are taken from different open source projects.

Example 1
Project: everrest-master  File: MethodParametersInjectionTest.java View source code
@UseDataProvider("injectParametersTestData")
@Test
public void injectsParameters(Object resource, String path, Map<String, List<String>> requestHeaders, String requestEntity, Object responseEntity) throws Exception {
    processor.addApplication(new Application() {

        @Override
        public Set<Object> getSingletons() {
            return newHashSet(resource);
        }
    });
    ContainerResponse response = launcher.service("POST", path, "", requestHeaders, requestEntity == null ? null : requestEntity.getBytes(), null);
    assertEquals(responseEntity, response.getEntity());
}
Example 2
Project: swagger-core-master  File: ApiListingJSON.java View source code
protected synchronized void scan(Application app) {
    Scanner scanner = ScannerFactory.getScanner();
    LOGGER.debug("using scanner " + scanner);
    if (scanner != null) {
        SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint());
        Set<Class<?>> classes = null;
        classes = scanner.classes();
        if (classes != null) {
            Reader reader = new Reader(swagger);
            swagger = reader.read(classes);
            if (scanner instanceof SwaggerConfig) {
                swagger = ((SwaggerConfig) scanner).configure(swagger);
            }
        }
    }
    initialized = true;
}
Example 3
Project: demoapps-master  File: RESTApplication.java View source code
/**
	 * Inits the.
	 */
public static void init() {
    Servlet servlet = new org.apache.wink.server.internal.servlet.RestServlet();
    ObjectNode params = JOM.createObjectNode();
    ArrayNode initParams = JOM.createArrayNode();
    ObjectNode param = JOM.createObjectNode();
    param.put("key", "javax.ws.rs.Application");
    param.put("value", RESTApplication.class.getName());
    initParams.add(param);
    params.set("initParams", initParams);
    JettyLauncher launcher = new JettyLauncher();
    try {
        launcher.add(servlet, new URI("/rs/"), params);
        launcher.addFilter("com.thetransactioncompany.cors.CORSFilter", "/*");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}
Example 4
Project: wildfly-swarm-master  File: JAXRSArchiveTest.java View source code
@Test
public void testWebXmlApplicationServletMappingPresent() {
    JAXRSArchive archive = ShrinkWrap.create(JAXRSArchive.class);
    archive.addClass(MyResource.class);
    archive.setWebXML(new StringAsset("<web-app><servlet-mapping><servlet-name>Faces Servlet</servlet-name><url-pattern>*.jsf</url-pattern></servlet-mapping><servlet-mapping><servlet-name>javax.ws.rs.core.Application</servlet-name><url-pattern>/foo/*</url-pattern></servlet-mapping></web-app>"));
    Node generated = archive.get(PATH);
    assertThat(generated).isNull();
}
Example 5
Project: embedded-rest-server-master  File: ApplicationFactoryLoader.java View source code
@Override
public Collection<ServletContextHandler> apply(Environment environment) {
    Iterable<ApplicationFactory> loader = loadFactories();
    Collection<ServletContextHandler> handlers = new ArrayList<>();
    for (ApplicationFactory factory : loader) {
        Application application = createApplication(environment, factory);
        if (application == null) {
            continue;
        }
        handlers.add(new JerseyServletContextHandler(application, factory.path()));
    }
    return handlers;
}
Example 6
Project: micro-server-master  File: SwaggerInitializer.java View source code
public void contextInitialized(ServletContextEvent servletContextEvent) {
    BeanConfig beanConfig = new BeanConfig() {

        @Override
        public List<Class<?>> classesFromContext(Application app, ServletConfig sc) {
            return resourceClasses;
        }
    };
    beanConfig.setVersion("1.0.2");
    beanConfig.setBasePath(baseUrlPattern);
    beanConfig.setDescription("RESTful resources");
    beanConfig.setTitle("RESTful API");
    beanConfig.setScan(true);
}
Example 7
Project: nuxeo-webengine-master  File: ApplicationFragment.java View source code
protected synchronized void createApp() {
    try {
        Object obj = bundle.loadClass(appClass).newInstance();
        if (obj instanceof ApplicationFactory) {
            app = ((ApplicationFactory) obj).getApplication(bundle, attrs);
        } else if (obj instanceof Application) {
            app = (Application) obj;
        } else {
            throw new IllegalArgumentException("Expecting an Application or ApplicationFactory class: " + appClass);
        }
    } catch (Exception e) {
        String msg = "Cannot instantiate JAX-RS application " + appClass + " from bundle " + bundle.getSymbolicName();
        throw new RuntimeException(msg, e);
    }
}
Example 8
Project: org.eclipse.ecr-master  File: ApplicationFragment.java View source code
protected synchronized void createApp() {
    try {
        Object obj = bundle.loadClass(appClass).newInstance();
        if (obj instanceof ApplicationFactory) {
            app = ((ApplicationFactory) obj).getApplication(bundle, attrs);
        } else if (obj instanceof Application) {
            app = (Application) obj;
        } else {
            throw new IllegalArgumentException("Expecting an Application or ApplicationFactory class: " + appClass);
        }
    } catch (Exception e) {
        String msg = "Cannot instantiate JAX-RS application " + appClass + " from bundle " + bundle.getSymbolicName();
        throw new RuntimeException(msg, e);
    }
}
Example 9
Project: Resteasy-master  File: ResteasyDeployment.java View source code
public static Application createApplication(String applicationClass, Dispatcher dispatcher, ResteasyProviderFactory providerFactory) {
    Class<?> clazz = null;
    try {
        clazz = Thread.currentThread().getContextClassLoader().loadClass(applicationClass);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    Application app = (Application) providerFactory.createProviderInstance(clazz);
    dispatcher.getDefaultContextObjects().put(Application.class, app);
    ResteasyProviderFactory.pushContext(Application.class, app);
    PropertyInjector propertyInjector = providerFactory.getInjectorFactory().createPropertyInjector(clazz, providerFactory);
    propertyInjector.inject(app);
    return app;
}
Example 10
Project: webengine-master  File: ApplicationFragment.java View source code
protected synchronized void createApp() {
    try {
        Object obj = bundle.loadClass(appClass).newInstance();
        if (obj instanceof ApplicationFactory) {
            app = ((ApplicationFactory) obj).getApplication(bundle, attrs);
        } else if (obj instanceof Application) {
            app = (Application) obj;
        } else {
            throw new IllegalArgumentException("Expecting an Application or ApplicationFactory class: " + appClass);
        }
    } catch (Exception e) {
        String msg = "Cannot instantiate JAX-RS application " + appClass + " from bundle " + bundle.getSymbolicName();
        throw new RuntimeException(msg, e);
    }
}
Example 11
Project: jbosstools-integration-tests-master  File: WebSocketHelper.java View source code
static TextEditor prepareAppEditor(String projectName) {
    TextEditor appEditor = createClass(projectName, NameBindingTest.Constants.PROJECT_PACKAGE, NameBindingTest.Constants.CLASS_NAME_APP);
    //add 'extends' def part
    String replacedCode = new DefaultStyledText().getText().replaceAll("public class " + NameBindingTest.Constants.CLASS_NAME_APP, "public class " + NameBindingTest.Constants.CLASS_NAME_APP + " extends Application");
    new DefaultStyledText().setText(replacedCode);
    addImport(appEditor, "import javax.ws.rs.core.Application;");
    addClassAnnotation(appEditor, "@ApplicationPath(\"/app\")", "import javax.ws.rs.ApplicationPath;");
    addClassAnnotation(appEditor, "@" + CLASS_NAME_ANNOTATION);
    appEditor.save();
    return appEditor;
}
Example 12
Project: tomee-master  File: CxfRsHttpListener.java View source code
private void deploy(final String contextRoot, final Class<?> clazz, final String address, final ResourceProvider rp, final Object serviceBean, final Application app, final Invoker invoker, final Collection<Object> additionalProviders, final ServiceConfiguration configuration, final WebBeansContext webBeansContext) {
    final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(CxfUtil.initBusLoader());
    try {
        final JAXRSServerFactoryBean factory = newFactory(address, createServiceJmxName(clazz.getClassLoader()), createEndpointName(app));
        configureFactory(additionalProviders, configuration, factory, webBeansContext);
        factory.setResourceClasses(clazz);
        context = contextRoot;
        if (context == null) {
            context = "";
        }
        if (!context.startsWith("/")) {
            context = "/" + context;
        }
        if (rp != null) {
            factory.setResourceProvider(rp);
        }
        if (app != null) {
            factory.setApplication(app);
        }
        if (invoker != null) {
            factory.setInvoker(invoker);
        }
        if (serviceBean != null) {
            factory.setServiceBean(serviceBean);
        } else {
            factory.setServiceClass(clazz);
        }
        server = factory.create();
        destination = (HttpDestination) server.getDestination();
        fireServerCreated(oldLoader);
    } finally {
        if (oldLoader != null) {
            CxfUtil.clearBusLoader(oldLoader);
        }
    }
}
Example 13
Project: vest-master  File: UriPathUtil.java View source code
/**
	 * Retrieve the context from the provided {@link Application}'s {@link ApplicationPath}.
	 *
	 * @param application with a {@link ApplicationPath} annotation.
	 * @return String of the path.
	 */
public static String getApplicationContext(Application application) {
    final Class<?> clazz = application.getClass();
    final ApplicationPath applicationPath = clazz.getAnnotation(ApplicationPath.class);
    String path = (applicationPath == null) ? "/" : applicationPath.value();
    if (path.length() < 1) {
        return "/";
    } else {
        return path.charAt(0) == '/' ? path : "/" + path;
    }
}
Example 14
Project: wildfly-master  File: JaxrsIntegrationProcessor.java View source code
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
        return;
    }
    if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
        return;
    }
    final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    final JBossWebMetaData webdata = warMetaData.getMergedJBossWebMetaData();
    final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
    if (resteasy == null)
        return;
    deploymentUnit.getDeploymentSubsystemModel(JaxrsExtension.SUBSYSTEM_NAME);
    final List<ParamValueMetaData> params = webdata.getContextParams();
    boolean entityExpandEnabled = false;
    if (params != null) {
        Iterator<ParamValueMetaData> it = params.iterator();
        while (it.hasNext()) {
            final ParamValueMetaData param = it.next();
            if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES)) {
                entityExpandEnabled = true;
            }
        }
    }
    //don't expand entity references by default
    if (!entityExpandEnabled) {
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES, "false");
    }
    final Map<ModuleIdentifier, ResteasyDeploymentData> attachmentMap = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
    final List<ResteasyDeploymentData> additionalData = new ArrayList<ResteasyDeploymentData>();
    final ModuleSpecification moduleSpec = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    if (moduleSpec != null && attachmentMap != null) {
        final Set<ModuleIdentifier> identifiers = new HashSet<ModuleIdentifier>();
        for (ModuleDependency dep : moduleSpec.getAllDependencies()) {
            //make sure we don't double up
            if (!identifiers.contains(dep.getIdentifier())) {
                identifiers.add(dep.getIdentifier());
                if (attachmentMap.containsKey(dep.getIdentifier())) {
                    additionalData.add(attachmentMap.get(dep.getIdentifier()));
                }
            }
        }
        resteasy.merge(additionalData);
    }
    if (!resteasy.getScannedResourceClasses().isEmpty()) {
        StringBuffer buf = null;
        for (String resource : resteasy.getScannedResourceClasses()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String resources = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS resource classes: %s", resources);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_RESOURCES, resources);
    }
    if (!resteasy.getScannedProviderClasses().isEmpty()) {
        StringBuffer buf = null;
        for (String provider : resteasy.getScannedProviderClasses()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(provider);
            } else {
                buf.append(",").append(provider);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS provider classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_PROVIDERS, providers);
    }
    if (!resteasy.getScannedJndiComponentResources().isEmpty()) {
        StringBuffer buf = null;
        for (String resource : resteasy.getScannedJndiComponentResources()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS jndi component resource classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_JNDI_RESOURCES, providers);
    }
    if (!resteasy.isUnwrappedExceptionsParameterSet()) {
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS, "javax.ejb.EJBException");
    }
    if (resteasy.hasBootClasses() || resteasy.isDispatcherCreated())
        return;
    // ignore any non-annotated Application class that doesn't have a servlet mapping
    Set<Class<? extends Application>> applicationClassSet = new HashSet<>();
    for (Class<? extends Application> clazz : resteasy.getScannedApplicationClasses()) {
        if (clazz.isAnnotationPresent(ApplicationPath.class) || servletMappingsExist(webdata, clazz.getName())) {
            applicationClassSet.add(clazz);
        }
    }
    // add default servlet
    if (applicationClassSet.size() == 0) {
        JBossServletMetaData servlet = new JBossServletMetaData();
        servlet.setName(JAX_RS_SERVLET_NAME);
        servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
        servlet.setAsyncSupported(true);
        addServlet(webdata, servlet);
        setServletMappingPrefix(webdata, JAX_RS_SERVLET_NAME, servlet);
    } else {
        for (Class<? extends Application> applicationClass : applicationClassSet) {
            String servletName = null;
            servletName = applicationClass.getName();
            JBossServletMetaData servlet = new JBossServletMetaData();
            // must load on startup for services like JSAPI to work
            servlet.setLoadOnStartup("" + 0);
            servlet.setName(servletName);
            servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
            servlet.setAsyncSupported(true);
            setServletInitParam(servlet, SERVLET_INIT_PARAM, applicationClass.getName());
            addServlet(webdata, servlet);
            if (!servletMappingsExist(webdata, servletName)) {
                try {
                    //no mappings, add our own
                    List<String> patterns = new ArrayList<String>();
                    //for some reason the spec requires this to be decoded
                    String pathValue = URLDecoder.decode(applicationClass.getAnnotation(ApplicationPath.class).value().trim(), "UTF-8");
                    if (!pathValue.startsWith("/")) {
                        pathValue = "/" + pathValue;
                    }
                    String prefix = pathValue;
                    if (pathValue.endsWith("/")) {
                        pathValue += "*";
                    } else {
                        pathValue += "/*";
                    }
                    patterns.add(pathValue);
                    setServletInitParam(servlet, "resteasy.servlet.mapping.prefix", prefix);
                    ServletMappingMetaData mapping = new ServletMappingMetaData();
                    mapping.setServletName(servletName);
                    mapping.setUrlPatterns(patterns);
                    if (webdata.getServletMappings() == null) {
                        webdata.setServletMappings(new ArrayList<ServletMappingMetaData>());
                    }
                    webdata.getServletMappings().add(mapping);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            } else {
                setServletMappingPrefix(webdata, servletName, servlet);
            }
        }
    }
    // suppress warning for EAR deployments, as we can't easily tell here the app is properly declared
    if (deploymentUnit.getParent() == null && (webdata.getServletMappings() == null || webdata.getServletMappings().isEmpty())) {
        JAXRS_LOGGER.noServletDeclaration(deploymentUnit.getName());
    }
}
Example 15
Project: core-master  File: MessageSenderTest.java View source code
@Deployment(testable = false)
public static WebArchive create() {
    return ShrinkWrap.create(WebArchive.class, Utils.getDeploymentNameAsHash(MessageSenderTest.class, Utils.ARCHIVE_TYPE.WAR)).addPackage(MessageSenderTest.class.getPackage()).setWebXML(new StringAsset("<web-app>" + "<display-name>jax</display-name>" + "<servlet-mapping>" + "<servlet-name>javax.ws.rs.core.Application</servlet-name>" + "<url-pattern>/rest/*</url-pattern>" + "</servlet-mapping>" + "</web-app>")).addAsWebInfResource(new BeansXml().decorators(MessageDecorator.class), "beans.xml");
}
Example 16
Project: Europeana-Cloud-master  File: UniqueIdentifierResourceTest.java View source code
/**
     * Configuration of the Spring context
     */
@Override
public Application configure() {
    return new ResourceConfig().registerClasses(CloudIdDoesNotExistExceptionMapper.class).registerClasses(CloudIdAlreadyExistExceptionMapper.class).registerClasses(DatabaseConnectionExceptionMapper.class).registerClasses(IdHasBeenMappedExceptionMapper.class).registerClasses(ProviderDoesNotExistExceptionMapper.class).registerClasses(RecordDatasetEmptyExceptionMapper.class).registerClasses(RecordDoesNotExistExceptionMapper.class).registerClasses(RecordExistsExceptionMapper.class).registerClasses(RecordIdDoesNotExistExceptionMapper.class).registerClasses(UniqueIdentifierResource.class).property("contextConfigLocation", "classpath:uir-context-test.xml");
}
Example 17
Project: fastjson-jaxrs-json-provider-master  File: ClassDefinitionFastJsonProviderTest.java View source code
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    ResourceConfig config = new ResourceConfig();
    Class<?>[] jsonTypes = { User.class };
    config.register(new FastJsonFeature()).register(new FastJsonProvider(jsonTypes));
    config.packages("com.colobu.fastjson", "com.colobu.test");
    return config;
}
Example 18
Project: jackson-jaxrs-propertyfiltering-master  File: Helper.java View source code
public Server startServer() throws Exception {
    Server server = new Server(0);
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);
    ServletHolder jaxrs = new ServletHolder(ServletContainer.class);
    jaxrs.setInitParameter("javax.ws.rs.Application", TestApplication.class.getName());
    ServletContextHandler mainHandler = new ServletContextHandler(contexts, "/", true, false);
    mainHandler.addServlet(jaxrs, "/*");
    server.setHandler(mainHandler);
    server.start();
    return server;
}
Example 19
Project: nuxeo-master  File: ApplicationFragment.java View source code
protected synchronized void createApp() {
    try {
        Object obj = bundle.loadClass(appClass).newInstance();
        if (obj instanceof ApplicationFactory) {
            app = ((ApplicationFactory) obj).getApplication(bundle, attrs);
        } else if (obj instanceof Application) {
            app = (Application) obj;
        } else {
            throw new IllegalArgumentException("Expecting an Application or ApplicationFactory class: " + appClass);
        }
    } catch (ReflectiveOperationExceptionIOException |  e) {
        String msg = "Cannot instantiate JAX-RS application " + appClass + " from bundle " + bundle.getSymbolicName();
        throw new RuntimeException(msg, e);
    }
}
Example 20
Project: ORCID-Source-master  File: SwaggerJSONResource.java View source code
protected synchronized Swagger scan(Application app) {
    Swagger swagger = null;
    Scanner scanner = ScannerFactory.getScanner();
    ModelConverters.getInstance().addConverter(new SwaggerModelConverter());
    LOGGER.debug("[SWAGGER] using scanner " + scanner);
    if (scanner != null) {
        SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint());
        swagger = (Swagger) context.getAttribute("swagger");
        Set<Class<?>> classes = scanner.classes();
        if (classes != null) {
            Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(context));
            swagger = reader.read(classes);
            if (scanner instanceof SwaggerConfig) {
                swagger = ((SwaggerConfig) scanner).configure(swagger);
            } else {
                SwaggerConfig configurator = (SwaggerConfig) context.getAttribute("reader");
                if (configurator != null) {
                    LOGGER.debug("configuring swagger with " + configurator);
                    configurator.configure(swagger);
                } else {
                    LOGGER.debug("no configurator");
                }
            }
            context.setAttribute("swagger", swagger);
        }
    }
    initialized = true;
    return swagger;
}
Example 21
Project: osgi-jax-rs-connector-master  File: JerseyContext.java View source code
private void registerServlet() throws ServletException, NamespaceException {
    ClassLoader original = getContextClassloader();
    try {
        Thread.currentThread().setContextClassLoader(Application.class.getClassLoader());
        httpService.registerServlet(rootPath, servletContainerBridge, getInitParams(), getHttpContext());
    } finally {
        resetContextClassloader(original);
    }
}
Example 22
Project: restlet-framework-java-master  File: JaxRsIntrospector.java View source code
/**
     * Constructor.
     * 
     * @param application
     *            An application to introspect.
     */
public static Definition getDefinition(Application application, String applicationName, List<Class> resources, Reference baseRef, boolean useSectionNamingPackageStrategy) {
    List<IntrospectionHelper> introspectionHelpers = IntrospectionUtils.getIntrospectionHelpers();
    Definition definition = new Definition();
    CollectInfo collectInfo = new CollectInfo();
    collectInfo.setUseSectionNamingPackageStrategy(useSectionNamingPackageStrategy);
    if (baseRef != null) {
        collectInfo.setApplicationPath(baseRef.getPath());
    } else if (application != null) {
        ApplicationPath applicationPath = application.getClass().getAnnotation(ApplicationPath.class);
        if (applicationPath != null) {
            collectInfo.setApplicationPath(applicationPath.value());
        }
    }
    List<Class> allResources = getAllResources(application, resources);
    scanResources(collectInfo, allResources, introspectionHelpers);
    if (applicationName != null) {
        collectInfo.setApplicationName(applicationName);
    } else if (application != null) {
        collectInfo.setApplicationName(application.getClass().getName());
    } else {
        collectInfo.setApplicationName("JAXRS-Application");
    }
    updateDefinitionContract(collectInfo, application, definition);
    Contract contract = definition.getContract();
    // add resources
    contract.setResources(collectInfo.getResources());
    // add representations
    contract.setRepresentations(collectInfo.getRepresentations());
    // add sections
    contract.setSections(collectInfo.getSections());
    addEndpoints(collectInfo.getApplicationPath(), definition);
    sortDefinition(definition);
    updateRepresentationsSectionsFromResources(definition);
    if (application != null) {
        for (IntrospectionHelper helper : introspectionHelpers) {
            helper.processDefinition(definition, application.getClass());
        }
    }
    return definition;
}
Example 23
Project: tajo-master  File: JerseyResourceDelegateUtil.java View source code
public static Response runJerseyResourceDelegate(JerseyResourceDelegate delegate, Application application, JerseyResourceDelegateContext context, Log log) {
    Application localApp = ResourceConfigUtil.getJAXRSApplication(application);
    if ((localApp != null) && (localApp instanceof ClientApplication)) {
        ClientApplication clientApplication = (ClientApplication) localApp;
        JerseyResourceDelegateContextKey<ClientApplication> clientApplicationKey = JerseyResourceDelegateContextKey.valueOf(ClientApplicationKey, ClientApplication.class);
        context.put(clientApplicationKey, clientApplication);
        MasterContext masterContext = clientApplication.getMasterContext();
        if (masterContext != null) {
            JerseyResourceDelegateContextKey<MasterContext> key = JerseyResourceDelegateContextKey.valueOf(MasterContextKey, MasterContext.class);
            context.put(key, masterContext);
            return delegate.run(context);
        } else {
            return ResourcesUtil.createExceptionResponse(log, "MasterContext is null.");
        }
    } else {
        return ResourcesUtil.createExceptionResponse(log, "Invalid injection on SessionsResource.");
    }
}
Example 24
Project: URS-master  File: HelloWorldTest.java View source code
@Override
protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig();
    ExampleApplicationConfiguration exampleApplicationConfiguration = new ExampleApplicationConfiguration();
    exampleApplicationConfiguration.setName("Ray");
    resourceConfig.registerInstances(new UrsusApplicationBinder(exampleApplicationConfiguration));
    resourceConfig.register(HelloWorldResource.class);
    return resourceConfig;
}
Example 25
Project: ursus-master  File: HelloWorldTest.java View source code
@Override
protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig();
    ExampleApplicationConfiguration exampleApplicationConfiguration = new ExampleApplicationConfiguration();
    exampleApplicationConfiguration.setName("Ray");
    resourceConfig.registerInstances(new UrsusApplicationBinder(exampleApplicationConfiguration));
    resourceConfig.register(HelloWorldResource.class);
    return resourceConfig;
}
Example 26
Project: Wink-master  File: WADLGenerator.java View source code
public Application generate(String baseURI, Set<Class<?>> classes) {
    /*
         * the idea is that classes comes from the Application subclass
         */
    Application app = new Application();
    if (classes == null || classes.isEmpty()) {
        return app;
    }
    Resources resources = new Resources();
    resources.setBase(baseURI);
    Set<ClassMetadata> metadataSet = buildClassMetdata(classes);
    resources.getResource().addAll(buildResources(metadataSet));
    app.getResources().add(resources);
    return app;
}
Example 27
Project: ameba-master  File: ConfigHelper.java View source code
@Override
public void onShutdown(final Container container) {
    final ApplicationHandler handler = container.getApplicationHandler();
    final InjectionManager injectionManager = handler.getInjectionManager();
    // Call @PreDestroy method on Application.
    injectionManager.preDestroy(getWrappedApplication(handler.getConfiguration()));
    // Shutdown ServiceLocator.
    injectionManager.shutdown();
}
Example 28
Project: bagri-master  File: QueryServiceTest.java View source code
@Override
protected Application configure() {
    queryMgr = mock(QueryManagement.class);
    mockRepo = mock(SchemaRepository.class);
    mockPro = mock(RepositoryProvider.class);
    when(mockPro.getRepository("client-id")).thenReturn(mockRepo);
    when(mockRepo.getQueryManagement()).thenReturn(queryMgr);
    BagriRestServer server = new BagriRestServer(mockPro, null, new Properties());
    return server.buildConfig();
}
Example 29
Project: cxf-master  File: JAXRSUtilsTest.java View source code
private Message createMessage() {
    ProviderFactory factory = ServerProviderFactory.getInstance();
    Message m = new MessageImpl();
    m.put("org.apache.cxf.http.case_insensitive_queries", false);
    Exchange e = new ExchangeImpl();
    m.setExchange(e);
    e.setInMessage(m);
    Endpoint endpoint = EasyMock.createMock(Endpoint.class);
    endpoint.getEndpointInfo();
    EasyMock.expectLastCall().andReturn(null).anyTimes();
    endpoint.get(Application.class.getName());
    EasyMock.expectLastCall().andReturn(null);
    endpoint.size();
    EasyMock.expectLastCall().andReturn(0).anyTimes();
    endpoint.isEmpty();
    EasyMock.expectLastCall().andReturn(true).anyTimes();
    endpoint.get(ServerProviderFactory.class.getName());
    EasyMock.expectLastCall().andReturn(factory).anyTimes();
    EasyMock.replay(endpoint);
    e.put(Endpoint.class, endpoint);
    return m;
}
Example 30
Project: dropwizard-master  File: JerseyIntegrationTest.java View source code
@Override
protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    final MetricRegistry metricRegistry = new MetricRegistry();
    final SessionFactoryFactory factory = new SessionFactoryFactory();
    final DataSourceFactory dbConfig = new DataSourceFactory();
    final HibernateBundle<?> bundle = mock(HibernateBundle.class);
    final Environment environment = mock(Environment.class);
    final LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class);
    when(environment.lifecycle()).thenReturn(lifecycleEnvironment);
    when(environment.metrics()).thenReturn(metricRegistry);
    dbConfig.setUrl("jdbc:hsqldb:mem:DbTest-" + System.nanoTime() + "?hsqldb.translate_dti_types=false");
    dbConfig.setUser("sa");
    dbConfig.setDriverClass("org.hsqldb.jdbcDriver");
    dbConfig.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS");
    this.sessionFactory = factory.build(bundle, environment, dbConfig, ImmutableList.of(Person.class));
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        session.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate();
        session.createNativeQuery("CREATE TABLE people (name varchar(100) primary key, email varchar(16), birthday timestamp with time zone)").executeUpdate();
        session.createNativeQuery("INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00+0:00')").executeUpdate();
        transaction.commit();
    }
    final DropwizardResourceConfig config = DropwizardResourceConfig.forTesting(new MetricRegistry());
    config.register(new UnitOfWorkApplicationListener("hr-db", sessionFactory));
    config.register(new PersonResource(new PersonDAO(sessionFactory)));
    config.register(new JacksonMessageBodyProvider(Jackson.newObjectMapper()));
    config.register(new PersistenceExceptionMapper());
    config.register(new DataExceptionMapper());
    config.register(new EmptyOptionalExceptionMapper());
    return config;
}
Example 31
Project: fastjson-master  File: TestIssue885.java View source code
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    ResourceConfig config = new ResourceConfig();
    //config.register(new FastJsonFeature()).register(FastJsonProvider.class);
    config.register(new FastJsonFeature()).register(new FastJsonProvider().setPretty(true));
    config.packages("com.alibaba.fastjson");
    return config;
}
Example 32
Project: incubator-brooklyn-master  File: ApiListingResource.java View source code
protected synchronized Swagger scan(Application app, WebConfig sc) {
    Swagger swagger = null;
    Scanner scanner = ScannerFactory.getScanner();
    LOGGER.debug("using scanner " + scanner);
    if (scanner != null) {
        SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint());
        swagger = (Swagger) context.getAttribute("swagger");
        Set<Class<?>> classes;
        if (scanner instanceof JaxrsScanner) {
            JaxrsScanner jaxrsScanner = (JaxrsScanner) scanner;
            classes = jaxrsScanner.classesFromContext(app, new ServletConfigAdapter(sc));
        } else {
            classes = scanner.classes();
        }
        if (classes != null) {
            Reader reader = new Reader(swagger, ReaderConfigUtils.getReaderConfig(context));
            swagger = reader.read(classes);
            if (scanner instanceof SwaggerConfig) {
                swagger = ((SwaggerConfig) scanner).configure(swagger);
            } else {
                SwaggerConfig configurator = (SwaggerConfig) context.getAttribute("reader");
                if (configurator != null) {
                    LOGGER.debug("configuring swagger with " + configurator);
                    configurator.configure(swagger);
                } else {
                    LOGGER.debug("no configurator");
                }
            }
            context.setAttribute("swagger", swagger);
        }
    }
    initialized = true;
    return swagger;
}
Example 33
Project: tesb-rt-se-master  File: ApplicationServer.java View source code
private static Server startApplication(Application app) {
    RuntimeDelegate delegate = RuntimeDelegate.getInstance();
    JAXRSServerFactoryBean bean = delegate.createEndpoint(app, JAXRSServerFactoryBean.class);
    bean.setAddress("http://localhost:8080" + bean.getAddress());
    bean.setStart(false);
    Server server = bean.create();
    JettyHTTPDestination dest = (JettyHTTPDestination) server.getDestination();
    JettyHTTPServerEngine engine = (JettyHTTPServerEngine) dest.getEngine();
    engine.setSessionSupport(true);
    server.start();
    return server;
}
Example 34
Project: web-framework-master  File: JerseyIntegrationTest.java View source code
@Override
protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    final MetricRegistry metricRegistry = new MetricRegistry();
    final SessionFactoryFactory factory = new SessionFactoryFactory();
    final DataSourceFactory dbConfig = new DataSourceFactory();
    final HibernateBundle<?> bundle = mock(HibernateBundle.class);
    final Environment environment = mock(Environment.class);
    final LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class);
    when(environment.lifecycle()).thenReturn(lifecycleEnvironment);
    when(environment.metrics()).thenReturn(metricRegistry);
    dbConfig.setUrl("jdbc:hsqldb:mem:DbTest-" + System.nanoTime() + "?hsqldb.translate_dti_types=false");
    dbConfig.setUser("sa");
    dbConfig.setDriverClass("org.hsqldb.jdbcDriver");
    dbConfig.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS");
    this.sessionFactory = factory.build(bundle, environment, dbConfig, ImmutableList.of(Person.class));
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        session.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate();
        session.createNativeQuery("CREATE TABLE people (name varchar(100) primary key, email varchar(16), birthday timestamp with time zone)").executeUpdate();
        session.createNativeQuery("INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00+0:00')").executeUpdate();
        transaction.commit();
    }
    final DropwizardResourceConfig config = DropwizardResourceConfig.forTesting(new MetricRegistry());
    config.register(new UnitOfWorkApplicationListener("hr-db", sessionFactory));
    config.register(new PersonResource(new PersonDAO(sessionFactory)));
    config.register(new JacksonMessageBodyProvider(Jackson.newObjectMapper()));
    config.register(new PersistenceExceptionMapper());
    config.register(new DataExceptionMapper());
    config.register(new EmptyOptionalExceptionMapper());
    return config;
}
Example 35
Project: spring-cloud-netflix-master  File: EurekaServerAutoConfiguration.java View source code
/**
	 * Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources
	 * required by the Eureka server.
	 */
@Bean
public javax.ws.rs.core.Application jerseyApplication(Environment environment, ResourceLoader resourceLoader) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment);
    // Filter to include only classes that have a particular annotation.
    //
    provider.addIncludeFilter(new AnnotationTypeFilter(Path.class));
    provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
    // Find classes in Eureka packages (or subpackages)
    //
    Set<Class<?>> classes = new HashSet<Class<?>>();
    for (String basePackage : EUREKA_PACKAGES) {
        Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
        for (BeanDefinition bd : beans) {
            Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(), resourceLoader.getClassLoader());
            classes.add(cls);
        }
    }
    // Construct the Jersey ResourceConfig
    //
    Map<String, Object> propsAndFeatures = new HashMap<String, Object>();
    propsAndFeatures.put(// Skip static content used by the webapp
    ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");
    DefaultResourceConfig rc = new DefaultResourceConfig(classes);
    rc.setPropertiesAndFeatures(propsAndFeatures);
    return rc;
}
Example 36
Project: apiman-master  File: GatewayServer.java View source code
/**
     * Configure the web application(s).
     * @param handlers
     * @throws Exception
     */
protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception {
    /* *************
         * Gateway
         * ************* */
    ServletContextHandler server = new ServletContextHandler(ServletContextHandler.SESSIONS);
    server.setContextPath("/");
    server.addEventListener(new WarGatewayBootstrapper());
    ServletHolder servlet = new ServletHolder(new WarGatewayServlet());
    server.addServlet(servlet, "/gateway/*");
    servlet = new ServletHolder(new HttpServletDispatcher());
    servlet.setInitParameter("javax.ws.rs.Application", TestGatewayApplication.class.getName());
    servlet.setInitParameter("resteasy.servlet.mapping.prefix", "/api");
    servlet.setInitOrder(1);
    server.addServlet(servlet, "/api/*");
    // Add the web contexts to jetty
    handlers.addHandler(server);
}
Example 37
Project: barge-master  File: BargeResourceTest.java View source code
@Override
protected Application configure() {
    raftService = mock(Raft.class);
    ResourceConfig resourceConfig = ResourceConfig.forApplication(new Application() {

        @Override
        public Set<Object> getSingletons() {
            return Sets.newHashSet((Object) new BargeResource(raftService, CLUSTER_CONFIG));
        }
    });
    resourceConfig.register(Jackson.customJacksonProvider());
    return resourceConfig;
}
Example 38
Project: brave-master  File: ITTracingFeature_Container.java View source code
@Override
public void contextInitialized(ServletContextEvent event) {
    deployment = new ResteasyDeployment();
    deployment.setApplication(new Application() {

        @Override
        public Set<Object> getSingletons() {
            return new LinkedHashSet<>(Arrays.asList(new TestResource(httpTracing), new CatchAllExceptions(), new TracingFeature(httpTracing)));
        }
    });
    ServletContext servletContext = event.getServletContext();
    ListenerBootstrap config = new ListenerBootstrap(servletContext);
    servletContext.setAttribute(ResteasyDeployment.class.getName(), deployment);
    deployment.getDefaultContextObjects().put(ResteasyConfiguration.class, config);
    config.createDeployment();
    deployment.start();
}
Example 39
Project: dropwizard-guicey-master  File: GuiceBindingsModule.java View source code
@Override
protected void configure() {
    jerseyToGuice(MultivaluedParameterExtractorProvider.class);
    jerseyToGuice(Application.class);
    jerseyToGuice(Providers.class);
    // request scoped objects, but hk will control their scope
    // must be used in guice only with Provider
    jerseyToGuice(UriInfo.class);
    jerseyToGuice(ResourceInfo.class);
    jerseyToGuice(HttpHeaders.class);
    jerseyToGuice(SecurityContext.class);
    jerseyToGuice(Request.class);
    jerseyToGuice(ContainerRequest.class);
    jerseyToGuice(AsyncContext.class);
    if (!guiceServletSupport) {
        // bind request and response objects when guice servlet module not registered
        // but this will work only for resources
        jerseyToGuice(HttpServletRequest.class);
        jerseyToGuice(HttpServletResponse.class);
    }
}
Example 40
Project: fluxtream-app-master  File: SwaggerBootstrapServlet.java View source code
private void reload() {
    System.out.println("ApplicationContext started, setting up REST API info");
    WebApplicationContext webContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    Configuration env = webContext.getBean(Configuration.class);
    final DefaultJaxrsScanner jaxrsScanner = new DefaultJaxrsScanner() {

        @Override
        public List<Class<?>> classesFromContext(Application app, ServletConfig sc) {
            final List<Class<?>> classes = super.classesFromContext(app, sc);
            return filterClasses(classes);
        }

        private List<Class<?>> filterClasses(final List<Class<?>> classes) {
            final Iterator<Class<?>> eachClass = classes.iterator();
            final ArrayList<Class<?>> filteredClasses = new ArrayList<Class<?>>();
            while (eachClass.hasNext()) {
                Class clazz = eachClass.next();
                //                    if (clazz.getName().indexOf("fluxtream")!=-1)
                //                        continue;
                filteredClasses.add(clazz);
            }
            return JavaConversions.asScalaBuffer(filteredClasses).toList();
        }

        @Override
        public List<Class<?>> classes() {
            final List<Class<?>> classes = super.classes();
            return filterClasses(classes);
        }
    };
    ScannerFactory.setScanner(jaxrsScanner);
    ClassReaders.setReader(new JerseyApiReader());
    String docsBaseURL = env.get("docsHomeBaseUrl") != null ? env.get("docsHomeBaseUrl") : env.get("homeBaseUrl");
    ApiInfo apiInfo = new ApiInfo("Fluxtream Public REST API", "", String.format("%shtml/privacyPolicy.html", docsBaseURL), "info@fluxtream.org", "Apache 2.0", "http://www.apache.org/licences/LICENSE-2.0.html");
    ConfigFactory.config().setBasePath(docsBaseURL + "api");
    ConfigFactory.config().setApiInfo(apiInfo);
    ConfigFactory.config().setApiVersion("v1");
    env.reload();
}
Example 41
Project: freedomotic-master  File: AbstractTest.java View source code
@Override
protected Application configure() {
    uuid = UUID.randomUUID().toString();
    representation = MediaType.APPLICATION_JSON_TYPE;
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    ResourceConfig rc = new ResourceConfig().packages(RestAPIv3.JERSEY_RESOURCE_PKG);
    rc.registerClasses(JacksonFeature.class);
    //  rc.registerClasses(MoxyXmlFeature.class);
    rc.register(ThrowableExceptionMapper.class);
    return rc;
}
Example 42
Project: jbosstools-webservices-master  File: JdtUtilsTestCase.java View source code
@Test
public void shouldResolveTypeHierarchyOnLibrariesWithSubclasses() throws CoreException {
    // preconditions
    IType type = projectMonitor.resolveType("javax.ws.rs.core.Application");
    Assert.assertNotNull("SourceType not found", type);
    // operation
    final ITypeHierarchy hierarchy = JdtUtils.resolveTypeHierarchy(type, type.getJavaProject(), true, new NullProgressMonitor());
    // verifications
    Assert.assertNotNull("SourceType hierarchy not found", hierarchy);
    Assert.assertEquals("SourceType hierarchy incomplete", 1, hierarchy.getSubtypes(type).length);
}
Example 43
Project: jersey-1.x-old-master  File: WebApplicationImpl.java View source code
private void _initiate(final ResourceConfig rc, final IoCComponentProviderFactory _provider) {
    if (rc == null) {
        throw new IllegalArgumentException("ResourceConfig instance MUST NOT be null");
    }
    if (initiated) {
        throw new ContainerException(ImplMessages.WEB_APP_ALREADY_INITIATED());
    }
    this.initiated = true;
    LOGGER.info("Initiating Jersey application, version '" + BuildId.getBuildId() + "'");
    // If there are components defined in jaxrs-components then
    // wrap resource config with appended set of classes
    Class<?>[] components = ServiceFinder.find("jersey-server-components").toClassArray();
    if (components.length > 0) {
        if (LOGGER.isLoggable(Level.INFO)) {
            StringBuilder b = new StringBuilder();
            b.append("Adding the following classes declared in META-INF/services/jersey-server-components to the resource configuration:");
            for (Class c : components) b.append('\n').append("  ").append(c);
            LOGGER.log(Level.INFO, b.toString());
        }
        this.resourceConfig = rc.clone();
        this.resourceConfig.getClasses().addAll(Arrays.asList(components));
    } else {
        this.resourceConfig = rc;
    }
    this.provider = _provider;
    this.providerFactories = new ArrayList<IoCComponentProviderFactory>(2);
    for (Object o : resourceConfig.getProviderSingletons()) {
        if (o instanceof IoCComponentProviderFactory) {
            providerFactories.add((IoCComponentProviderFactory) o);
        }
    }
    if (_provider != null)
        providerFactories.add(_provider);
    // Set up the component provider factory to be
    // used with non-resource class components
    this.cpFactory = (providerFactories.isEmpty()) ? new ProviderFactory(injectableFactory) : new IoCProviderFactory(injectableFactory, providerFactories);
    // Set up the resource component provider factory
    this.rcpFactory = (providerFactories.isEmpty()) ? new ResourceFactory(this.resourceConfig, this.injectableFactory) : new IoCResourceFactory(this.resourceConfig, this.injectableFactory, providerFactories);
    // Initiate IoCComponentProcessorFactoryInitializer
    for (IoCComponentProviderFactory f : providerFactories) {
        IoCComponentProcessorFactory cpf;
        if (f instanceof IoCComponentProcessorFactoryInitializer) {
            cpf = new ComponentProcessorFactoryImpl();
            IoCComponentProcessorFactoryInitializer i = (IoCComponentProcessorFactoryInitializer) f;
            i.init(cpf);
        }
    }
    this.resourceContext = new ResourceContext() {

        @Override
        public ExtendedUriInfo matchUriInfo(URI u) throws ContainerException {
            try {
                return handleMatchResourceRequest(u);
            } catch (ContainerException ex) {
                throw ex;
            } catch (WebApplicationException ex) {
                if (ex.getResponse().getStatus() == 404) {
                    return null;
                } else {
                    throw new ContainerException(ex);
                }
            } catch (RuntimeException ex) {
                throw new ContainerException(ex);
            }
        }

        @Override
        public Object matchResource(URI u) throws ContainerException {
            ExtendedUriInfo ui = matchUriInfo(u);
            return (ui != null) ? ui.getMatchedResources().get(0) : null;
        }

        @Override
        public <T> T matchResource(URI u, Class<T> c) throws ContainerException, ClassCastException {
            return c.cast(matchResource(u));
        }

        @Override
        public <T> T getResource(Class<T> c) {
            return c.cast(getResourceComponentProvider(c).getInstance(context));
        }
    };
    final ProviderServices providerServices = new ProviderServices(ServerSide.class, this.cpFactory, resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons());
    injectableFactory.add(new ContextInjectableProvider<ProviderServices>(ProviderServices.class, providerServices));
    injectableFactory.add(new ContextInjectableProvider<ResourceMethodCustomInvokerDispatchFactory>(ResourceMethodCustomInvokerDispatchFactory.class, new ResourceMethodCustomInvokerDispatchFactory(providerServices)));
    // Add injectable provider for @ParentRef
    injectableFactory.add(new InjectableProvider<ParentRef, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, ParentRef a, Type t) {
            if (!(t instanceof Class))
                return null;
            final Class target = ReflectionHelper.getDeclaringClass(cc.getAccesibleObject());
            final Class inject = (Class) t;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    final UriInfo ui = context.getUriInfo();
                    final List l = ui.getMatchedResources();
                    final Object parent = getParent(l, target);
                    if (parent == null)
                        return null;
                    try {
                        return inject.cast(parent);
                    } catch (ClassCastException ex) {
                        throw new ContainerException("The parent resource is expected to be of class " + inject.getName() + " but is of class " + parent.getClass().getName(), ex);
                    }
                }

                private Object getParent(List l, Class target) {
                    if (l.isEmpty()) {
                        return null;
                    } else if (l.size() == 1) {
                        return (l.get(0).getClass() == target) ? null : l.get(0);
                    } else {
                        return (l.get(0).getClass() == target) ? l.get(1) : l.get(0);
                    }
                }
            };
        }
    });
    // Add injectable provider for @Inject
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Undefined;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() == ComponentScope.PerRequest)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() != ComponentScope.Singleton)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    // Add injectable provider for @ResourceRef
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Undefined;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() == ComponentScope.PerRequest)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() != ComponentScope.Singleton)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    // Allow injection of features and properties
    injectableFactory.add(new ContextInjectableProvider<FeaturesAndProperties>(FeaturesAndProperties.class, resourceConfig));
    // Allow injection of resource config
    // Since the resourceConfig reference can change refer to the
    // reference directly.
    injectableFactory.add(new InjectableProvider<Context, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        @Override
        public Injectable<ResourceConfig> getInjectable(ComponentContext cc, Context a, Type t) {
            if (t != ResourceConfig.class)
                return null;
            return new Injectable<ResourceConfig>() {

                @Override
                public ResourceConfig getValue() {
                    return resourceConfig;
                }
            };
        }
    });
    // Allow injection of resource context
    injectableFactory.add(new ContextInjectableProvider<ResourceContext>(ResourceContext.class, resourceContext));
    // Configure the injectable factory with declared providers
    injectableFactory.configure(providerServices);
    boolean updateRequired = false;
    // Create application-declared Application instance as a component
    if (rc instanceof DeferredResourceConfig) {
        final DeferredResourceConfig drc = (DeferredResourceConfig) rc;
        // Check if resource config has already been cloned
        if (resourceConfig == drc)
            resourceConfig = drc.clone();
        final DeferredResourceConfig.ApplicationHolder da = drc.getApplication(cpFactory);
        resourceConfig.add(da.getApplication());
        updateRequired = true;
        injectableFactory.add(new ContextInjectableProvider<Application>(Application.class, da.getOriginalApplication()));
    } else {
        injectableFactory.add(new ContextInjectableProvider<FeaturesAndProperties>(Application.class, resourceConfig));
    }
    // Pipelined, decentralized configuration
    for (ResourceConfigurator configurator : providerServices.getProviders(ResourceConfigurator.class)) {
        configurator.configure(this.resourceConfig);
        updateRequired = true;
    }
    // Validate the resource config
    this.resourceConfig.validate();
    if (updateRequired) {
        // Check if application modified provider classes or singletons
        providerServices.update(resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons(), injectableFactory);
    }
    // Obtain all the templates
    this.templateContext = new TemplateFactory(providerServices);
    // Allow injection of template context
    injectableFactory.add(new ContextInjectableProvider<TemplateContext>(TemplateContext.class, templateContext));
    // Obtain all context resolvers
    final ContextResolverFactory crf = new ContextResolverFactory();
    // Obtain all the exception mappers
    this.exceptionFactory = new ExceptionMapperFactory();
    // Obtain all message body readers/writers
    this.bodyFactory = new MessageBodyFactory(providerServices, getFeaturesAndProperties().getFeature(FeaturesAndProperties.FEATURE_PRE_1_4_PROVIDER_PRECEDENCE));
    injectableFactory.add(new ContextInjectableProvider<MessageBodyWorkers>(MessageBodyWorkers.class, bodyFactory));
    // Injection of Providers
    this.providers = new Providers() {

        @Override
        public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> c, Type t, Annotation[] as, MediaType m) {
            return bodyFactory.getMessageBodyReader(c, t, as, m);
        }

        @Override
        public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> c, Type t, Annotation[] as, MediaType m) {
            return bodyFactory.getMessageBodyWriter(c, t, as, m);
        }

        @Override
        public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> c) {
            if (Throwable.class.isAssignableFrom(c))
                return exceptionFactory.find(c);
            else
                return null;
        }

        @Override
        public <T> ContextResolver<T> getContextResolver(Class<T> ct, MediaType m) {
            return crf.resolve(ct, m);
        }
    };
    injectableFactory.add(new ContextInjectableProvider<Providers>(Providers.class, providers));
    // Obtain all String readers
    this.stringReaderFactory = new StringReaderFactory();
    injectableFactory.add(new ContextInjectableProvider<StringReaderWorkers>(StringReaderWorkers.class, stringReaderFactory));
    MultivaluedParameterExtractorProvider mpep = new MultivaluedParameterExtractorFactory(stringReaderFactory);
    // Add the multi-valued parameter extractor provider
    injectableFactory.add(new ContextInjectableProvider<MultivaluedParameterExtractorProvider>(MultivaluedParameterExtractorProvider.class, mpep));
    // Add per-request-based injectable providers
    injectableFactory.add(new CookieParamInjectableProvider(mpep));
    injectableFactory.add(new HeaderParamInjectableProvider(mpep));
    injectableFactory.add(new HttpContextInjectableProvider());
    injectableFactory.add(new MatrixParamInjectableProvider(mpep));
    injectableFactory.add(new PathParamInjectableProvider(mpep));
    injectableFactory.add(new QueryParamInjectableProvider(mpep));
    injectableFactory.add(new FormParamInjectableProvider(mpep));
    // Create filter factory
    filterFactory = new FilterFactory(providerServices);
    // Initiate resource method dispatchers
    dispatcherFactory = ResourceMethodDispatcherFactory.create(providerServices);
    dispatchingListener = new DispatchingListenerProxy();
    // Initiate the WADL factory
    this.wadlFactory = new WadlFactory(resourceConfig, this.providers);
    WadlApplicationContextInjectionProxy wadlApplicationContextInjectionProxy = null;
    if (!resourceConfig.getFeature(ResourceConfig.FEATURE_DISABLE_WADL)) {
        wadlApplicationContextInjectionProxy = new WadlApplicationContextInjectionProxy();
        injectableFactory.add(new SingletonTypeInjectableProvider<Context, WadlApplicationContext>(WadlApplicationContext.class, wadlApplicationContextInjectionProxy) {
        });
        // In order for the application to properly marshall the Application
        // object we need to make sure that we provide a JAXBContext that
        // will work
        final WadlApplicationContext wac = wadlApplicationContextInjectionProxy;
        @Provider
        @Produces({ MediaTypes.WADL_STRING, MediaTypes.WADL_JSON_STRING, MediaType.APPLICATION_XML })
        class WadlContextResolver implements ContextResolver<JAXBContext> {

            @Override
            public JAXBContext getContext(Class<?> type) {
                if (com.sun.research.ws.wadl.Application.class.isAssignableFrom(type)) {
                    return wac.getJAXBContext();
                } else {
                    return null;
                }
            }
        }
        resourceConfig.getSingletons().add(new WadlContextResolver());
        // Update the provider services, so this is used
        providerServices.update(resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons(), injectableFactory);
    } else {
        injectableFactory.add(new SingletonTypeInjectableProvider<Context, WadlApplicationContext>(WadlApplicationContext.class, wadlApplicationContextInjectionProxy) {
        });
    }
    // Initiate filter
    filterFactory.init(resourceConfig);
    if (!resourceConfig.getMediaTypeMappings().isEmpty() || !resourceConfig.getLanguageMappings().isEmpty()) {
        boolean present = false;
        for (ContainerRequestFilter f : filterFactory.getRequestFilters()) {
            present |= f instanceof UriConnegFilter;
        }
        if (!present) {
            filterFactory.getRequestFilters().add(new UriConnegFilter(resourceConfig.getMediaTypeMappings(), resourceConfig.getLanguageMappings()));
        } else {
            LOGGER.warning("The media type and language mappings " + "declared in the ResourceConfig are ignored because " + "there is an instance of " + UriConnegFilter.class.getName() + "present in the list of request filters.");
        }
    }
    // Initiate context resolvers
    crf.init(providerServices, injectableFactory);
    // Initiate the exception mappers
    exceptionFactory.init(providerServices);
    // Initiate message body readers/writers
    bodyFactory.init();
    // Initiate string readers
    stringReaderFactory.init(providerServices);
    // Inject on all components
    Errors.setReportMissingDependentFieldOrMethod(true);
    cpFactory.injectOnAllComponents();
    cpFactory.injectOnProviderInstances(resourceConfig.getProviderSingletons());
    // web application is ready
    for (IoCComponentProviderFactory providerFactory : providerFactories) {
        if (providerFactory instanceof WebApplicationListener) {
            WebApplicationListener listener = (WebApplicationListener) providerFactory;
            listener.onWebApplicationReady();
        }
    }
    createAbstractResourceModelStructures();
    // Obtain all root resource rules
    RulesMap<UriRule> rootRules = new RootResourceUriRules(this, resourceConfig, wadlFactory, injectableFactory).getRules();
    this.rootsRule = new RootResourceClassesRule(rootRules);
    if (!resourceConfig.getFeature(ResourceConfig.FEATURE_DISABLE_WADL)) {
        wadlApplicationContextInjectionProxy.init(wadlFactory);
    }
    requestListener = MonitoringProviderFactory.createRequestListener(providerServices);
    responseListener = MonitoringProviderFactory.createResponseListener(providerServices);
    dispatchingListener.init(providerServices);
    callAbstractResourceModelListenersOnLoaded(providerServices);
    this.isTraceEnabled = resourceConfig.getFeature(ResourceConfig.FEATURE_TRACE) | resourceConfig.getFeature(ResourceConfig.FEATURE_TRACE_PER_REQUEST);
}
Example 44
Project: jersey-master  File: WadlResourceTest.java View source code
@Test
public void testWadl() throws Exception {
    final Response response = target("/application.wadl").request().get();
    assertThat(response.getStatus(), is(200));
    assertThat(response.hasEntity(), is(true));
    final Method method = (Method) // wadl
    response.readEntity(com.sun.research.ws.wadl.Application.class).getResources().get(0).getResource().get(// resource
    0).getMethodOrResource().get(// method
    0);
    // param
    final Param param = method.getRequest().getParam().get(0);
    // not interested in returned value, only whether we can compile.
    assertThat(param.isRequired(), notNullValue());
    assertThat(param.isRepeating(), notNullValue());
}
Example 45
Project: jersey-old-master  File: WebApplicationImpl.java View source code
private void _initiate(final ResourceConfig rc, final IoCComponentProviderFactory _provider) {
    if (rc == null) {
        throw new IllegalArgumentException("ResourceConfig instance MUST NOT be null");
    }
    if (initiated) {
        throw new ContainerException(ImplMessages.WEB_APP_ALREADY_INITIATED());
    }
    this.initiated = true;
    LOGGER.info("Initiating Jersey application, version '" + BuildId.getBuildId() + "'");
    // If there are components defined in jaxrs-components then
    // wrap resource config with appended set of classes
    Class<?>[] components = ServiceFinder.find("jersey-server-components").toClassArray();
    if (components.length > 0) {
        if (LOGGER.isLoggable(Level.INFO)) {
            StringBuilder b = new StringBuilder();
            b.append("Adding the following classes declared in META-INF/services/jersey-server-components to the resource configuration:");
            for (Class c : components) b.append('\n').append("  ").append(c);
            LOGGER.log(Level.INFO, b.toString());
        }
        this.resourceConfig = rc.clone();
        this.resourceConfig.getClasses().addAll(Arrays.asList(components));
    } else {
        this.resourceConfig = rc;
    }
    this.provider = _provider;
    this.providerFactories = new ArrayList<IoCComponentProviderFactory>(2);
    for (Object o : resourceConfig.getProviderSingletons()) {
        if (o instanceof IoCComponentProviderFactory) {
            providerFactories.add((IoCComponentProviderFactory) o);
        }
    }
    if (_provider != null)
        providerFactories.add(_provider);
    // Set up the component provider factory to be
    // used with non-resource class components
    this.cpFactory = (providerFactories.isEmpty()) ? new ProviderFactory(injectableFactory) : new IoCProviderFactory(injectableFactory, providerFactories);
    // Set up the resource component provider factory
    this.rcpFactory = (providerFactories.isEmpty()) ? new ResourceFactory(this.resourceConfig, this.injectableFactory) : new IoCResourceFactory(this.resourceConfig, this.injectableFactory, providerFactories);
    // Initiate IoCComponentProcessorFactoryInitializer
    for (IoCComponentProviderFactory f : providerFactories) {
        IoCComponentProcessorFactory cpf = null;
        if (f instanceof IoCComponentProcessorFactoryInitializer) {
            if (cpf == null) {
                cpf = new ComponentProcessorFactoryImpl();
            }
            IoCComponentProcessorFactoryInitializer i = (IoCComponentProcessorFactoryInitializer) f;
            i.init(cpf);
        }
    }
    this.resourceContext = new ResourceContext() {

        public ExtendedUriInfo matchUriInfo(URI u) throws ContainerException {
            try {
                return handleMatchResourceRequest(u);
            } catch (ContainerException ex) {
                throw ex;
            } catch (WebApplicationException ex) {
                if (ex.getResponse().getStatus() == 404) {
                    return null;
                } else {
                    throw new ContainerException(ex);
                }
            } catch (RuntimeException ex) {
                throw new ContainerException(ex);
            }
        }

        public Object matchResource(URI u) throws ContainerException {
            ExtendedUriInfo ui = matchUriInfo(u);
            return (ui != null) ? ui.getMatchedResources().get(0) : null;
        }

        public <T> T matchResource(URI u, Class<T> c) throws ContainerException, ClassCastException {
            return c.cast(matchResource(u));
        }

        public <T> T getResource(Class<T> c) {
            return c.cast(getResourceComponentProvider(c).getInstance(context));
        }
    };
    ProviderServices providerServices = new ProviderServices(ServerSide.class, this.cpFactory, resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons());
    // Add injectable provider for @ParentRef
    injectableFactory.add(new InjectableProvider<ParentRef, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, ParentRef a, Type t) {
            if (!(t instanceof Class))
                return null;
            final Class target = ReflectionHelper.getDeclaringClass(cc.getAccesibleObject());
            final Class inject = (Class) t;
            return new Injectable<Object>() {

                public Object getValue() {
                    final UriInfo ui = context.getUriInfo();
                    final List l = ui.getMatchedResources();
                    final Object parent = getParent(l, target);
                    if (parent == null)
                        return null;
                    try {
                        return inject.cast(parent);
                    } catch (ClassCastException ex) {
                        throw new ContainerException("The parent resource is expected to be of class " + inject.getName() + " but is of class " + l.get(1).getClass().getName(), ex);
                    }
                }

                private Object getParent(List l, Class target) {
                    if (l.isEmpty()) {
                        return null;
                    } else if (l.size() == 1) {
                        return (l.get(0).getClass() == target) ? null : l.get(0);
                    } else {
                        return (l.get(0).getClass() == target) ? l.get(1) : l.get(0);
                    }
                }
            };
        }
    });
    // Add injectable provider for @Inject
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            return new Injectable<Object>() {

                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.Undefined;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() == ComponentScope.PerRequest)
                return null;
            return new Injectable<Object>() {

                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() != ComponentScope.Singleton)
                return null;
            return new Injectable<Object>() {

                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    // Add injectable provider for @ResourceRef
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            return new Injectable<Object>() {

                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.Undefined;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() == ComponentScope.PerRequest)
                return null;
            return new Injectable<Object>() {

                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() != ComponentScope.Singleton)
                return null;
            return new Injectable<Object>() {

                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    // Allow injection of features and properties
    injectableFactory.add(new ContextInjectableProvider<FeaturesAndProperties>(FeaturesAndProperties.class, resourceConfig));
    // Allow injection of resource config
    // Since the resourceConfig reference can change refer to the
    // reference directly.
    injectableFactory.add(new InjectableProvider<Context, Type>() {

        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        public Injectable<ResourceConfig> getInjectable(ComponentContext cc, Context a, Type t) {
            if (t != ResourceConfig.class)
                return null;
            return new Injectable<ResourceConfig>() {

                public ResourceConfig getValue() {
                    return resourceConfig;
                }
            };
        }
    });
    // Allow injection of resource context
    injectableFactory.add(new ContextInjectableProvider<ResourceContext>(ResourceContext.class, resourceContext));
    // Configure the injectable factory with declared providers
    injectableFactory.configure(providerServices);
    boolean updateRequired = false;
    // Create application-declared Application instance as a component
    if (rc instanceof DeferredResourceConfig) {
        final DeferredResourceConfig drc = (DeferredResourceConfig) rc;
        // Check if resource config has already been cloned
        if (resourceConfig == drc)
            resourceConfig = drc.clone();
        final DeferredResourceConfig.ApplicationHolder da = drc.getApplication(cpFactory);
        resourceConfig.add(da.getApplication());
        updateRequired = true;
        injectableFactory.add(new ContextInjectableProvider<Application>(Application.class, da.getOriginalApplication()));
    } else {
        injectableFactory.add(new ContextInjectableProvider<FeaturesAndProperties>(Application.class, resourceConfig));
    }
    // Pipelined, decentralized configuration
    for (ResourceConfigurator configurator : providerServices.getProviders(ResourceConfigurator.class)) {
        configurator.configure(this.resourceConfig);
        updateRequired = true;
    }
    // Validate the resource config
    this.resourceConfig.validate();
    if (updateRequired) {
        // Check if application modified provider classes or singletons
        providerServices.update(resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons(), injectableFactory);
    }
    // Obtain all the templates
    this.templateContext = new TemplateFactory(providerServices);
    // Allow injection of template context
    injectableFactory.add(new ContextInjectableProvider<TemplateContext>(TemplateContext.class, templateContext));
    // Obtain all context resolvers
    final ContextResolverFactory crf = new ContextResolverFactory();
    // Obtain all the exception mappers
    this.exceptionFactory = new ExceptionMapperFactory();
    // Obtain all message body readers/writers
    this.bodyFactory = new MessageBodyFactory(providerServices, getFeaturesAndProperties().getFeature(FeaturesAndProperties.FEATURE_PRE_1_4_PROVIDER_PRECEDENCE));
    injectableFactory.add(new ContextInjectableProvider<MessageBodyWorkers>(MessageBodyWorkers.class, bodyFactory));
    // Injection of Providers
    this.providers = new Providers() {

        public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> c, Type t, Annotation[] as, MediaType m) {
            return bodyFactory.getMessageBodyReader(c, t, as, m);
        }

        public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> c, Type t, Annotation[] as, MediaType m) {
            return bodyFactory.getMessageBodyWriter(c, t, as, m);
        }

        public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> c) {
            if (Throwable.class.isAssignableFrom(c))
                return exceptionFactory.find((Class<Throwable>) c);
            else
                return null;
        }

        public <T> ContextResolver<T> getContextResolver(Class<T> ct, MediaType m) {
            return crf.resolve(ct, m);
        }
    };
    injectableFactory.add(new ContextInjectableProvider<Providers>(Providers.class, providers));
    // Obtain all String readers
    this.stringReaderFactory = new StringReaderFactory();
    injectableFactory.add(new ContextInjectableProvider<StringReaderWorkers>(StringReaderWorkers.class, stringReaderFactory));
    MultivaluedParameterExtractorProvider mpep = new MultivaluedParameterExtractorFactory(stringReaderFactory);
    // Add the multi-valued parameter extractor provider
    injectableFactory.add(new ContextInjectableProvider<MultivaluedParameterExtractorProvider>(MultivaluedParameterExtractorProvider.class, mpep));
    // Add per-request-based injectable providers
    injectableFactory.add(new CookieParamInjectableProvider(mpep));
    injectableFactory.add(new HeaderParamInjectableProvider(mpep));
    injectableFactory.add(new HttpContextInjectableProvider());
    injectableFactory.add(new MatrixParamInjectableProvider(mpep));
    injectableFactory.add(new PathParamInjectableProvider(mpep));
    injectableFactory.add(new QueryParamInjectableProvider(mpep));
    injectableFactory.add(new FormParamInjectableProvider(mpep));
    // Create filter factory
    filterFactory = new FilterFactory(providerServices);
    // Initiate resource method dispatchers
    dispatcherFactory = new ResourceMethodDispatcherFactory(providerServices);
    // Initiate the WADL factory
    this.wadlFactory = new WadlFactory(resourceConfig);
    // Initiate filter
    filterFactory.init(resourceConfig);
    if (!resourceConfig.getMediaTypeMappings().isEmpty() || !resourceConfig.getLanguageMappings().isEmpty()) {
        boolean present = false;
        for (ContainerRequestFilter f : filterFactory.getRequestFilters()) {
            present |= f instanceof UriConnegFilter;
        }
        if (!present) {
            filterFactory.getRequestFilters().add(new UriConnegFilter(resourceConfig.getMediaTypeMappings(), resourceConfig.getLanguageMappings()));
        } else {
            LOGGER.warning("The media type and language mappings " + "declared in the ResourceConfig are ignored because " + "there is an instance of " + UriConnegFilter.class.getName() + "present in the list of request filters.");
        }
    }
    // Initiate context resolvers
    crf.init(providerServices, injectableFactory);
    // Initiate the exception mappers
    exceptionFactory.init(providerServices);
    // Initiate message body readers/writers
    bodyFactory.init();
    // Initiate string readers
    stringReaderFactory.init(providerServices);
    // Inject on all components
    Errors.setReportMissingDependentFieldOrMethod(true);
    cpFactory.injectOnAllComponents();
    cpFactory.injectOnProviderInstances(resourceConfig.getProviderSingletons());
    // web application is ready
    for (IoCComponentProviderFactory providerFactory : providerFactories) {
        if (providerFactory instanceof WebApplicationListener) {
            WebApplicationListener listener = (WebApplicationListener) providerFactory;
            listener.onWebApplicationReady();
        }
    }
    // Obtain all root resource rules
    RulesMap<UriRule> rootRules = new RootResourceUriRules(this, resourceConfig, wadlFactory, injectableFactory).getRules();
    this.rootsRule = new RootResourceClassesRule(rootRules);
    this.isTraceEnabled = resourceConfig.getFeature(ResourceConfig.FEATURE_TRACE) | resourceConfig.getFeature(ResourceConfig.FEATURE_TRACE_PER_REQUEST);
}
Example 46
Project: jersey2-guice-master  File: JerseyGuiceModule.java View source code
@Override
protected void configure() {
    Provider<Injector> injector = getProvider(Injector.class);
    bind(ServiceLocator.class).toProvider(new ServiceLocatorProvider(injector, locator)).in(Singleton.class);
    Provider<ServiceLocator> provider = getProvider(ServiceLocator.class);
    bind(Application.class).toProvider(new JerseyProvider<>(provider, Application.class));
    bind(Providers.class).toProvider(new JerseyProvider<>(provider, Providers.class));
    bind(UriInfo.class).toProvider(new JerseyProvider<>(provider, UriInfo.class)).in(RequestScoped.class);
    bind(HttpHeaders.class).toProvider(new JerseyProvider<>(provider, HttpHeaders.class)).in(RequestScoped.class);
    bind(SecurityContext.class).toProvider(new JerseyProvider<>(provider, SecurityContext.class)).in(RequestScoped.class);
    bind(Request.class).toProvider(new JerseyProvider<>(provider, Request.class)).in(RequestScoped.class);
}
Example 47
Project: liferay-ide-master  File: NewLiferayComponentRestOperation.java View source code
@Override
protected List<String> getImports() {
    List<String> imports = new ArrayList<String>();
    imports.add("com.liferay.portal.kernel.model.User");
    imports.add("com.liferay.portal.kernel.service.UserLocalService");
    imports.add("java.util.Collections");
    imports.add("java.util.Set");
    imports.add("javax.ws.rs.GET");
    imports.add("javax.ws.rs.Path");
    imports.add("javax.ws.rs.Produces");
    imports.add("javax.ws.rs.core.Application");
    imports.add("org.osgi.service.component.annotations.Reference");
    imports.addAll(super.getImports());
    return imports;
}
Example 48
Project: minnal-master  File: ApplicationEnhancerTest.java View source code
@BeforeMethod
public void setup() {
    application = mock(Application.class);
    rc1 = ResourceMetaDataProvider.instance().getResourceMetaData(DummyResource.class);
    rc2 = ResourceMetaDataProvider.instance().getResourceMetaData(DummyResource1.class);
    when(application.getClasses()).thenReturn(Sets.newHashSet(DummyResource.class, DummyResource1.class));
    namingStrategy = new UnderscoreNamingStrategy();
    enhancer = spy(new ApplicationEnhancer(application, namingStrategy, new String[] { "org.minnal.instrument" }, new String[] { "org.minnal.instrument" }));
}
Example 49
Project: nuxeo-filesystem-connectors-master  File: WebDavServerFeature.java View source code
private void startGrizzly() {
    // static content is linked from here
    String path = "src/main/resources/www";
    gws = new GrizzlyWebServer(PORT, path);
    ServletAdapter jerseyAdapter = new ServletAdapter();
    Application app = new org.nuxeo.ecm.webdav.Application();
    ApplicationAdapter conf = new ApplicationAdapter(app);
    conf.getFeatures().put(ResourceConfig.FEATURE_MATCH_MATRIX_PARAMS, Boolean.TRUE);
    jerseyAdapter.setServletInstance(new ServletContainer(conf));
    jerseyAdapter.addRootFolder(path);
    jerseyAdapter.setHandleStaticResources(true);
    jerseyAdapter.setContextPath("");
    // session cleanup
    jerseyAdapter.addFilter(new RequestContextFilter(), "RequestContextFilter", null);
    jerseyAdapter.addFilter(new SessionCleanupFilter(), "SessionCleanupFilter", null);
    jerseyAdapter.addFilter(new NuxeoAuthenticationFilter(), "NuxeoAuthenticationFilter", null);
    jerseyAdapter.addFilter(new WebEngineFilter(), "WebEngineFilter", null);
    if (DEBUG) {
        jerseyAdapter.addInitParameter("com.sun.jersey.spi.container.ContainerRequestFilters", "com.sun.jersey.api.container.filter.LoggingFilter");
        jerseyAdapter.addInitParameter("com.sun.jersey.spi.container.ContainerResponseFilters", "com.sun.jersey.api.container.filter.LoggingFilter");
    }
    jerseyAdapter.addInitParameter("com.sun.jersey.config.feature.logging.DisableEntitylogging", "true");
    gws.addGrizzlyAdapter(jerseyAdapter, new String[] { "" });
    // let Grizzly run
    try {
        gws.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 50
Project: OG-Platform-master  File: OpenGammaSpringServlet.java View source code
@Override
protected void initiate(ResourceConfig rc, WebApplication wa) {
    Application app = createApplication();
    try {
        // initialize the Jetty system
        rc.add(app);
        wa.initiate(rc, new SpringComponentProviderFactory(rc, getContext()));
    } catch (RuntimeException ex) {
        s_logger.error("Exception occurred during intialization", ex);
        throw ex;
    }
}
Example 51
Project: oreva-master  File: ODataCxfServer.java View source code
@Override
public ODataServer start() {
    if (odataApp == null)
        throw new RuntimeException("ODataApplication not set");
    URL url;
    try {
        url = new URL(appBaseUri);
    } catch (MalformedURLException e) {
        throw Throwables.propagate(e);
    }
    CXFNonSpringJaxrsServlet odataServlet = new CXFNonSpringJaxrsServlet();
    ServletHolder odataServletHolder = new ServletHolder(odataServlet);
    odataServletHolder.setInitParameter("javax.ws.rs.Application", odataApp.getCanonicalName());
    ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.addServlet(odataServletHolder, normalizePath(url.getPath()) + "/*");
    if (rootApp != null) {
        CXFNonSpringJaxrsServlet rootServlet = new CXFNonSpringJaxrsServlet();
        ServletHolder rootServletHolder = new ServletHolder(rootServlet);
        rootServletHolder.setInitParameter("javax.ws.rs.Application", rootApp.getCanonicalName());
        contextHandler.addServlet(rootServletHolder, "/*");
    }
    if (jettySecurityHandler != null)
        contextHandler.setSecurityHandler(jettySecurityHandler);
    server = new Server(url.getPort());
    server.setHandler(getHandlerCollection(contextHandler));
    try {
        server.start();
        return this;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
Example 52
Project: platform-api-master  File: ProjectServiceTest.java View source code
@BeforeMethod
public void setUp() throws Exception {
    final EventService eventService = new EventService();
    VirtualFileSystemRegistry vfsRegistry = new VirtualFileSystemRegistry();
    final MemoryFileSystemProvider memoryFileSystemProvider = new MemoryFileSystemProvider(workspace, eventService, new VirtualFileSystemUserContext() {

        @Override
        public VirtualFileSystemUser getVirtualFileSystemUser() {
            return new VirtualFileSystemUser(vfsUser, vfsUserGroups);
        }
    }, vfsRegistry);
    MemoryMountPoint mmp = (MemoryMountPoint) memoryFileSystemProvider.getMountPoint(true);
    vfsRegistry.registerProvider(workspace, memoryFileSystemProvider);
    // PTs for test
    ProjectType chuck = new ProjectType("chuck_project_type", "chuck_project_type", true, false) {

        {
            addConstantDefinition("x", "attr description", new AttributeValue(Arrays.asList("a", "b")));
            addVariableDefinition("y", "descr", false);
        }
    };
    Set<ProjectType> projTypes = new HashSet<>();
    projTypes.add(new MyProjType());
    projTypes.add(chuck);
    ProjectTypeRegistry ptRegistry = new ProjectTypeRegistry(projTypes);
    phRegistry = new ProjectHandlerRegistry(new HashSet<ProjectHandler>());
    pm = new DefaultProjectManager(vfsRegistry, eventService, ptRegistry, phRegistry);
    pm.createProject(workspace, "my_project", new ProjectConfig("my test project", "my_project_type", new HashMap<String, AttributeValue>(), null, null, null), null, null);
    DependencySupplierImpl dependencies = new DependencySupplierImpl();
    importerRegistry = new ProjectImporterRegistry(Collections.<ProjectImporter>emptySet());
    HashSet<ProjectTypeResolver> resolvers = new HashSet<>();
    resolvers.add(new ProjectTypeResolver() {

        @Override
        public boolean resolve(FolderEntry projectFolder) throws ServerException, ValueStorageException, InvalidValueException, ProjectTypeConstraintException {
            ProjectConfig conf = new ProjectConfig("my proj", "my_project_type");
            Project project = new Project(projectFolder, pm);
            project.updateConfig(conf);
            return true;
        }
    });
    resolverRegistry = new ProjectTypeResolverRegistry(resolvers);
    dependencies.addComponent(ProjectTypeRegistry.class, ptRegistry);
    dependencies.addComponent(UserDao.class, userDao);
    dependencies.addComponent(ProjectManager.class, pm);
    dependencies.addComponent(ProjectImporterRegistry.class, importerRegistry);
    dependencies.addComponent(ProjectHandlerRegistry.class, phRegistry);
    dependencies.addComponent(SearcherProvider.class, mmp.getSearcherProvider());
    dependencies.addComponent(ProjectTypeResolverRegistry.class, resolverRegistry);
    dependencies.addComponent(EventService.class, eventService);
    ResourceBinder resources = new ResourceBinderImpl();
    ProviderBinder providers = new ApplicationProviderBinder();
    EverrestProcessor processor = new EverrestProcessor(resources, providers, dependencies, new EverrestConfiguration(), null);
    launcher = new ResourceLauncher(processor);
    processor.addApplication(new Application() {

        @Override
        public Set<Class<?>> getClasses() {
            return java.util.Collections.<Class<?>>singleton(ProjectService.class);
        }

        @Override
        public Set<Object> getSingletons() {
            return new HashSet<>(Arrays.asList(new CodenvyJsonProvider(new HashSet<>(Arrays.asList(ContentStream.class))), new ContentStreamWriter(), new ApiExceptionMapper()));
        }
    });
    ApplicationContextImpl.setCurrent(new ApplicationContextImpl(null, null, ProviderBinder.getInstance()));
    env = org.eclipse.che.commons.env.EnvironmentContext.getCurrent();
    env.setUser(new UserImpl(vfsUser, vfsUser, "dummy_token", vfsUserGroups, false));
    env.setWorkspaceName(workspace);
    env.setWorkspaceId(workspace);
}
Example 53
Project: airlift-master  File: JaxrsModule.java View source code
@Provides
public Application createJaxRsApplication(@JaxrsResource Set<Object> jaxRsSingletons, @JaxrsResource Set<JaxrsBinding> jaxrsBinding, Injector injector) {
    // detect jax-rs services that are bound into Guice, but not explicitly exported
    Set<Key<?>> missingBindings = new HashSet<>();
    ImmutableSet.Builder<Object> singletons = ImmutableSet.builder();
    singletons.addAll(jaxRsSingletons);
    while (injector != null) {
        for (Entry<Key<?>, Binding<?>> entry : injector.getBindings().entrySet()) {
            Key<?> key = entry.getKey();
            if (isJaxRsBinding(key) && !jaxrsBinding.contains(new JaxrsBinding(key))) {
                if (requireExplicitBindings) {
                    missingBindings.add(key);
                } else {
                    log.warn("Jax-rs service %s is not explicitly bound using the JaxrsBinder", key);
                    Object jaxRsSingleton = entry.getValue().getProvider().get();
                    singletons.add(jaxRsSingleton);
                }
            }
        }
        injector = injector.getParent();
    }
    checkState(!requireExplicitBindings || missingBindings.isEmpty(), "Jax-rs services must be explicitly bound using the JaxRsBinder: ", missingBindings);
    return new JaxRsApplication(singletons.build());
}
Example 54
Project: alchemy-rest-client-generator-master  File: AlchemyRestClientFactoryTest.java View source code
/*
     * (non-Javadoc)
     * @see org.glassfish.jersey.test.JerseyTest#configure()
     */
@Override
protected Application configure() {
    final ResourceConfig application = new ResourceConfig(TestWebserviceWithPath.class, TestWebserviceWithPutDelete.class, TestWebserviceMultipart.class, TestWebserviceExceptionHandling.class, JacksonJsonProvider.class);
    final Injector injector = Guice.createInjector(new ClientModule(), new ExceptionObjectMapperModule());
    // register multi part feature.
    application.register(MultiPartFeature.class);
    // register the application mapper.
    application.register(injector.getInstance(TestExceptionMapper.class));
    return application;
}
Example 55
Project: confit-master  File: JettyServer.java View source code
public static void start() {
    if (RUNNING.get()) {
        return;
    }
    server = new Server(8080);
    ResteasyJacksonProvider provider = new ResteasyJacksonProvider();
    provider.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ResteasyDeployment deployment = new ResteasyDeployment();
    deployment.setApplication(new JaxrsApplication());
    ResteasyProviderFactory resteasyFactory = ResteasyProviderFactory.getInstance();
    resteasyFactory.registerProviderInstance(provider);
    deployment.setProviderFactory(resteasyFactory);
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletContextHandler.setAttribute(ResteasyDeployment.class.getName(), deployment);
    servletContextHandler.setContextPath("/");
    ServletHolder h = new ServletHolder(new HttpServletDispatcher());
    h.setInitParameter("javax.ws.rs.Application", JaxrsApplication.class.getName());
    servletContextHandler.addServlet(h, JaxrsConfigEndpoint.PATH + "/*");
    HandlerList handlers = new HandlerList();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(false);
    File root = new File(computeMavenProjectRoot(JaxrsConfigEndpoint.class), "src/main/resources/html");
    resourceHandler.setResourceBase(root.getAbsolutePath());
    handlers.addHandler(resourceHandler);
    handlers.addHandler(servletContextHandler);
    server.setHandler(handlers);
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    RUNNING.set(true);
    ShutdownHook.install(new Thread() {

        @Override
        public void run() {
            try {
                server.stop();
                RUNNING.set(false);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    });
}
Example 56
Project: ff-master  File: SecuredFF4JResourceTestIT.java View source code
@Override
protected Application configure() {
    // Initialisation of clientss
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonJsonProvider.class);
    clientConfig.register(FF4jJacksonMapper.class);
    setClient(ClientBuilder.newClient(clientConfig));
    return new SecuredJersey2Application(ff4j);
}
Example 57
Project: ff4j-master  File: SecuredFF4JResourceTestIT.java View source code
@Override
protected Application configure() {
    // Initialisation of clientss
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(JacksonJsonProvider.class);
    clientConfig.register(FF4jJacksonMapper.class);
    setClient(ClientBuilder.newClient(clientConfig));
    return new SecuredJersey2Application(ff4j);
}
Example 58
Project: geo-platform-master  File: GPServiceJsonConfig.java View source code
@Bean(initMethod = "create")
@Required
public static JAXRSServerFactoryBean geoplatformServiceJSON(@Qualifier(value = "geoPlatformService") GeoPlatformService geoPlatformService, @Qualifier(value = "gpJsonCoreApplication") Application gpJsonCoreApplication, @Value("configurator{cxf_rest_provider_type}") GPRestProviderType providerType, @Qualifier(value = "gpCoreSwaggerRestConfiguration") GPSwaggerRestConfiguration gpCoreSwaggerRestConfiguration, @Qualifier(value = "gpCrossResourceSharingFilter") CrossOriginResourceSharingFilter gpCrossResourceSharingFilter, @Qualifier(value = "serverLoggingInInterceptorBean") LoggingInInterceptor serverLogInInterceptor, @Qualifier(value = "serverLoggingOutInterceptorBean") LoggingOutInterceptor serverLogOutInterceptor) {
    logger.debug("\n\n#####################GP_CORE_SWAGGER_CONFIGURED : {}\n\n", gpCoreSwaggerRestConfiguration.isSwaggerConfigured());
    List<Object> serviceBeans;
    List<? extends Object> providers;
    if (gpCoreSwaggerRestConfiguration.isSwaggerConfigured()) {
        serviceBeans = Arrays.asList(new Object[] { geoPlatformService, gpCoreSwaggerRestConfiguration.getSwaggerApiListingResource() });
        providers = Arrays.asList(new Object[] { createProvider(providerType), gpCoreSwaggerRestConfiguration.getSwaggerResourceWriter(), new GPExceptionFaultMapper(), gpCrossResourceSharingFilter });
    } else {
        serviceBeans = Arrays.asList(new Object[] { geoPlatformService });
        providers = Arrays.asList(new Object[] { createProvider(providerType), new GPExceptionFaultMapper(), gpCrossResourceSharingFilter });
    }
    JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint(gpJsonCoreApplication, JAXRSServerFactoryBean.class);
    factory.setServiceBeans(serviceBeans);
    factory.setAddress(factory.getAddress());
    factory.setProviders(providers);
    factory.setInInterceptors(Arrays.<Interceptor<? extends Message>>asList(serverLogInInterceptor));
    factory.setOutInterceptors(Arrays.<Interceptor<? extends Message>>asList(serverLogOutInterceptor));
    return factory;
}
Example 59
Project: javaee7-samples-master  File: MyResource.java View source code
@GET
@Path("context")
@Produces("text/plain")
public String getList() {
    StringBuilder builder = new StringBuilder();
    builder.append("Application.classes: ").append(app.getClasses()).append("<br>Path: ").append(uri.getPath());
    for (String header : headers.getRequestHeaders().keySet()) {
        builder.append("<br>Http header: ").append(headers.getRequestHeader(header));
    }
    builder.append("<br>Headers.cookies: ").append(headers.getCookies()).append("<br>Request.method: ").append(request.getMethod()).append("<br>Security.isSecure: ").append(security.isSecure());
    return builder.toString();
}
Example 60
Project: JavaIncrementalParser-master  File: MyResource.java View source code
@GET
@Path("context")
@Produces("text/plain")
public String getList() {
    StringBuilder builder = new StringBuilder();
    builder.append("Application.classes: ").append(app.getClasses()).append("<br>Path: ").append(uri.getPath());
    for (String header : headers.getRequestHeaders().keySet()) {
        builder.append("<br>Http header: ").append(headers.getRequestHeader(header));
    }
    builder.append("<br>Headers.cookies: ").append(headers.getCookies()).append("<br>Request.method: ").append(request.getMethod()).append("<br>Security.isSecure: ").append(security.isSecure());
    return builder.toString();
}
Example 61
Project: liferay-portal-master  File: ConfigurationAdminBundleActivator.java View source code
@Override
public void start(BundleContext bundleContext) throws Exception {
    ServiceReference<ConfigurationAdmin> serviceReference = bundleContext.getServiceReference(ConfigurationAdmin.class);
    try {
        ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference);
        _cxfConfiguration = configurationAdmin.createFactoryConfiguration("com.liferay.portal.remote.cxf.common.configuration." + "CXFEndpointPublisherConfiguration", null);
        Dictionary<String, Object> properties = new Hashtable<>();
        properties.put("contextPath", "/rest-test");
        _cxfConfiguration.update(properties);
        _restConfiguration = configurationAdmin.createFactoryConfiguration("com.liferay.portal.remote.rest.extender.configuration." + "RestExtenderConfiguration", null);
        properties = new Hashtable<>();
        properties.put("contextPaths", new String[] { "/rest-test" });
        properties.put("jaxRsApplicationFilterStrings", new String[] { "(jaxrs.application=true)" });
        _restConfiguration.update(properties);
        properties = new Hashtable<>();
        properties.put("jaxrs.application", true);
        _serviceRegistration = bundleContext.registerService(Application.class, new Greeter(), properties);
        ServiceTracker<Bus, Bus> serviceTracker = ServiceTrackerFactory.open(bundleContext, "(&(objectClass=" + Bus.class.getName() + ")(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH + "=/rest-test))");
        Bus bus = serviceTracker.waitForService(10000L);
        if (bus == null) {
            throw new IllegalStateException("Bus was not registered within 10 seconds");
        }
        ServerRegistry serverRegistry = bus.getExtension(ServerRegistry.class);
        List<Server> servers = null;
        for (int i = 0; i <= 100; i++) {
            servers = serverRegistry.getServers();
            if (!servers.isEmpty()) {
                break;
            }
            Thread.sleep(100);
        }
        if (servers.isEmpty()) {
            _cleanUp(bundleContext);
            throw new IllegalStateException("Endpoint was not registered within 10 seconds");
        }
    } finally {
        bundleContext.ungetService(serviceReference);
    }
}
Example 62
Project: olingo-odata2-master  File: ODataRootLocator.java View source code
public static ODataServiceFactory createServiceFactoryFromContext(final Application app, final HttpServletRequest servletRequest, final ServletConfig servletConfig) {
    try {
        Class<?> factoryClass;
        if (app instanceof AbstractODataApplication) {
            factoryClass = ((AbstractODataApplication) app).getServiceFactoryClass();
        } else {
            final String factoryClassName = servletConfig.getInitParameter(ODataServiceFactory.FACTORY_LABEL);
            if (factoryClassName == null) {
                throw new ODataRuntimeException("Servlet config missing: " + ODataServiceFactory.FACTORY_LABEL);
            }
            ClassLoader cl = (ClassLoader) servletRequest.getAttribute(ODataServiceFactory.FACTORY_CLASSLOADER_LABEL);
            if (cl == null) {
                factoryClass = Class.forName(factoryClassName);
            } else {
                factoryClass = Class.forName(factoryClassName, true, cl);
            }
        }
        return (ODataServiceFactory) factoryClass.newInstance();
    } catch (Exception e) {
        throw new ODataRuntimeException("Exception during ODataServiceFactory creation occured.", e);
    }
}
Example 63
Project: qafe-platform-master  File: BusinessActionRestTest.java View source code
//@formatter:on
@Override
protected Application configure() {
    final ResourceConfig resourceConfig = new ResourceConfig(BusinessActionResource.class);
    resourceConfig.register(new AbstractBinder() {

        @Override
        protected void configure() {
            bind(new TestBusinessActionHandler()).to(BusinessActionHandler.class);
        }
    });
    resourceConfig.register(ParameterMessageBodyReaderWriter.class);
    return resourceConfig;
}
Example 64
Project: rest-utils-master  File: EmbeddedServerTestHarness.java View source code
/**
   * Creates and configures an application. This may be overridden by subclasses if they need
   * to customize the Application's Configuration or invoke a constructor other than
   * Application(Configuration c).
   */
protected T createApplication() throws RestConfigException {
    Class<T> appClass = Generics.getTypeParameter(getClass(), io.confluent.rest.Application.class);
    try {
        return appClass.getConstructor(this.config.getClass()).newInstance(this.config);
    } catch (NoSuchMethodException e) {
        throw new RestConfigException("Couldn't find default constructor for " + appClass.getName(), e);
    } catch (IllegalAccessException e) {
        throw new RestConfigException("Error invoking default constructor " + appClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new RestConfigException("Error invoking default constructor for " + appClass.getName(), e);
    } catch (InstantiationException e) {
        throw new RestConfigException("Error invoking default constructor for " + appClass.getName(), e);
    }
}
Example 65
Project: tuscany-sca-2.x-master  File: RESTBindingInvoker.java View source code
private RestClient createRestClient() {
    ClientConfig config = new ClientConfig();
    // configureBasicAuth(config, userName, password);
    config.applications(new Application() {

        @Override
        public Set<Class<?>> getClasses() {
            return Collections.emptySet();
        }

        @Override
        public Set<Object> getSingletons() {
            Set<Object> providers = new HashSet<Object>();
            providers.add(new DataBindingJAXRSReader(registry));
            providers.add(new DataBindingJAXRSWriter(registry));
            return providers;
        }
    });
    RestClient client = new RestClient(config);
    // Default to GET for RPC
    httpMethod = HttpMethod.GET;
    for (Map.Entry<Class<?>, String> e : mapping.entrySet()) {
        if (operation.getAttributes().get(e.getKey()) != null) {
            httpMethod = e.getValue();
            break;
        }
    }
    if (operation.getOutputType() != null) {
        responseType = operation.getOutputType().getPhysical();
    } else {
        responseType = null;
    }
    return client;
}
Example 66
Project: gyrex-jaxrs-application-master  File: WebApplicationImpl.java View source code
private void _initiate(final ResourceConfig rc, final IoCComponentProviderFactory _provider) {
    if (rc == null) {
        throw new IllegalArgumentException("ResourceConfig instance MUST NOT be null");
    }
    if (initiated) {
        throw new ContainerException(ImplMessages.WEB_APP_ALREADY_INITIATED());
    }
    this.initiated = true;
    LOGGER.info("Initiating Jersey application, version '" + BuildId.getBuildId() + "'");
    // If there are components defined in jaxrs-components then
    // wrap resource config with appended set of classes
    Class<?>[] components = ServiceFinder.find("jersey-server-components").toClassArray();
    if (components.length > 0) {
        if (LOGGER.isLoggable(Level.INFO)) {
            StringBuilder b = new StringBuilder();
            b.append("Adding the following classes declared in META-INF/services/jersey-server-components to the resource configuration:");
            for (Class c : components) b.append('\n').append("  ").append(c);
            LOGGER.log(Level.INFO, b.toString());
        }
        this.resourceConfig = rc.clone();
        this.resourceConfig.getClasses().addAll(Arrays.asList(components));
    } else {
        this.resourceConfig = rc;
    }
    this.provider = _provider;
    this.providerFactories = new ArrayList<IoCComponentProviderFactory>(2);
    for (Object o : resourceConfig.getProviderSingletons()) {
        if (o instanceof IoCComponentProviderFactory) {
            providerFactories.add((IoCComponentProviderFactory) o);
        }
    }
    if (_provider != null)
        providerFactories.add(_provider);
    // Set up the component provider factory to be
    // used with non-resource class components
    this.cpFactory = (providerFactories.isEmpty()) ? new ProviderFactory(injectableFactory) : new IoCProviderFactory(injectableFactory, providerFactories);
    // Set up the resource component provider factory
    this.rcpFactory = (providerFactories.isEmpty()) ? new ResourceFactory(this.resourceConfig, this.injectableFactory) : new IoCResourceFactory(this.resourceConfig, this.injectableFactory, providerFactories);
    // Initiate IoCComponentProcessorFactoryInitializer
    for (IoCComponentProviderFactory f : providerFactories) {
        IoCComponentProcessorFactory cpf;
        if (f instanceof IoCComponentProcessorFactoryInitializer) {
            cpf = new ComponentProcessorFactoryImpl();
            IoCComponentProcessorFactoryInitializer i = (IoCComponentProcessorFactoryInitializer) f;
            i.init(cpf);
        }
    }
    this.resourceContext = new ResourceContext() {

        @Override
        public ExtendedUriInfo matchUriInfo(URI u) throws ContainerException {
            try {
                return handleMatchResourceRequest(u);
            } catch (ContainerException ex) {
                throw ex;
            } catch (WebApplicationException ex) {
                if (ex.getResponse().getStatus() == 404) {
                    return null;
                } else {
                    throw new ContainerException(ex);
                }
            } catch (RuntimeException ex) {
                throw new ContainerException(ex);
            }
        }

        @Override
        public Object matchResource(URI u) throws ContainerException {
            ExtendedUriInfo ui = matchUriInfo(u);
            return (ui != null) ? ui.getMatchedResources().get(0) : null;
        }

        @Override
        public <T> T matchResource(URI u, Class<T> c) throws ContainerException, ClassCastException {
            return c.cast(matchResource(u));
        }

        @Override
        public <T> T getResource(Class<T> c) {
            return c.cast(getResourceComponentProvider(c).getInstance(context));
        }
    };
    final ProviderServices providerServices = new ProviderServices(ServerSide.class, this.cpFactory, resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons());
    injectableFactory.add(new ContextInjectableProvider<ProviderServices>(ProviderServices.class, providerServices));
    injectableFactory.add(new ContextInjectableProvider<ResourceMethodCustomInvokerDispatchFactory>(ResourceMethodCustomInvokerDispatchFactory.class, new ResourceMethodCustomInvokerDispatchFactory(providerServices)));
    // Add injectable provider for @ParentRef
    injectableFactory.add(new InjectableProvider<ParentRef, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, ParentRef a, Type t) {
            if (!(t instanceof Class))
                return null;
            final Class target = ReflectionHelper.getDeclaringClass(cc.getAccesibleObject());
            final Class inject = (Class) t;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    final UriInfo ui = context.getUriInfo();
                    final List l = ui.getMatchedResources();
                    final Object parent = getParent(l, target);
                    if (parent == null)
                        return null;
                    try {
                        return inject.cast(parent);
                    } catch (ClassCastException ex) {
                        throw new ContainerException("The parent resource is expected to be of class " + inject.getName() + " but is of class " + parent.getClass().getName(), ex);
                    }
                }

                private Object getParent(List l, Class target) {
                    if (l.isEmpty()) {
                        return null;
                    } else if (l.size() == 1) {
                        return (l.get(0).getClass() == target) ? null : l.get(0);
                    } else {
                        return (l.get(0).getClass() == target) ? l.get(1) : l.get(0);
                    }
                }
            };
        }
    });
    // Add injectable provider for @Inject
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Undefined;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() == ComponentScope.PerRequest)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<Inject, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, Inject a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() != ComponentScope.Singleton)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    // Add injectable provider for @ResourceRef
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.PerRequest;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Undefined;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() == ComponentScope.PerRequest)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    injectableFactory.add(new InjectableProvider<InjectParam, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        @Override
        public Injectable<Object> getInjectable(ComponentContext cc, InjectParam a, Type t) {
            if (!(t instanceof Class))
                return null;
            final ResourceComponentProvider rcp = getResourceComponentProvider(cc, (Class) t);
            if (rcp.getScope() != ComponentScope.Singleton)
                return null;
            return new Injectable<Object>() {

                @Override
                public Object getValue() {
                    return rcp.getInstance(context);
                }
            };
        }
    });
    // Allow injection of features and properties
    injectableFactory.add(new ContextInjectableProvider<FeaturesAndProperties>(FeaturesAndProperties.class, resourceConfig));
    // Allow injection of resource config
    // Since the resourceConfig reference can change refer to the
    // reference directly.
    injectableFactory.add(new InjectableProvider<Context, Type>() {

        @Override
        public ComponentScope getScope() {
            return ComponentScope.Singleton;
        }

        @Override
        public Injectable<ResourceConfig> getInjectable(ComponentContext cc, Context a, Type t) {
            if (t != ResourceConfig.class)
                return null;
            return new Injectable<ResourceConfig>() {

                @Override
                public ResourceConfig getValue() {
                    return resourceConfig;
                }
            };
        }
    });
    // Allow injection of resource context
    injectableFactory.add(new ContextInjectableProvider<ResourceContext>(ResourceContext.class, resourceContext));
    // Configure the injectable factory with declared providers
    injectableFactory.configure(providerServices);
    boolean updateRequired = false;
    // Create application-declared Application instance as a component
    if (rc instanceof DeferredResourceConfig) {
        final DeferredResourceConfig drc = (DeferredResourceConfig) rc;
        // Check if resource config has already been cloned
        if (resourceConfig == drc)
            resourceConfig = drc.clone();
        final DeferredResourceConfig.ApplicationHolder da = drc.getApplication(cpFactory);
        resourceConfig.add(da.getApplication());
        updateRequired = true;
        injectableFactory.add(new ContextInjectableProvider<Application>(Application.class, da.getOriginalApplication()));
    } else {
        injectableFactory.add(new ContextInjectableProvider<FeaturesAndProperties>(Application.class, resourceConfig));
    }
    // Pipelined, decentralized configuration
    for (ResourceConfigurator configurator : providerServices.getProviders(ResourceConfigurator.class)) {
        configurator.configure(this.resourceConfig);
        updateRequired = true;
    }
    // Validate the resource config
    this.resourceConfig.validate();
    if (updateRequired) {
        // Check if application modified provider classes or singletons
        providerServices.update(resourceConfig.getProviderClasses(), resourceConfig.getProviderSingletons(), injectableFactory);
    }
    // Obtain all the templates
    this.templateContext = new TemplateFactory(providerServices);
    // Allow injection of template context
    injectableFactory.add(new ContextInjectableProvider<TemplateContext>(TemplateContext.class, templateContext));
    // Obtain all context resolvers
    final ContextResolverFactory crf = new ContextResolverFactory();
    // Obtain all the exception mappers
    this.exceptionFactory = new ExceptionMapperFactory();
    // Obtain all message body readers/writers
    this.bodyFactory = new MessageBodyFactory(providerServices, getFeaturesAndProperties().getFeature(FeaturesAndProperties.FEATURE_PRE_1_4_PROVIDER_PRECEDENCE));
    injectableFactory.add(new ContextInjectableProvider<MessageBodyWorkers>(MessageBodyWorkers.class, bodyFactory));
    // Injection of Providers
    this.providers = new Providers() {

        @Override
        public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> c, Type t, Annotation[] as, MediaType m) {
            return bodyFactory.getMessageBodyReader(c, t, as, m);
        }

        @Override
        public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> c, Type t, Annotation[] as, MediaType m) {
            return bodyFactory.getMessageBodyWriter(c, t, as, m);
        }

        @Override
        public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> c) {
            if (Throwable.class.isAssignableFrom(c))
                return exceptionFactory.find(c);
            else
                return null;
        }

        @Override
        public <T> ContextResolver<T> getContextResolver(Class<T> ct, MediaType m) {
            return crf.resolve(ct, m);
        }
    };
    injectableFactory.add(new ContextInjectableProvider<Providers>(Providers.class, providers));
    // Obtain all String readers
    this.stringReaderFactory = new StringReaderFactory();
    injectableFactory.add(new ContextInjectableProvider<StringReaderWorkers>(StringReaderWorkers.class, stringReaderFactory));
    MultivaluedParameterExtractorProvider mpep = new MultivaluedParameterExtractorFactory(stringReaderFactory);
    // Add the multi-valued parameter extractor provider
    injectableFactory.add(new ContextInjectableProvider<MultivaluedParameterExtractorProvider>(MultivaluedParameterExtractorProvider.class, mpep));
    // Add per-request-based injectable providers
    injectableFactory.add(new CookieParamInjectableProvider(mpep));
    injectableFactory.add(new HeaderParamInjectableProvider(mpep));
    injectableFactory.add(new HttpContextInjectableProvider());
    injectableFactory.add(new MatrixParamInjectableProvider(mpep));
    injectableFactory.add(new PathParamInjectableProvider(mpep));
    injectableFactory.add(new QueryParamInjectableProvider(mpep));
    injectableFactory.add(new FormParamInjectableProvider(mpep));
    // Create filter factory
    filterFactory = new FilterFactory(providerServices);
    // Initiate resource method dispatchers
    dispatcherFactory = ResourceMethodDispatcherFactory.create(providerServices);
    dispatchingListener = new DispatchingListenerProxy();
    // Initiate the WADL factory
    this.wadlFactory = new WadlFactory(resourceConfig);
    WadlApplicationContextInjectionProxy wadlApplicationContextInjectionProxy = null;
    if (!resourceConfig.getFeature(ResourceConfig.FEATURE_DISABLE_WADL)) {
        wadlApplicationContextInjectionProxy = new WadlApplicationContextInjectionProxy();
        injectableFactory.add(new SingletonTypeInjectableProvider<Context, WadlApplicationContext>(WadlApplicationContext.class, wadlApplicationContextInjectionProxy) {
        });
    }
    // Initiate filter
    filterFactory.init(resourceConfig);
    if (!resourceConfig.getMediaTypeMappings().isEmpty() || !resourceConfig.getLanguageMappings().isEmpty()) {
        boolean present = false;
        for (ContainerRequestFilter f : filterFactory.getRequestFilters()) {
            present |= f instanceof UriConnegFilter;
        }
        if (!present) {
            filterFactory.getRequestFilters().add(new UriConnegFilter(resourceConfig.getMediaTypeMappings(), resourceConfig.getLanguageMappings()));
        } else {
            LOGGER.warning("The media type and language mappings " + "declared in the ResourceConfig are ignored because " + "there is an instance of " + UriConnegFilter.class.getName() + "present in the list of request filters.");
        }
    }
    // Initiate context resolvers
    crf.init(providerServices, injectableFactory);
    // Initiate the exception mappers
    exceptionFactory.init(providerServices);
    // Initiate message body readers/writers
    bodyFactory.init();
    // Initiate string readers
    stringReaderFactory.init(providerServices);
    // Inject on all components
    Errors.setReportMissingDependentFieldOrMethod(true);
    cpFactory.injectOnAllComponents();
    cpFactory.injectOnProviderInstances(resourceConfig.getProviderSingletons());
    // web application is ready
    for (IoCComponentProviderFactory providerFactory : providerFactories) {
        if (providerFactory instanceof WebApplicationListener) {
            WebApplicationListener listener = (WebApplicationListener) providerFactory;
            listener.onWebApplicationReady();
        }
    }
    createAbstractResourceModelStructures();
    // Obtain all root resource rules
    RulesMap<UriRule> rootRules = new RootResourceUriRules(this, resourceConfig, wadlFactory, injectableFactory).getRules();
    this.rootsRule = new RootResourceClassesRule(rootRules);
    if (!resourceConfig.getFeature(ResourceConfig.FEATURE_DISABLE_WADL)) {
        wadlApplicationContextInjectionProxy.init(wadlFactory);
    }
    requestListener = MonitoringProviderFactory.createRequestListener(providerServices);
    responseListener = MonitoringProviderFactory.createResponseListener(providerServices);
    dispatchingListener.init(providerServices);
    callAbstractResourceModelListenersOnLoaded(providerServices);
    this.isTraceEnabled = resourceConfig.getFeature(ResourceConfig.FEATURE_TRACE) | resourceConfig.getFeature(ResourceConfig.FEATURE_TRACE_PER_REQUEST);
}
Example 67
Project: genson-master  File: JaxRSIntegrationTest.java View source code
@Test
public void testJerseyJsonPConverter() throws Exception {
    Map<String, String> jerseyParams = new HashMap<String, String>();
    jerseyParams.put("javax.ws.rs.Application", RestEasyApp.class.getName());
    startServer(ServletContainer.class, jerseyParams);
    try {
        ClientConfig cfg = new ClientConfig(GensonJsonConverter.class);
        Client client = ClientBuilder.newClient(cfg);
        assertEquals("someCallback([1,2,3])", client.target("http://localhost:9999/get").request("application/x-javascript").get(String.class));
    } finally {
        stopServer();
    }
}
Example 68
Project: Hystrix-master  File: HystricsMetricsControllerTest.java View source code
@Override
protected Application configure() {
    int port = 0;
    try {
        final ServerSocket socket = new ServerSocket(0);
        port = socket.getLocalPort();
        socket.close();
    } catch (IOException e1) {
        throw new RuntimeException("Failed to find port to start test server");
    }
    set(TestProperties.CONTAINER_PORT, port);
    try {
        SystemConfiguration.setSystemProperties("test.properties");
    } catch (Exception e) {
        throw new RuntimeException("Failed to load config file");
    }
    return new ResourceConfig(HystricsMetricsControllerTest.class, HystrixStreamFeature.class);
}
Example 69
Project: incubator-zeppelin-master  File: ZeppelinServer.java View source code
private static ServletContextHandler setupRestApiContextHandler(ZeppelinConfiguration conf) {
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    cxfServletHolder.setInitParameter("javax.ws.rs.Application", ZeppelinServer.class.getName());
    cxfServletHolder.setName("rest");
    cxfServletHolder.setForcedPath("rest");
    final ServletContextHandler cxfContext = new ServletContextHandler();
    cxfContext.setSessionHandler(new SessionHandler());
    cxfContext.setContextPath(conf.getServerContextPath());
    cxfContext.addServlet(cxfServletHolder, "/api/*");
    cxfContext.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class));
    return cxfContext;
}
Example 70
Project: jbosgi-master  File: RestEndpointTestCase.java View source code
@Override
public InputStream openStream() {
    OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
    builder.addBundleSymbolicName(archive.getName());
    builder.addBundleManifestVersion(2);
    builder.addImportPackages(Produces.class, Application.class);
    builder.addBundleClasspath("WEB-INF/classes");
    return builder.openStream();
}
Example 71
Project: nginx-clojure-master  File: NginxJerseyContainer.java View source code
@Override
public void boot(Map<String, String> properties, ClassLoader loader) {
    appPath = properties.get("jersey.app.path");
    bootLoader = loader;
    if (appPath == null) {
        appPath = "";
    }
    String application = properties.get("jersey.app.Appclass");
    if (application != null) {
        Class appClz = null;
        try {
            appClz = loader.loadClass(application.trim());
        } catch (ClassNotFoundException e) {
            NginxClojureRT.log.warn("can not load jersey.app.Appclass %s", application, e);
            throw new RuntimeException("can not load jersey.app.Appclass " + e.getMessage(), e);
        }
        try {
            appHandler = new ApplicationHandler((Class<? extends Application>) appClz.newInstance());
        } catch (Exception e) {
            throw new RuntimeException("can not create jersey.app.Appclass" + e.getMessage(), e);
        }
    } else {
        String res = properties.get("jersey.app.resources");
        List<Class> clzList = new ArrayList<Class>();
        if (res != null) {
            for (String clz : res.split(",")) {
                try {
                    clzList.add(loader.loadClass(clz.trim()));
                } catch (Throwable e) {
                    NginxClojureRT.log.warn("can not load resource %s, skiping", clz, e);
                }
            }
            appResources = clzList.toArray(new Class[clzList.size()]);
        }
        if (appResources == null || appResources.length == 0) {
            NginxClojureRT.log.warn("no resource defined, property %s is null", "jersey.app.resources");
        }
        appHandler = new ApplicationHandler(configure());
    }
}
Example 72
Project: OpenTripPlanner-master  File: GrizzlyServer.java View source code
/**
     * This function goes through roughly the same steps as Jersey's GrizzlyServerFactory, but we instead construct
     * an HttpServer and NetworkListener manually so we can set the number of threads and other details.
     */
public void run() {
    LOG.info("Starting OTP Grizzly server on ports {} (HTTP) and {} (HTTPS) of interface {}", params.port, params.securePort, params.bindAddress);
    LOG.info("OTP server base path is {}", params.basePath);
    HttpServer httpServer = new HttpServer();
    /* Configure SSL */
    SSLContextConfigurator sslConfig = new SSLContextConfigurator();
    sslConfig.setKeyStoreFile(new File(params.basePath, "keystore").getAbsolutePath());
    sslConfig.setKeyStorePass("opentrip");
    /* OTP is CPU-bound, so we want only as many worker threads as we have cores. */
    ThreadPoolConfig threadPoolConfig = ThreadPoolConfig.defaultConfig().setCorePoolSize(1).setMaxPoolSize(Runtime.getRuntime().availableProcessors());
    /* HTTP (non-encrypted) listener */
    NetworkListener httpListener = new NetworkListener("otp_insecure", params.bindAddress, params.port);
    // OTP is CPU-bound, we don't want more threads than cores. TODO: We should switch to async handling.
    httpListener.setSecure(false);
    /* HTTPS listener */
    NetworkListener httpsListener = new NetworkListener("otp_secure", params.bindAddress, params.securePort);
    // Ideally we'd share the threads between HTTP and HTTPS.
    httpsListener.setSecure(true);
    httpsListener.setSSLEngineConfig(new SSLEngineConfigurator(sslConfig).setClientMode(false).setNeedClientAuth(false));
    // For both HTTP and HTTPS listeners: enable gzip compression, set thread pool, add listener to httpServer.
    for (NetworkListener listener : new NetworkListener[] { httpListener, httpsListener }) {
        CompressionConfig cc = listener.getCompressionConfig();
        cc.setCompressionMode(CompressionConfig.CompressionMode.ON);
        // the min number of bytes to compress
        cc.setCompressionMinSize(50000);
        // the mime types to compress
        cc.setCompressableMimeTypes("application/json", "text/json");
        listener.getTransport().setWorkerThreadPoolConfig(threadPoolConfig);
        httpServer.addListener(listener);
    }
    /* Add a few handlers (~= servlets) to the Grizzly server. */
    /* 1. A Grizzly wrapper around the Jersey Application. */
    Application app = new OTPApplication(server, !params.insecure);
    HttpHandler dynamicHandler = ContainerFactory.createContainer(HttpHandler.class, app);
    httpServer.getServerConfiguration().addHttpHandler(dynamicHandler, "/otp/");
    /* 2. A static content handler to serve the client JS apps etc. from the classpath. */
    CLStaticHttpHandler staticHandler = new CLStaticHttpHandler(GrizzlyServer.class.getClassLoader(), "/client/");
    if (params.disableFileCache) {
        LOG.info("Disabling HTTP server static file cache.");
        staticHandler.setFileCacheEnabled(false);
    }
    httpServer.getServerConfiguration().addHttpHandler(staticHandler, "/");
    /*
         * 3. A static content handler to serve local files from the filesystem, under the "local"
         * path.
         */
    if (params.clientDirectory != null) {
        StaticHttpHandler localHandler = new StaticHttpHandler(params.clientDirectory.getAbsolutePath());
        localHandler.setFileCacheEnabled(false);
        httpServer.getServerConfiguration().addHttpHandler(localHandler, "/local");
    }
    /* 3. Test alternate method (no Jersey). */
    // As in servlets, * is needed in base path to identify the "rest" of the path.
    // GraphService gs = (GraphService) iocFactory.getComponentProvider(GraphService.class).getInstance();
    // Graph graph = gs.getGraph();
    // httpServer.getServerConfiguration().addHttpHandler(new OTPHttpHandler(graph), "/test/*");
    // Add shutdown hook to gracefully shut down Grizzly.
    // Signal handling (sun.misc.Signal) is potentially not available on all JVMs.
    Thread shutdownThread = new Thread(httpServer::shutdown);
    Runtime.getRuntime().addShutdownHook(shutdownThread);
    /* RELINQUISH CONTROL TO THE SERVER THREAD */
    try {
        httpServer.start();
        LOG.info("Grizzly server running.");
        Thread.currentThread().join();
    } catch (BindException be) {
        LOG.error("Cannot bind to port {}. Is it already in use?", params.port);
    } catch (IOException ioe) {
        LOG.error("IO exception while starting server.");
    } catch (InterruptedException ie) {
        LOG.info("Interrupted, shutting down.");
    }
    // Clean up graceful shutdown hook before shutting down Grizzly.
    Runtime.getRuntime().removeShutdownHook(shutdownThread);
    httpServer.shutdown();
}
Example 73
Project: Planner-master  File: GrizzlyServer.java View source code
/**
     * This function goes through roughly the same steps as Jersey's GrizzlyServerFactory, but we instead construct
     * an HttpServer and NetworkListener manually so we can set the number of threads and other details.
     */
public void run() {
    LOG.info("Starting OTP Grizzly server on ports {} (HTTP) and {} (HTTPS) of interface {}", params.port, params.securePort, params.bindAddress);
    LOG.info("OTP server base path is {}", params.basePath);
    HttpServer httpServer = new HttpServer();
    /* Configure SSL */
    SSLContextConfigurator sslConfig = new SSLContextConfigurator();
    sslConfig.setKeyStoreFile(new File(params.basePath, "keystore").getAbsolutePath());
    sslConfig.setKeyStorePass("opentrip");
    /* OTP is CPU-bound, so we want only as many worker threads as we have cores. */
    ThreadPoolConfig threadPoolConfig = ThreadPoolConfig.defaultConfig().setCorePoolSize(1).setMaxPoolSize(Runtime.getRuntime().availableProcessors());
    /* HTTP (non-encrypted) listener */
    NetworkListener httpListener = new NetworkListener("otp_insecure", params.bindAddress, params.port);
    // OTP is CPU-bound, we don't want more threads than cores. TODO: We should switch to async handling.
    httpListener.setSecure(false);
    /* HTTPS listener */
    NetworkListener httpsListener = new NetworkListener("otp_secure", params.bindAddress, params.securePort);
    // Ideally we'd share the threads between HTTP and HTTPS.
    httpsListener.setSecure(true);
    httpsListener.setSSLEngineConfig(new SSLEngineConfigurator(sslConfig).setClientMode(false).setNeedClientAuth(false));
    // For both HTTP and HTTPS listeners: enable gzip compression, set thread pool, add listener to httpServer.
    for (NetworkListener listener : new NetworkListener[] { httpListener, httpsListener }) {
        CompressionConfig cc = listener.getCompressionConfig();
        cc.setCompressionMode(CompressionConfig.CompressionMode.ON);
        // the min number of bytes to compress
        cc.setCompressionMinSize(50000);
        // the mime types to compress
        cc.setCompressableMimeTypes("application/json", "text/json");
        listener.getTransport().setWorkerThreadPoolConfig(threadPoolConfig);
        httpServer.addListener(listener);
    }
    /* Add a few handlers (~= servlets) to the Grizzly server. */
    /* 1. A Grizzly wrapper around the Jersey Application. */
    Application app = new OTPApplication(server, !params.insecure);
    HttpHandler dynamicHandler = ContainerFactory.createContainer(HttpHandler.class, app);
    httpServer.getServerConfiguration().addHttpHandler(dynamicHandler, "/otp/");
    /* 2. A static content handler to serve the client JS apps etc. from the classpath. */
    CLStaticHttpHandler staticHandler = new CLStaticHttpHandler(GrizzlyServer.class.getClassLoader(), "/client/");
    if (params.disableFileCache) {
        LOG.info("Disabling HTTP server static file cache.");
        staticHandler.setFileCacheEnabled(false);
    }
    httpServer.getServerConfiguration().addHttpHandler(staticHandler, "/");
    /*
         * 3. A static content handler to serve local files from the filesystem, under the "local"
         * path.
         */
    if (params.clientDirectory != null) {
        StaticHttpHandler localHandler = new StaticHttpHandler(params.clientDirectory.getAbsolutePath());
        localHandler.setFileCacheEnabled(false);
        httpServer.getServerConfiguration().addHttpHandler(localHandler, "/local");
    }
    /* 3. Test alternate method (no Jersey). */
    // As in servlets, * is needed in base path to identify the "rest" of the path.
    // GraphService gs = (GraphService) iocFactory.getComponentProvider(GraphService.class).getInstance();
    // Graph graph = gs.getGraph();
    // httpServer.getServerConfiguration().addHttpHandler(new OTPHttpHandler(graph), "/test/*");
    // Add shutdown hook to gracefully shut down Grizzly.
    // Signal handling (sun.misc.Signal) is potentially not available on all JVMs.
    Thread shutdownThread = new Thread(httpServer::shutdown);
    Runtime.getRuntime().addShutdownHook(shutdownThread);
    /* RELINQUISH CONTROL TO THE SERVER THREAD */
    try {
        httpServer.start();
        LOG.info("Grizzly server running.");
        Thread.currentThread().join();
    } catch (BindException be) {
        LOG.error("Cannot bind to port {}. Is it already in use?", params.port);
    } catch (IOException ioe) {
        LOG.error("IO exception while starting server.");
    } catch (InterruptedException ie) {
        LOG.info("Interrupted, shutting down.");
    }
    // Clean up graceful shutdown hook before shutting down Grizzly.
    Runtime.getRuntime().removeShutdownHook(shutdownThread);
    httpServer.shutdown();
}
Example 74
Project: play-dcep-master  File: EcConnectionManager4storeTest.java View source code
@BeforeClass
public static void setupBeforeClass() throws Exception {
    Application listener = new TestListenerRest(eventSink);
    Application fourstore = new TestFourstore(rdfSink);
    final ResourceConfig rc = new ResourceConfig().register(listener).register(fourstore).register(MoxyJsonFeature.class);
    BusFactory.getDefaultBus(true);
    notifyReceiverRest = new Server(URI.create(REST_URI).getPort());
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    ServletHolder h = new ServletHolder(new ServletContainer(rc));
    context.addServlet(h, "/");
    notifyReceiverRest.setHandler(context);
    notifyReceiverRest.start();
    logger.info("Test server started.");
}
Example 75
Project: xdocreport-master  File: RESTXDocReportServiceTest.java View source code
@BeforeClass
public static void startServer() throws Exception {
    ServletHolder servlet = new ServletHolder(CXFNonSpringJaxrsServlet.class);
    servlet.setInitParameter(Application.class.getName(), fr.opensagres.xdocreport.service.rest.XDocreportApplication.class.getName());
    servlet.setInitParameter("jaxrs.serviceClasses", XDocReportServiceJaxRs.class.getName());
    servlet.setInitParameter("timeout", "60000");
    server = new Server(PORT);
    ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    context.addServlet(servlet, "/*");
    server.start();
}
Example 76
Project: knowledgestore-master  File: Application.java View source code
static Application unwrap(final javax.ws.rs.core.Application application) {
    if (application instanceof Application) {
        return (Application) application;
    } else if (application instanceof ResourceConfig) {
        return (Application) ((ResourceConfig) application).getApplication();
    }
    Preconditions.checkNotNull(application, "Null application");
    throw new IllegalArgumentException("Invalid application class " + application.getClass().getName());
}
Example 77
Project: carbon-commons-master  File: POMGenerator.java View source code
public static void generateJaxRSClient(List optionsList, String codegenOutputDirectory, HashMap<String, String> projOptionsList) throws Exception {
    String s = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("org/wso2/carbon/wsdl2code/jaxrs-pom.xml"), "UTF-8");
    s = s.replace("gid", projOptionsList.get("-gid").toString()).replace("aid", projOptionsList.get("-aid").toString()).replace("vn", projOptionsList.get("-vn").toString());
    //        URL url = getContainingArtifact(javax.ws.rs.core.Application.class);
    //        String version = getVersion(url.getFile());
    //  s = s.replace("jsr311-version", version);
    String wadlUrl = getArgumentValue("-Service", optionsList);
    String wsdlOptions = getExtraArgsJaxRS(optionsList);
    s = String.format(s, wadlUrl, wsdlOptions);
    createFile(codegenOutputDirectory, s);
}
Example 78
Project: etk-component-master  File: ResourceBinder.java View source code
/**
   * @param application Application
   * @see Application
   */
@SuppressWarnings("unchecked")
public void addApplication(Application application) {
    for (Object obj : application.getSingletons()) {
        if (obj.getClass().getAnnotation(Provider.class) != null) {
            // singleton provider
            if (obj instanceof ContextResolver) {
                providers.addContextResolver((ContextResolver) obj);
            }
            if (obj instanceof ExceptionMapper) {
                providers.addExceptionMapper((ExceptionMapper) obj);
            }
            if (obj instanceof MessageBodyReader) {
                providers.addMessageBodyReader((MessageBodyReader) obj);
            }
            if (obj instanceof MessageBodyWriter) {
                providers.addMessageBodyWriter((MessageBodyWriter) obj);
            }
        } else {
            // singleton resource
            bind(obj);
        }
    }
    for (Class clazz : application.getClasses()) {
        if (clazz.getAnnotation(Provider.class) != null) {
            // per-request provider
            if (ContextResolver.class.isAssignableFrom(clazz)) {
                providers.addContextResolver(clazz);
            }
            if (ExceptionMapper.class.isAssignableFrom(clazz)) {
                providers.addExceptionMapper(clazz);
            }
            if (MessageBodyReader.class.isAssignableFrom(clazz)) {
                providers.addMessageBodyReader(clazz);
            }
            if (MessageBodyWriter.class.isAssignableFrom(clazz)) {
                providers.addMessageBodyWriter(clazz);
            }
        } else {
            // per-request resource
            bind(clazz);
        }
    }
}
Example 79
Project: keycloak-master  File: AbstractKeycloakRule.java View source code
public void deployJaxrsApplication(String name, String contextPath, Class<? extends Application> applicationClass, Map<String, String> initParams) {
    ResteasyDeployment deployment = new ResteasyDeployment();
    deployment.setApplicationClass(applicationClass.getName());
    DeploymentInfo di = server.getServer().undertowDeployment(deployment, "");
    di.setClassLoader(getClass().getClassLoader());
    di.setContextPath(contextPath);
    di.setDeploymentName(name);
    for (Map.Entry<String, String> param : initParams.entrySet()) {
        di.addInitParameter(param.getKey(), param.getValue());
    }
    server.getServer().deploy(di);
}
Example 80
Project: terremark-api-master  File: TerremarkClientImpl.java View source code
/**
     * Configures the application for the rest client. If the content type is XML, the custom JAXB XML provider is
     * added. If the content type is JSON, the custom JAXB JSON provider is added. These will aid in deserialization of
     * the responses.
     *
     * @param config Apache Wink client configuration.
     * @param properties Terremark API configuration.
     */
private static void setApplications(final ClientConfig config, final ClientConfiguration properties) {
    config.applications(new Application() {

        @Override
        public Set<Object> getSingletons() {
            final ContentType contentType = properties.getContentType();
            final Set<Object> set = new HashSet<Object>();
            if (contentType == ContentType.XML) {
                set.add(new TerremarkJAXBXmlProvider());
            } else if (contentType == ContentType.JSON) {
                set.add(new TerremarkJAXBJsonProvider());
            } else {
                throw new IllegalArgumentException("Invalid content type: " + contentType);
            }
            return set;
        }
    });
}
Example 81
Project: typescript-generator-master  File: JaxrsApplicationParser.java View source code
public Result tryParse(SourceType<?> sourceType) {
    if (!(sourceType.type instanceof Class<?>)) {
        return null;
    }
    final Class<?> cls = (Class<?>) sourceType.type;
    // application
    if (Application.class.isAssignableFrom(cls)) {
        final ApplicationPath applicationPathAnnotation = cls.getAnnotation(ApplicationPath.class);
        if (applicationPathAnnotation != null) {
            model.setApplicationPath(applicationPathAnnotation.value());
        }
        model.setApplicationName(cls.getSimpleName());
        final List<SourceType<Type>> discoveredTypes = JaxrsApplicationScanner.scanJaxrsApplication(cls, isClassNameExcluded);
        return new Result(discoveredTypes);
    }
    // resource
    final Path path = cls.getAnnotation(Path.class);
    if (path != null) {
        System.out.println("Parsing JAX-RS resource: " + cls.getName());
        final Result result = new Result();
        parseResource(result, new ResourceContext(cls, path.value()), cls);
        return result;
    }
    return null;
}
Example 82
Project: grill-master  File: TestSessionResource.java View source code
/*
   * (non-Javadoc)
   *
   * @see org.glassfish.jersey.test.JerseyTest#configure()
   */
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    return new SessionApp() {

        @Override
        public Set<Class<?>> getClasses() {
            final Set<Class<?>> classes = super.getClasses();
            classes.add(GenericExceptionMapper.class);
            classes.add(LensJAXBContextResolver.class);
            return classes;
        }
    };
}
Example 83
Project: lens-master  File: TestSessionResource.java View source code
/*
   * (non-Javadoc)
   *
   * @see org.glassfish.jersey.test.JerseyTest#configure()
   */
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    return new SessionApp() {

        @Override
        public Set<Class<?>> getClasses() {
            final Set<Class<?>> classes = super.getClasses();
            classes.add(GenericExceptionMapper.class);
            classes.add(LensJAXBContextResolver.class);
            return classes;
        }
    };
}
Example 84
Project: zeppelin-master  File: ZeppelinServer.java View source code
private static void setupRestApiContextHandler(WebAppContext webapp, ZeppelinConfiguration conf) {
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    cxfServletHolder.setInitParameter("javax.ws.rs.Application", ZeppelinServer.class.getName());
    cxfServletHolder.setName("rest");
    cxfServletHolder.setForcedPath("rest");
    webapp.setSessionHandler(new SessionHandler());
    webapp.addServlet(cxfServletHolder, "/api/*");
    String shiroIniPath = conf.getShiroPath();
    if (!StringUtils.isBlank(shiroIniPath)) {
        webapp.setInitParameter("shiroConfigLocations", new File(shiroIniPath).toURI().toString());
        SecurityUtils.initSecurityManager(shiroIniPath);
        webapp.addFilter(ShiroFilter.class, "/api/*", EnumSet.allOf(DispatcherType.class));
        webapp.addEventListener(new EnvironmentLoaderListener());
    }
}
Example 85
Project: teiid-master  File: RestASMBasedWebArchiveBuilder.java View source code
public byte[] getApplicationClass(ArrayList<String> models) {
    ClassWriter cw = new ClassWriter(0);
    FieldVisitor fv;
    MethodVisitor mv;
    cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, "org/teiid/jboss/rest/TeiidRestApplication", null, "javax/ws/rs/core/Application", null);
    {
        fv = cw.visitField(ACC_PRIVATE, "singletons", "Ljava/util/Set;", "Ljava/util/Set<Ljava/lang/Object;>;", null);
        fv.visitEnd();
    }
    {
        fv = cw.visitField(ACC_PRIVATE, "empty", "Ljava/util/Set;", "Ljava/util/Set<Ljava/lang/Class<*>;>;", null);
        fv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/core/Application", "<init>", "()V");
        mv.visitVarInsn(ALOAD, 0);
        mv.visitTypeInsn(NEW, "java/util/HashSet");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/util/HashSet", "<init>", "()V");
        mv.visitFieldInsn(PUTFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "singletons", "Ljava/util/Set;");
        mv.visitVarInsn(ALOAD, 0);
        mv.visitTypeInsn(NEW, "java/util/HashSet");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/util/HashSet", "<init>", "()V");
        mv.visitFieldInsn(PUTFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "empty", "Ljava/util/Set;");
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "singletons", "Ljava/util/Set;");
        mv.visitTypeInsn(NEW, "io/swagger/jaxrs/listing/ApiListingResource");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "io/swagger/jaxrs/listing/ApiListingResource", "<init>", "()V");
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Set", "add", "(Ljava/lang/Object;)Z");
        mv.visitInsn(POP);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "singletons", "Ljava/util/Set;");
        mv.visitTypeInsn(NEW, "io/swagger/jaxrs/listing/SwaggerSerializers");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "io/swagger/jaxrs/listing/SwaggerSerializers", "<init>", "()V");
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Set", "add", "(Ljava/lang/Object;)Z");
        mv.visitInsn(POP);
        mv.visitVarInsn(ALOAD, 0);
        for (int i = 0; i < models.size(); i++) {
            mv.visitFieldInsn(GETFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "singletons", "Ljava/util/Set;");
            mv.visitTypeInsn(NEW, "org/teiid/jboss/rest/" + models.get(i));
            mv.visitInsn(DUP);
            mv.visitMethodInsn(INVOKESPECIAL, "org/teiid/jboss/rest/" + models.get(i), "<init>", "()V");
            mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Set", "add", "(Ljava/lang/Object;)Z");
            mv.visitInsn(POP);
            if (i < models.size() - 1) {
                mv.visitVarInsn(ALOAD, 0);
            }
        }
        mv.visitInsn(RETURN);
        mv.visitMaxs(3, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "getClasses", "()Ljava/util/Set;", "()Ljava/util/Set<Ljava/lang/Class<*>;>;", null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "empty", "Ljava/util/Set;");
        mv.visitInsn(ARETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "getSingletons", "()Ljava/util/Set;", "()Ljava/util/Set<Ljava/lang/Object;>;", null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, "org/teiid/jboss/rest/TeiidRestApplication", "singletons", "Ljava/util/Set;");
        mv.visitInsn(ARETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    cw.visitEnd();
    return cw.toByteArray();
}
Example 86
Project: opencirm-master  File: StartUp.java View source code
public static void main(String[] args) throws Exception {
    if (STRESS_TEST_CONFIG)
        stressTestConfig();
    if ((args.length > 0)) {
        setConfig(Json.read(GenUtils.readTextFile(new File(args[0]))));
    }
    boolean productionMode = config.at(MODE_CONFIG_PARAM).asString().equals(PRODUCTION_MODE_IDENTIFIER);
    setProductionMode(productionMode);
    System.out.println("Using config " + config.toString());
    if (isProductionMode()) {
        ThreadLocalStopwatch.now("************************* 311Hub PRODUCTION MODE *************************");
    } else {
        ThreadLocalStopwatch.now("------------------------- 311Hub TEST OR DEV MODE: " + config.at(MODE_CONFIG_PARAM).asString() + "-------------------------");
    }
    try {
        ConfigSet.getInstance();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
    configureServer();
    final Restlet restApplication = createRestServicesApp();
    final Context childCtx = server.getContext().createChildContext();
    Application javaScriptApplication = new Application(childCtx) {

        @Override
        public Restlet createInboundRoot() {
            return configureDirResource(new Directory(childCtx.createChildContext(), "file:///" + config.at("workingDir").asString() + "/src/javascript/"));
        }
    };
    //server.getDefaultHost().attach("/javascript", application);
    Application resourcesApplication = new Application(childCtx) {

        @Override
        public Restlet createInboundRoot() {
            return configureDirResource(new Directory(childCtx.createChildContext(), "file:///" + config.at("workingDir").asString() + "/src/resources/"));
        }
    };
    //server.getDefaultHost().attach("/resources", application);
    // Restlet to upload file from client to server
    Application uploadApplication = new Application(server.getContext().createChildContext()) {

        public Restlet createInboundRoot() {
            Router router = new Router();
            // Attach the resource.
            router.attachDefault(UploadToCloudServerResource.class);
            return router;
        }
    };
    //server.getDefaultHost().attach("/upload", application);
    // Restlet to serve uploaded files from server to client
    Application uploadedApplication = new Application(childCtx) {

        @Override
        public Restlet createInboundRoot() {
            return configureDirResource(new Directory(childCtx.createChildContext(), "file:///" + config.at("workingDir").asString() + "/src/uploaded/"));
        }
    };
    //server.getDefaultHost().attach("/uploaded", application);
    Application healthcheckApplication = new Application(childCtx) {

        @Override
        public Restlet createInboundRoot() {
            return configureDirResource(new Directory(childCtx.createChildContext(), "file:///" + config.at("workingDir").asString() + "/src/html/healthcheck.htm"));
        }
    };
    //server.getDefaultHost().attach("/healthcheck.htm", application);
    Application htmlApplication = new Application(server.getContext().createChildContext()) {

        @Override
        public Restlet createInboundRoot() {
            Directory dir = new Directory(getContext().createChildContext(), "file:///" + config.at("workingDir").asString() + "/src/html/");
            dir.setIndexName("startup.html");
            return configureDirResource(dir);
        }
    };
    final Router router = new Router(server.getContext().createChildContext());
    router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/healthcheck.htm", healthcheckApplication).setMatchingMode(Template.MODE_EQUALS);
    router.attach("/", htmlApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/go", htmlApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/html", htmlApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/javascript", javaScriptApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/resources", resourcesApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/upload", uploadApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    router.attach("/uploaded", uploadedApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    if (config.is("startTest", true)) {
        Application testApplication = new Application(server.getContext().createChildContext()) {

            @Override
            public Restlet createInboundRoot() {
                Directory dir = new Directory(getContext().createChildContext(), "file:///" + config.at("workingDir").asString() + "/src/test/");
                dir.setIndexName("testsuite.html");
                return configureDirResource(dir);
            }
        };
        router.attach("/test", testApplication).setMatchingMode(Template.MODE_STARTS_WITH);
    }
    router.setRoutingMode(Router.MODE_BEST_MATCH);
    final Restlet topRestlet = new Restlet() {

        @Override
        public void handle(Request request, Response response) {
            if (request.getResourceRef().getPath().equals("/") || request.getResourceRef().getPath().startsWith("/images") || request.getResourceRef().getPath().equals("/healthcheck.htm") || request.getResourceRef().getPath().startsWith("/go") || request.getResourceRef().getPath().startsWith("/favicon.ico") || request.getResourceRef().getPath().startsWith("/html") || request.getResourceRef().getPath().startsWith("/test") || request.getResourceRef().getPath().startsWith("/javascript") || request.getResourceRef().getPath().startsWith("/resources") || request.getResourceRef().getPath().startsWith("/upload")) {
                //System.out.println("FILE REQUEST : " + request);// + request.getResourceRef().getPath());
                router.handle(request, response);
            } else {
                //System.out.println("REST SERVICE : " + request.getResourceRef().getPath());
                RequestScopeFilter.set("clientInfo", request.getClientInfo());
                restApplication.handle(request, response);
            }
        }
    };
    StartupUtils.disableCertificateValidation();
    attachToServer(topRestlet);
    RelationalOWLMapper.getInstance();
    if (config.has("cachedReasonerPopulate") && config.is("cachedReasonerPopulate", true)) {
        OntoAdmin oa = new OntoAdmin();
        oa.populateIndividualSerialEntityCache();
        oa.cachedReasonerQ1Populate();
    }
    try {
        if (config.has("isConfigMode") && config.at("isConfigMode").asBoolean()) {
            System.out.println("Create Configuration Server cache...");
            ServiceCaseManager.getInstance();
            System.out.println("Done creating Configuration Server cache.");
        }
        server.start();
        if (redirectServer != null) {
            redirectServer.start();
        }
        HTTP_INIT.initialize();
    } catch (Exception e) {
        System.err.println("ERROR ON STARTUP - EXITING");
        throw new RuntimeException(e);
    }
}
Example 87
Project: datacollector-master  File: HttpClientSourceIT.java View source code
@Override
protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    return new ResourceConfig(Sets.newHashSet(StreamResource.class, NewlineStreamResource.class, TextStreamResource.class, SlowTextStreamResource.class, XmlStreamResource.class, PreemptiveAuthResource.class, AuthResource.class, HeaderRequired.class, AlwaysUnauthorized.class, HttpStageTestUtil.TestPostCustomType.class, StreamTokenResetResource.class, Auth2Resource.class, Auth2ResourceOwnerWithIdResource.class, Auth2BasicResource.class, Auth2JWTResource.class));
}
Example 88
Project: XPagesExtensionLibrary-master  File: DasServlet.java View source code
public void doDestroy() {
    if (s_initialized) {
        Iterator<String> iterator = s_services.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            DasService service = s_services.get(key);
            Application application = service.getApplication();
            if (application instanceof RestService) {
                try {
                    ((RestService) application).destroy();
                } catch (Throwable e) {
                    DAS_LOGGER.warn(e, e.getMessage());
                }
            }
        }
        // Clean up Domino stats
        IStatisticsProvider provider = ProviderFactory.getStatisticsProvider();
        if (provider != null) {
            Set<Map.Entry<String, Object>> set = DasStats.get().getEntries();
            for (Map.Entry<String, Object> entry : set) {
                provider.Delete(STATS_FACILITY, entry.getKey());
            }
        }
    }
    super.doDestroy();
}
Example 89
Project: bennu-master  File: OAuthServletTest.java View source code
public static void initObjects() {
    if (user1 == null) {
        user1 = createUser("user1", "John", "Doe", "John Doe", "john.doe@fenixedu.org");
    }
    if (oauthServlet == null) {
        oauthServlet = new OAuthAuthorizationServlet();
    }
    if (serviceApplication == null) {
        serviceApplication = new ServiceApplication();
        serviceApplication.setAuthor(user1);
        serviceApplication.setName("Test Service Application");
        serviceApplication.setDescription("This is a test service application");
    }
    if (serviceApplicationWithScope == null) {
        serviceApplicationWithScope = new ServiceApplication();
        serviceApplicationWithScope.setAuthorName("John Doe");
        serviceApplicationWithScope.setName("Service App with scope");
        serviceApplicationWithScope.setDescription("Service App with scope SERVICE");
        ExternalApplicationScope scope = new ExternalApplicationScope();
        scope.setScopeKey("SERVICE");
        scope.setName(new LocalizedString.Builder().with(enGB, "Service Scope").build());
        scope.setDescription(new LocalizedString.Builder().with(enGB, "Service scope is for service only").build());
        scope.setService(Boolean.TRUE);
        serviceApplicationWithScope.addScopes(scope);
    }
    if (externalApplication == null) {
        externalApplication = new ExternalApplication();
        externalApplication.setAuthor(user1);
        externalApplication.setName("Test External Application");
        externalApplication.setDescription("This is a test external application");
        externalApplication.setRedirectUrl("http://test.url/callback");
    }
    if (externalApplicationScope == null) {
        externalApplicationScope = new ExternalApplicationScope();
        externalApplicationScope.setScopeKey("TEST");
        externalApplicationScope.setName(new LocalizedString.Builder().with(enGB, "TEST Scope").build());
        externalApplicationScope.setDescription(new LocalizedString.Builder().with(enGB, "TEST scope").build());
        externalApplicationScope.setService(Boolean.FALSE);
    }
    if (serviceApplicationOAuthAccessProvider == null) {
        serviceApplicationOAuthAccessProvider = new ExternalApplicationScope();
        serviceApplicationOAuthAccessProvider.setScopeKey("OAUTH_AUTHORIZATION_PROVIDER");
        serviceApplicationOAuthAccessProvider.setName(new LocalizedString.Builder().with(enGB, "OAuth Authorization Provider Scope").build());
        serviceApplicationOAuthAccessProvider.setDescription(new LocalizedString.Builder().with(enGB, "OAuth Authorization Provider Scope").build());
    }
    if (loggedScope == null) {
        loggedScope = new ExternalApplicationScope();
        loggedScope.setScopeKey("LOGGED");
        loggedScope.setName(new LocalizedString.Builder().with(enGB, "Logged Scope").build());
        loggedScope.setDescription(new LocalizedString.Builder().with(enGB, "Logged Scope").build());
    }
    JsonAwareResource.setDefault(ExternalApplication.class, ExternalApplicationAdapter.class);
    JsonAwareResource.setDefault(ApplicationUserAuthorization.class, ExternalApplicationAuthorizationAdapter.class);
    JsonAwareResource.setDefault(ApplicationUserSession.class, ExternalApplicationAuthorizationSessionAdapter.class);
    JsonAwareResource.setDefault(ExternalApplicationScope.class, ExternalApplicationScopeAdapter.class);
    JsonAwareResource.setDefault(ServiceApplication.class, ServiceApplicationAdapter.class);
}
Example 90
Project: che-master  File: ProjectServiceTest.java View source code
@BeforeMethod
public void setUp() throws Exception {
    WorkspaceProjectsSyncer workspaceHolder = new WsAgentTestBase.TestWorkspaceHolder();
    File root = new File(FS_PATH);
    if (root.exists()) {
        IoUtil.deleteRecursive(root);
    }
    root.mkdir();
    File indexDir = new File(INDEX_PATH);
    if (indexDir.exists()) {
        IoUtil.deleteRecursive(indexDir);
    }
    indexDir.mkdir();
    Set<PathMatcher> filters = new HashSet<>();
    filters.add( path -> {
        for (java.nio.file.Path pathElement : path) {
            if (pathElement == null || EXCLUDE_SEARCH_PATH.equals(pathElement.toString())) {
                return true;
            }
        }
        return false;
    });
    FSLuceneSearcherProvider sProvider = new FSLuceneSearcherProvider(indexDir, filters);
    vfsProvider = new LocalVirtualFileSystemProvider(root, sProvider);
    final EventService eventService = new EventService();
    // PTs for test
    ProjectTypeDef chuck = new ProjectTypeDef("chuck_project_type", "chuck_project_type", true, false) {

        {
            addConstantDefinition("x", "attr description", new AttributeValue(Arrays.asList("a", "b")));
        }
    };
    Set<ProjectTypeDef> projectTypes = new HashSet<>();
    final LocalProjectType myProjectType = new LocalProjectType("my_project_type", "my project type");
    projectTypes.add(myProjectType);
    projectTypes.add(new LocalProjectType("module_type", "module type"));
    projectTypes.add(chuck);
    ptRegistry = new ProjectTypeRegistry(projectTypes);
    phRegistry = new ProjectHandlerRegistry(new HashSet<>());
    importerRegistry = new ProjectImporterRegistry(Collections.<ProjectImporter>emptySet());
    projectServiceLinksInjector = new ProjectServiceLinksInjector();
    projectRegistry = new ProjectRegistry(workspaceHolder, vfsProvider, ptRegistry, phRegistry, eventService);
    projectRegistry.initProjects();
    FileWatcherNotificationHandler fileWatcherNotificationHandler = new DefaultFileWatcherNotificationHandler(vfsProvider);
    FileTreeWatcher fileTreeWatcher = new FileTreeWatcher(root, new HashSet<>(), fileWatcherNotificationHandler);
    pm = new ProjectManager(vfsProvider, ptRegistry, projectRegistry, phRegistry, importerRegistry, fileWatcherNotificationHandler, fileTreeWatcher, workspaceHolder, fileWatcherManager);
    pm.initWatcher();
    HttpJsonRequest httpJsonRequest = mock(HttpJsonRequest.class, new SelfReturningAnswer());
    //List<ProjectConfigDto> modules = new ArrayList<>();
    projects = new ArrayList<>();
    addMockedProjectConfigDto(myProjectType, "my_project");
    when(httpJsonRequestFactory.fromLink(any())).thenReturn(httpJsonRequest);
    when(httpJsonRequest.request()).thenReturn(httpJsonResponse);
    when(httpJsonResponse.asDto(WorkspaceDto.class)).thenReturn(usersWorkspaceMock);
    when(usersWorkspaceMock.getConfig()).thenReturn(workspaceConfigMock);
    when(workspaceConfigMock.getProjects()).thenReturn(projects);
    //        verify(httpJsonRequestFactory).fromLink(eq(DtoFactory.newDto(Link.class)
    //                                                             .withHref(apiEndpoint + "/workspace/" + workspace + "/project")
    //                                                             .withMethod(PUT)));
    DependencySupplierImpl dependencies = new DependencySupplierImpl();
    dependencies.addInstance(ProjectTypeRegistry.class, ptRegistry);
    dependencies.addInstance(UserDao.class, userDao);
    dependencies.addInstance(ProjectManager.class, pm);
    dependencies.addInstance(ProjectImporterRegistry.class, importerRegistry);
    dependencies.addInstance(ProjectHandlerRegistry.class, phRegistry);
    dependencies.addInstance(EventService.class, eventService);
    dependencies.addInstance(ProjectServiceLinksInjector.class, projectServiceLinksInjector);
    ResourceBinder resources = new ResourceBinderImpl();
    ProviderBinder providers = ProviderBinder.getInstance();
    EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), dependencies, new RequestHandlerImpl(new RequestDispatcher(resources), providers), null);
    launcher = new ResourceLauncher(processor);
    processor.addApplication(new Application() {

        @Override
        public Set<Class<?>> getClasses() {
            return java.util.Collections.<Class<?>>singleton(ProjectService.class);
        }

        @Override
        public Set<Object> getSingletons() {
            return new HashSet<>(Arrays.asList(new ApiExceptionMapper()));
        }
    });
    ApplicationContext.setCurrent(anApplicationContext().withProviders(providers).build());
    env = org.eclipse.che.commons.env.EnvironmentContext.getCurrent();
}
Example 91
Project: DevTools-master  File: ProjectServiceTest.java View source code
@BeforeMethod
public void setUp() throws Exception {
    WorkspaceProjectsSyncer workspaceHolder = new WsAgentTestBase.TestWorkspaceHolder();
    File root = new File(FS_PATH);
    if (root.exists()) {
        IoUtil.deleteRecursive(root);
    }
    root.mkdir();
    File indexDir = new File(INDEX_PATH);
    if (indexDir.exists()) {
        IoUtil.deleteRecursive(indexDir);
    }
    indexDir.mkdir();
    Set<PathMatcher> filters = new HashSet<>();
    filters.add( path -> {
        for (java.nio.file.Path pathElement : path) {
            if (pathElement == null || EXCLUDE_SEARCH_PATH.equals(pathElement.toString())) {
                return true;
            }
        }
        return false;
    });
    FSLuceneSearcherProvider sProvider = new FSLuceneSearcherProvider(indexDir, filters);
    vfsProvider = new LocalVirtualFileSystemProvider(root, sProvider);
    final EventService eventService = new EventService();
    // PTs for test
    ProjectTypeDef chuck = new ProjectTypeDef("chuck_project_type", "chuck_project_type", true, false) {

        {
            addConstantDefinition("x", "attr description", new AttributeValue(Arrays.asList("a", "b")));
        }
    };
    Set<ProjectTypeDef> projectTypes = new HashSet<>();
    final LocalProjectType myProjectType = new LocalProjectType("my_project_type", "my project type");
    projectTypes.add(myProjectType);
    projectTypes.add(new LocalProjectType("module_type", "module type"));
    projectTypes.add(chuck);
    ptRegistry = new ProjectTypeRegistry(projectTypes);
    phRegistry = new ProjectHandlerRegistry(new HashSet<>());
    importerRegistry = new ProjectImporterRegistry(Collections.<ProjectImporter>emptySet());
    projectServiceLinksInjector = new ProjectServiceLinksInjector();
    projectRegistry = new ProjectRegistry(workspaceHolder, vfsProvider, ptRegistry, phRegistry, eventService);
    projectRegistry.initProjects();
    FileWatcherNotificationHandler fileWatcherNotificationHandler = new DefaultFileWatcherNotificationHandler(vfsProvider);
    FileTreeWatcher fileTreeWatcher = new FileTreeWatcher(root, new HashSet<>(), fileWatcherNotificationHandler);
    pm = new ProjectManager(vfsProvider, ptRegistry, projectRegistry, phRegistry, importerRegistry, fileWatcherNotificationHandler, fileTreeWatcher, workspaceHolder, fileWatcherManager);
    pm.initWatcher();
    HttpJsonRequest httpJsonRequest = mock(HttpJsonRequest.class, new SelfReturningAnswer());
    //List<ProjectConfigDto> modules = new ArrayList<>();
    projects = new ArrayList<>();
    addMockedProjectConfigDto(myProjectType, "my_project");
    when(httpJsonRequestFactory.fromLink(any())).thenReturn(httpJsonRequest);
    when(httpJsonRequest.request()).thenReturn(httpJsonResponse);
    when(httpJsonResponse.asDto(WorkspaceDto.class)).thenReturn(usersWorkspaceMock);
    when(usersWorkspaceMock.getConfig()).thenReturn(workspaceConfigMock);
    when(workspaceConfigMock.getProjects()).thenReturn(projects);
    //        verify(httpJsonRequestFactory).fromLink(eq(DtoFactory.newDto(Link.class)
    //                                                             .withHref(apiEndpoint + "/workspace/" + workspace + "/project")
    //                                                             .withMethod(PUT)));
    DependencySupplierImpl dependencies = new DependencySupplierImpl();
    dependencies.addInstance(ProjectTypeRegistry.class, ptRegistry);
    dependencies.addInstance(UserDao.class, userDao);
    dependencies.addInstance(ProjectManager.class, pm);
    dependencies.addInstance(ProjectImporterRegistry.class, importerRegistry);
    dependencies.addInstance(ProjectHandlerRegistry.class, phRegistry);
    dependencies.addInstance(EventService.class, eventService);
    dependencies.addInstance(ProjectServiceLinksInjector.class, projectServiceLinksInjector);
    ResourceBinder resources = new ResourceBinderImpl();
    ProviderBinder providers = ProviderBinder.getInstance();
    EverrestProcessor processor = new EverrestProcessor(new EverrestConfiguration(), dependencies, new RequestHandlerImpl(new RequestDispatcher(resources), providers), null);
    launcher = new ResourceLauncher(processor);
    processor.addApplication(new Application() {

        @Override
        public Set<Class<?>> getClasses() {
            return java.util.Collections.<Class<?>>singleton(ProjectService.class);
        }

        @Override
        public Set<Object> getSingletons() {
            return new HashSet<>(Arrays.asList(new ApiExceptionMapper()));
        }
    });
    ApplicationContext.setCurrent(anApplicationContext().withProviders(providers).build());
    env = org.eclipse.che.commons.env.EnvironmentContext.getCurrent();
}
Example 92
Project: jena-sparql-api-master  File: MySpringBootServletInitializer.java View source code
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
}
Example 93
Project: ameba-container-grizzly-master  File: GrizzlyHttpContainerProvider.java View source code
@Override
public <T> T createContainer(Class<T> type, Application application) throws ProcessingException {
    if (HttpHandler.class == type || GrizzlyHttpContainer.class == type) {
        return type.cast(new GrizzlyHttpContainer(application));
    }
    return null;
}
Example 94
Project: compatibility-master  File: ExceptionMapperWithApplicationInjection.java View source code
@Override
public Response toResponse(NullPointerException exception) {
    StringBuilder builder = new StringBuilder();
    builder.append("Application:" + (application != null));
    return Response.status(200).entity(builder.toString()).type(MediaType.TEXT_PLAIN).build();
}
Example 95
Project: koshinuke.java-master  File: SimpleAppDescriptor.java View source code
public Class<? extends Application> getApplicationClass() {
    return this.clazz;
}
Example 96
Project: cyREST-master  File: GlobalResourceTest.java View source code
@Override
protected Application configure() {
    return new ResourceConfig(GlobalTableResource.class);
}
Example 97
Project: jersey2-restfull-examples-master  File: PathParamTest.java View source code
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    return new MyApplication();
}
Example 98
Project: neighborhoodPSS-master  File: MyResourceTest.java View source code
protected Application configure() {
    return new ResourceConfig(MyResource.class);
}
Example 99
Project: boon-jaxrs-provider-master  File: MockRuntimeDelegate.java View source code
@Override
public <T> T createEndpoint(final Application app, final Class<T> type) {
    throw new UnsupportedOperationException();
}
Example 100
Project: clickstream-rest-proxy-master  File: PingServiceTest.java View source code
@Override
protected Application configure() {
    return new ResourceConfig(PingService.class);
}
Example 101
Project: dropwizard-weld-master  File: JerseyCdiSpike.java View source code
@Override
protected Application configure() {
    weld = new Weld();
    container = weld.initialize();
    return new ResourceConfig(DummyResource.class);
}