Esempio n. 1
0
  /**
   * Will create a ServiceLocator after doing test-specific bindings from the TestModule
   *
   * @param name The name of the service locator to create. Should be unique per test, otherwise
   *     this method will fail.
   * @param parent The parent locator this one should have. May be null
   * @param modules The test modules, that will do test specific bindings. May be null
   * @return A service locator with all the test specific bindings bound
   */
  public static ServiceLocator create(
      String name, ServiceLocator parent, HK2TestModule... modules) {
    ServiceLocator retVal = factory.find(name);
    Assert.assertNull(
        "There is already a service locator of this name, change names to ensure a clean test: "
            + name,
        retVal);

    retVal = factory.create(name, parent);

    if (modules == null || modules.length <= 0) return retVal;

    DynamicConfigurationService dcs = retVal.getService(DynamicConfigurationService.class);
    Assert.assertNotNull("Their is no DynamicConfigurationService.  Epic fail", dcs);

    DynamicConfiguration dc = dcs.createDynamicConfiguration();
    Assert.assertNotNull("DynamicConfiguration creation failure", dc);

    for (HK2TestModule module : modules) {
      module.configure(dc);
    }

    dc.commit();

    return retVal;
  }
Esempio n. 2
0
  /** Tests that a third-party service that fails in dispose */
  @Test
  public void testFailingInDisposeThirdPartyService() {
    ServiceLocator locator = LocatorHelper.getServiceLocator(RecordingErrorService.class);

    AlwaysFailInDisposeActiveDescriptor thirdPartyDescriptor =
        new AlwaysFailInDisposeActiveDescriptor();

    ServiceLocatorUtilities.addOneDescriptor(locator, thirdPartyDescriptor);

    ActiveDescriptor<?> serviceDescriptor =
        locator.getBestDescriptor(
            BuilderHelper.createContractFilter(SimpleService.class.getName()));
    Assert.assertNotNull(serviceDescriptor);

    ServiceHandle<SimpleService> handle = locator.getServiceHandle(SimpleService.class);
    Assert.assertNotNull(handle);
    Assert.assertNotNull(handle.getService());

    handle.destroy();

    List<ErrorInformation> errors =
        locator.getService(RecordingErrorService.class).getAndClearErrors();

    Assert.assertEquals(1, errors.size());

    ErrorInformation ei = errors.get(0);

    Assert.assertEquals(ErrorType.SERVICE_DESTRUCTION_FAILURE, ei.getErrorType());
    Assert.assertEquals(serviceDescriptor, ei.getDescriptor());
    Assert.assertNull(ei.getInjectee());

    Throwable associatedException = ei.getAssociatedException();
    Assert.assertTrue(associatedException.getMessage().contains(ERROR_STRING));
  }
Esempio n. 3
0
  /**
   * Tests that a service that fails in the constructor has the error passed to the error service
   */
  @Test
  public void testServiceFailsInConstructor() {
    ServiceLocator locator =
        LocatorHelper.getServiceLocator(
            RecordingErrorService.class, ServiceFailsInConstructor.class);

    ActiveDescriptor<?> serviceDescriptor =
        locator.getBestDescriptor(
            BuilderHelper.createContractFilter(ServiceFailsInConstructor.class.getName()));
    Assert.assertNotNull(serviceDescriptor);

    try {
      locator.getService(ServiceFailsInConstructor.class);
      Assert.fail("Should have failed");
    } catch (MultiException me) {
      Assert.assertTrue(me.getMessage().contains(ERROR_STRING));
    }

    List<ErrorInformation> errors =
        locator.getService(RecordingErrorService.class).getAndClearErrors();

    Assert.assertEquals(1, errors.size());

    ErrorInformation ei = errors.get(0);

    Assert.assertEquals(ErrorType.SERVICE_CREATION_FAILURE, ei.getErrorType());
    Assert.assertEquals(serviceDescriptor, ei.getDescriptor());
    Assert.assertNull(ei.getInjectee());

    Throwable associatedException = ei.getAssociatedException();
    Assert.assertTrue(associatedException.getMessage().contains(ERROR_STRING));
  }
Esempio n. 4
0
  /**
   * This test ensures that spending forever in an onProgress does not hold up other threads from
   * calling cancel on the RLC
   */
  @Test
  public void testOnProgressCancelDeadlock() {
    ServiceLocator locator = Utilities.getServiceLocator(DeadLock1Listener.class);

    RunLevelController rlc = locator.getService(RunLevelController.class);
    rlc.proceedTo(1);
  }
Esempio n. 5
0
  private static void bind(ServiceLocator locator, Binder binder) {
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    locator.inject(binder);
    binder.bind(dc);

    dc.commit();
  }
Esempio n. 6
0
  private String getLogNames(String instanceName, String type) throws IOException {

    if (habitat.getService(LogManager.class) == null) {
      // the logger service is not install, so we cannot rely on it.
      // return an error
      throw new IOException("The GlassFish LogManager Service is not available. Not installed?");
    }

    LogFilter logFilter = habitat.getService(LogFilter.class);

    return convertQueryResult(logFilter.getInstanceLogFileNames(instanceName), type);
  }
  /**
   * @see org.glassfish.internal.api.ClassLoaderHierarchy#getAppLibClassLoader(String, List<URI>)
   */
  public ClassLoader getAppLibClassLoader(String application, List<URI> libURIs)
      throws MalformedURLException {

    ClassLoaderHierarchy clh = habitat.getService(ClassLoaderHierarchy.class);
    DelegatingClassLoader connectorCL = clh.getConnectorClassLoader(application);

    if (libURIs == null || libURIs.isEmpty()) {
      // Optimization: when there are no libraries, why create an empty
      // class loader in the hierarchy? Instead return the parent.
      return connectorCL;
    }

    final ClassLoader commonCL = commonCLS.getCommonClassLoader();
    DelegatingClassLoader applibCL =
        AccessController.doPrivileged(
            new PrivilegedAction<DelegatingClassLoader>() {
              public DelegatingClassLoader run() {
                return new DelegatingClassLoader(commonCL);
              }
            });

    // order of classfinders is important here :
    // connector's classfinders should be added before libraries' classfinders
    // as the delegation hierarchy is appCL->app-libsCL->connectorCL->commonCL->API-CL
    // since we are merging connector and applib classfinders to be at same level,
    // connector classfinders need to be be before applib classfinders in the horizontal
    // search path
    for (DelegatingClassLoader.ClassFinder cf : connectorCL.getDelegates()) {
      applibCL.addDelegate(cf);
    }
    addDelegates(libURIs, applibCL);

    return applibCL;
  }
Esempio n. 8
0
 private synchronized File domainRoot() {
   if (domainRoot == null) {
     ServerEnvironment serverEnv = habitat.getService(ServerEnvironment.class);
     domainRoot = serverEnv.getDomainRoot();
   }
   return domainRoot;
 }
 @Test
 public void verifyPerThreadScoped() {
   ServiceHandle<KryoFactory> serviceHandle = locator.getServiceHandle(KryoFactory.class);
   ActiveDescriptor<KryoFactory> activeDescriptor = serviceHandle.getActiveDescriptor();
   Class<? extends Annotation> scope = activeDescriptor.getScopeAnnotation();
   assertThat(scope).isEqualTo(Singleton.class);
 }
  public static void initRecovery(boolean force) {
    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "initRecovery:recoveryInitialized: " + recoveryInitialized);
    }

    if (recoveryInitialized) {
      // Only start initial recovery if it wasn't started before
      return;
    }

    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "initRecovery:properties: " + properties);
    }
    if (properties == null) {
      if (force) {
        _logger.log(Level.WARNING, "", new IllegalStateException());
      }
      return;
    }

    // Start if force is true or automatic-recovery is set
    String value = properties.getProperty(Configuration.MANUAL_RECOVERY);
    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "initRecovery:Configuration.MANUAL_RECOVERY: " + value);
    }
    if (force || (isValueSet(value) && "true".equals(value))) {
      recoveryInitialized = true;

      ServiceLocator serviceLocator = (ServiceLocator) properties.get(HABITAT);
      if (serviceLocator != null) {
        ProcessEnvironment processEnv = serviceLocator.getService(ProcessEnvironment.class);
        if (processEnv.getProcessType().isServer()) {
          // Start ResourceManager if it hadn't started yet
          serviceLocator.getAllServices(BuilderHelper.createNameFilter("ResourceManager"));
          value = properties.getProperty("pending-txn-cleanup-interval");
          int interval = -1;
          if (isValueSet(value)) {
            interval = Integer.parseInt(value);
          }
          new RecoveryHelperThread(serviceLocator, interval).start();
        }
        // Release all locks
        RecoveryManager.startResyncThread();
        if (_logger.isLoggable(Level.FINE)) _logger.log(Level.FINE, "[JTS] Started ResyncThread");
      }
    }
  }
Esempio n. 11
0
 @Before
 public void setUp() {
   habitat = getHabitat();
   parameters = new ParameterMap();
   cr = habitat.getService(CommandRunner.class);
   assertTrue(cr != null);
   Resources resources = habitat.<Domain>getService(Domain.class).getResources();
   context =
       new AdminCommandContextImpl(
           LogDomains.getLogger(ListJavaMailResourcesTest.class, LogDomains.ADMIN_LOGGER),
           new PropsFileActionReporter());
   for (Resource resource : resources.getResources()) {
     if (resource instanceof MailResource) {
       origNum = origNum + 1;
     }
   }
 }
  protected void configureSpdySupport(
      final ServiceLocator locator,
      final NetworkListener listener,
      final Spdy spdyElement,
      final FilterChainBuilder builder,
      final boolean secure) {
    if (spdyElement != null && spdyElement.getEnabled()) {

      boolean isNpnMode =
          spdyElement.getMode() == null || "npn".equalsIgnoreCase(spdyElement.getMode());

      // Spdy without NPN is supported, but warn that there may
      // be consequences to this configuration.
      if (!secure && isNpnMode) {
        LOGGER.log(
            Level.WARNING,
            "SSL is not enabled for listener {0}.  SPDY support will be enabled, but will not be secured.  Some clients may not be able to use SPDY in this configuration.",
            listener.getName());
      }

      // first try to lookup a service appropriate for the mode
      // that has been configured.
      AddOn spdyAddon = locator.getService(AddOn.class, "spdy");

      // if no service was found, attempt to load via reflection.
      if (spdyAddon == null) {
        Class<?> spdyMode;
        try {
          spdyMode = Utils.loadClass("org.glassfish.grizzly.spdy.SpdyMode");
        } catch (ClassNotFoundException cnfe) {
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine(
                "Unable to load class org.glassfish.grizzly.spdy.SpdyMode.  SPDY support cannot be enabled");
          }
          return;
        }
        Object[] enumConstants = spdyMode.getEnumConstants();
        Object mode = ((isNpnMode) ? enumConstants[1] : enumConstants[0]);
        spdyAddon = loadAddOn("org.glassfish.grizzly.spdy.SpdyAddOn", new Class[] {spdyMode}, mode);
      }

      if (spdyAddon != null) {
        // Configure SpdyAddOn
        configureElement(locator, listener, spdyElement, spdyAddon);

        // Spdy requires access to more information compared to the other addons
        // that are currently leveraged.  As such, we'll need to mock out a
        // Grizzly NetworkListener to pass to the addon.  This mock object will
        // only provide the information necessary for the addon to operate.
        // It will be important to keep this mock in sync with the details the
        // addon requires.
        spdyAddon.setup(createMockListener(), builder);
        isSpdyEnabled = true;
      }
    }
  }
  /**
   * Populate serviceLocator with services from classpath
   *
   * @see <a
   *     href="https://hk2.java.net/2.4.0-b16/inhabitant-generator.html">https://hk2.java.net/2.4.0-b16/inhabitant-generator.html</a>
   */
  private void populate(ServiceLocator serviceLocator) {
    DynamicConfigurationService dcs = serviceLocator.getService(DynamicConfigurationService.class);
    Populator populator = dcs.getPopulator();

    try {
      populator.populate();
    } catch (IOException | MultiException e) {
      throw new MultiException(e);
    }
  }
Esempio n. 14
0
  /** Ensures we can add a scope to a service with no scope at all */
  @Test
  public void testGiveClassWithNoScopeAScope() {
    ServiceLocator locator = LocatorHelper.create();
    ServiceLocatorUtilities.enableLookupExceptions(locator);

    Descriptor desc =
        BuilderHelper.activeLink(NoScopeService.class)
            .to(NoScopeService.class)
            .in(ServiceLocatorUtilities.getSingletonAnnotation())
            .build();

    ServiceLocatorUtilities.addOneDescriptor(locator, desc);

    NoScopeService one = locator.getService(NoScopeService.class);
    NoScopeService two = locator.getService(NoScopeService.class);

    Assert.assertNotNull(one);
    Assert.assertEquals(one, two);
  }
Esempio n. 15
0
 private void deleteJavaMailResource() {
   parameters = new ParameterMap();
   parameters.set("jndi_name", "mailresource");
   DeleteJavaMailResource deleteCommand = habitat.getService(DeleteJavaMailResource.class);
   assertTrue(deleteCommand != null);
   cr.getCommandInvocation("delete-javamail-resource", context.getActionReport(), adminSubject())
       .parameters(parameters)
       .execute(deleteCommand);
   assertEquals(ActionReport.ExitCode.SUCCESS, context.getActionReport().getActionExitCode());
 }
Esempio n. 16
0
  /**
   * Ensures that you can change from one hard-coded scope on the descriptor to a different scope
   */
  @Test
  public void testSwitchFromExplicitScopeToGhostedScope() {
    ServiceLocator locator = LocatorHelper.create();
    ServiceLocatorUtilities.enableLookupExceptions(locator);
    ServiceLocatorUtilities.addClasses(locator, GhostedContext.class);

    Descriptor desc =
        BuilderHelper.activeLink(SingletonScopedService.class)
            .to(SingletonScopedService.class)
            .in(new GhostedScopeImpl(0))
            .build();

    ServiceLocatorUtilities.addOneDescriptor(locator, desc);

    SingletonScopedService one = locator.getService(SingletonScopedService.class);
    SingletonScopedService two = locator.getService(SingletonScopedService.class);

    Assert.assertNotNull(one);
    Assert.assertNotSame(one, two);
  }
 @Override
 public void initialize(final ServiceLocator locator) {
   this.locator = locator;
   if (locator != null) {
     injector = locator.getService(Injector.class);
     MutableServiceLocatorProvider serviceLocatorProvider =
         injector.getInstance(MutableServiceLocatorProvider.class);
     if (serviceLocatorProvider != null) {
       serviceLocatorProvider.setServiceLocator(locator);
     }
   }
 }
Esempio n. 18
0
  /* package */ @SuppressWarnings({"unchecked"})
  void register() {
    ServiceLocator locator = getServiceLocator();

    ActiveDescriptor<?> myselfReified = locator.reifyDescriptor(this);

    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    //        habitat.add(this);
    HK2Loader loader = this.model.classLoaderHolder;

    Set<Type> ctrs = new HashSet<Type>();
    ctrs.add(myselfReified.getImplementationClass());

    if (ConfigBean.class.isAssignableFrom(this.getClass())) {
      ctrs.add(ConfigBean.class);
    }

    DomDescriptor<Dom> domDesc =
        new DomDescriptor<Dom>(
            this, ctrs, Singleton.class, getImplementation(), new HashSet<Annotation>());
    domDesc.setLoader(loader);
    domDescriptor = dc.addActiveDescriptor(domDesc, false);

    String key = getKey();
    for (String contract : model.contracts) {
      ActiveDescriptor<Dom> alias = new AliasDescriptor<Dom>(locator, domDescriptor, contract, key);
      dc.addActiveDescriptor(alias, false);
    }
    if (key != null) {
      ActiveDescriptor<Dom> alias =
          new AliasDescriptor<Dom>(locator, domDescriptor, model.targetTypeName, key);
      dc.addActiveDescriptor(alias, false);
    }

    dc.commit();

    serviceHandle = getHabitat().getServiceHandle(domDescriptor);
  }
Esempio n. 19
0
  /**
   * Test of execute method, of class ListJdbcResource. delete-javamail-resource mailresource
   * list-javamail-resources
   */
  @Test
  public void testExecuteSuccessListNoMailResource() {
    createJavaMailResource();

    parameters = new ParameterMap();
    org.glassfish.resources.javamail.admin.cli.ListJavaMailResources listCommand =
        habitat.getService(org.glassfish.resources.javamail.admin.cli.ListJavaMailResources.class);
    cr.getCommandInvocation("list-javamail-resources", context.getActionReport(), adminSubject())
        .parameters(parameters)
        .execute(listCommand);

    List<ActionReport.MessagePart> list =
        context.getActionReport().getTopMessagePart().getChildren();
    assertEquals(origNum + 1, list.size());
    origNum = origNum + 1; // as we newly created a resource after test "setup".

    deleteJavaMailResource();
    parameters = new ParameterMap();
    listCommand =
        habitat.getService(org.glassfish.resources.javamail.admin.cli.ListJavaMailResources.class);
    context =
        new AdminCommandContextImpl(
            LogDomains.getLogger(ListJavaMailResourcesTest.class, LogDomains.ADMIN_LOGGER),
            new PropsFileActionReporter());
    cr.getCommandInvocation("list-javamail-resources", context.getActionReport(), adminSubject())
        .parameters(parameters)
        .execute(listCommand);
    list = context.getActionReport().getTopMessagePart().getChildren();
    if ((origNum - 1) == 0) {
      // Nothing to list.
    } else {
      assertEquals(origNum - 1, list.size());
    }
    List<String> listStr = new ArrayList<String>();
    for (MessagePart mp : list) {
      listStr.add(mp.getMessage());
    }
    assertFalse(listStr.contains("mailresource"));
    assertEquals(ActionReport.ExitCode.SUCCESS, context.getActionReport().getActionExitCode());
  }
Esempio n. 20
0
 private void createJavaMailResource() {
   parameters = new ParameterMap();
   parameters.set("mailhost", "localhost");
   parameters.set("mailuser", "test");
   parameters.set("fromaddress", "*****@*****.**");
   parameters.set("jndi_name", "mailresource");
   CreateJavaMailResource createCommand = habitat.getService(CreateJavaMailResource.class);
   assertTrue(createCommand != null);
   cr.getCommandInvocation("create-javamail-resource", context.getActionReport(), adminSubject())
       .parameters(parameters)
       .execute(createCommand);
   assertEquals(ActionReport.ExitCode.SUCCESS, context.getActionReport().getActionExitCode());
 }
Esempio n. 21
0
  /**
   * Tests that a service that fails but tells HK2 to NOT report the failure to the error handler
   * service
   */
  @Test
  public void testSilentFailureInPostConstruct() {
    ServiceLocator locator =
        LocatorHelper.getServiceLocator(
            RecordingErrorService.class, ServiceDirectsNoErrorService.class);

    ActiveDescriptor<?> serviceDescriptor =
        locator.getBestDescriptor(
            BuilderHelper.createContractFilter(ServiceDirectsNoErrorService.class.getName()));
    Assert.assertNotNull(serviceDescriptor);

    try {
      locator.getService(ServiceDirectsNoErrorService.class);
      Assert.fail("Should have failed");
    } catch (MultiException me) {
      Assert.assertTrue(me.getMessage().contains(ERROR_STRING));
    }

    List<ErrorInformation> errors =
        locator.getService(RecordingErrorService.class).getAndClearErrors();

    Assert.assertEquals(0, errors.size());
  }
Esempio n. 22
0
  /**
   * Enables the Configuration subsystem of HK2. This call is idempotent
   *
   * @param locator The non-null service locator in which to enable the configuration subsystem
   */
  public static void enableConfigurationSystem(ServiceLocator locator) {
    ServiceHandle<ConfiguredByContext> alreadyThere =
        locator.getServiceHandle(ConfiguredByContext.class);
    if (alreadyThere != null) {
      // The assumption is that if this service is there then this is already on, don't do it again
      return;
    }

    ManagerUtilities.enableConfigurationHub(locator);

    ServiceLocatorUtilities.addClasses(locator, true, ConfiguredValidator.class);

    ServiceLocatorUtilities.addClasses(
        locator,
        true,
        ConfiguredByContext.class,
        ConfigurationValidationService.class,
        ConfiguredByInjectionResolver.class,
        ConfigurationListener.class,
        ChildInjectResolverImpl.class);

    // Creates demand, starts the thing off
    locator.getService(ConfigurationListener.class);
  }
Esempio n. 23
0
  /** Tests that we can change the value of a field in a scope with a ghost added annotation */
  @Test
  public void testModifyExistingScopeWithDifferentValue() {
    ServiceLocator locator = LocatorHelper.create();
    ServiceLocatorUtilities.addClasses(locator, GhostedContext.class);

    Descriptor desc =
        BuilderHelper.activeLink(GhostedServiceWithValue.class)
            .to(GhostedServiceWithValue.class)
            .in(new GhostedScopeImpl(0))
            .build();

    ServiceLocatorUtilities.addOneDescriptor(locator, desc);

    GhostedServiceWithValue ghosted = locator.getService(GhostedServiceWithValue.class);
    Assert.assertNotNull(ghosted);

    ActiveDescriptor<?> gDesck = ghosted.getDescriptor();

    Annotation anno = gDesck.getScopeAsAnnotation();
    Assert.assertNotNull(anno);

    GhostedScope gs = (GhostedScope) anno;
    Assert.assertEquals(0, gs.value());
  }
Esempio n. 24
0
 /** Test of execute method, of class ListJavaMailResources. list-javamail-resources */
 @Test
 public void testExecuteSuccessListOriginal() {
   org.glassfish.resources.javamail.admin.cli.ListJavaMailResources listCommand =
       habitat.getService(org.glassfish.resources.javamail.admin.cli.ListJavaMailResources.class);
   cr.getCommandInvocation("list-javamail-resources", context.getActionReport(), adminSubject())
       .parameters(parameters)
       .execute(listCommand);
   List<MessagePart> list = context.getActionReport().getTopMessagePart().getChildren();
   if (origNum == 0) {
     // Nothing to list
   } else {
     assertEquals(origNum, list.size());
   }
   assertEquals(ActionReport.ExitCode.SUCCESS, context.getActionReport().getActionExitCode());
 }
    @Inject
    private PersistenceUnitInjectionResolver(final ServiceLocator locator) {
      // Look for persistence units.
      final ServletConfig servletConfig = locator.getService(ServletConfig.class);

      for (final Enumeration parameterNames = servletConfig.getInitParameterNames();
          parameterNames.hasMoreElements(); ) {
        final String key = (String) parameterNames.nextElement();

        if (key.startsWith(PERSISTENCE_UNIT_PREFIX)) {
          persistenceUnits.put(
              key.substring(PERSISTENCE_UNIT_PREFIX.length()),
              "java:comp/env/" + servletConfig.getInitParameter(key));
        }
      }
    }
Esempio n. 26
0
 private Application createApplication(Class<? extends Application> applicationClass) {
   // need to handle ResourceConfig and Application separately as invoking forContract() on these
   // will trigger the factories which we don't want at this point
   if (applicationClass == ResourceConfig.class) {
     return new ResourceConfig();
   } else if (applicationClass == Application.class) {
     return new Application();
   } else {
     Application app = locator.createAndInitialize(applicationClass);
     if (app instanceof ResourceConfig) {
       final ResourceConfig _rc = (ResourceConfig) app;
       final Class<? extends Application> innerAppClass = _rc.getApplicationClass();
       if (innerAppClass != null) {
         final Application innerApp = createApplication(innerAppClass);
         _rc.setApplication(innerApp);
       }
     }
     return app;
   }
 }
    public void run() {
      ResourceRecoveryManager recoveryManager =
          serviceLocator.getService(ResourceRecoveryManager.class);
      if (interval <= 0) {
        // Only start the recovery thread if the interval value is set, and set to a positive value
        return;
      }

      if (_logger.isLoggable(Level.INFO)) {
        _logger.log(
            Level.INFO,
            "Asynchronous thread for incomplete " + "tx is enabled with interval " + interval);
      }
      int prevSize = 0;
      try {
        while (true) {
          Thread.sleep(interval * 1000L);
          if (!RecoveryManager.isIncompleteTxRecoveryRequired()) {
            if (_logger.isLoggable(Level.FINE))
              _logger.log(
                  Level.FINE,
                  "Incomplete transaction recovery is "
                      + "not requeired,  waiting for the next interval");
            continue;
          }
          if (RecoveryManager.sizeOfInCompleteTx() <= prevSize) {
            if (_logger.isLoggable(Level.FINE))
              _logger.log(
                  Level.FINE,
                  "Incomplete transaction recovery is "
                      + "not required,  waiting for the next interval SIZE");
            continue;
          }
          prevSize = RecoveryManager.sizeOfInCompleteTx();
          recoveryManager.recoverIncompleteTx(false, null);
        }
      } catch (Exception ex) {
        if (_logger.isLoggable(Level.FINE))
          _logger.log(Level.FINE, " Exception occurred in recoverInCompleteTx ");
      }
    }
Esempio n. 28
0
  /**
   * Test of execute method, of class ListJavaMailResource. create-javamail-resource --mailuser=test
   * --mailhost=localhost [email protected] mailresource list-javamail-resources
   */
  @Test
  public void testExecuteSuccessListMailResource() {
    createJavaMailResource();

    parameters = new ParameterMap();
    org.glassfish.resources.javamail.admin.cli.ListJavaMailResources listCommand =
        habitat.getService(org.glassfish.resources.javamail.admin.cli.ListJavaMailResources.class);
    assertTrue(listCommand != null);
    cr.getCommandInvocation("list-javamail-resources", context.getActionReport(), adminSubject())
        .parameters(parameters)
        .execute(listCommand);
    List<MessagePart> list = context.getActionReport().getTopMessagePart().getChildren();
    assertEquals(origNum + 1, list.size());
    List<String> listStr = new ArrayList<String>();
    for (MessagePart mp : list) {
      listStr.add(mp.getMessage());
    }
    assertTrue(listStr.contains("mailresource"));
    assertEquals(ActionReport.ExitCode.SUCCESS, context.getActionReport().getActionExitCode());
    deleteJavaMailResource();
  }
  /**
   * Executes the command with the command parameters passed as Properties where the keys are the
   * parameter names and the values the parameter values
   *
   * @param context information
   */
  public void execute(AdminCommandContext context) {

    final ActionReport report = context.getActionReport();

    try {
      Collection<ManagedExecutorService> managedExecutorServices =
          domain.getResources().getResources(ManagedExecutorService.class);
      List<Map<String, String>> resourcesList = new ArrayList<Map<String, String>>();
      List<DefaultResourceProxy> drps = habitat.getAllServices(DefaultResourceProxy.class);

      for (ManagedExecutorService managedExecutorService : managedExecutorServices) {
        String jndiName = managedExecutorService.getJndiName();
        if (bindableResourcesHelper.resourceExists(jndiName, target)) {
          ActionReport.MessagePart part = report.getTopMessagePart().addChild();
          part.setMessage(jndiName);
          Map<String, String> resourceNameMap = new HashMap<String, String>();
          String logicalName = DefaultResourceProxy.Util.getLogicalName(drps, jndiName);
          if (logicalName != null) {
            resourceNameMap.put("logical-jndi-name", logicalName);
          }
          resourceNameMap.put("name", jndiName);
          resourcesList.add(resourceNameMap);
        }
      }

      Properties extraProperties = new Properties();
      extraProperties.put("managedExecutorServices", resourcesList);
      report.setExtraProperties(extraProperties);
    } catch (Exception e) {
      report.setMessage(
          localStrings.getLocalString(
              "list.managed.executor.service.failed", "List managed executor services failed"));
      report.setActionExitCode(ActionReport.ExitCode.FAILURE);
      report.setFailureCause(e);
      return;
    }
    report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
  }
Esempio n. 30
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }