/**
   * 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));
  }
Example #2
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);
  }
Example #3
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);
  }
Example #4
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;
  }
  /** 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));
  }
Example #6
0
 private synchronized File domainRoot() {
   if (domainRoot == null) {
     ServerEnvironment serverEnv = habitat.getService(ServerEnvironment.class);
     domainRoot = serverEnv.getDomainRoot();
   }
   return domainRoot;
 }
  /**
   * @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;
  }
 @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;
     }
   }
 }
Example #9
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();
  }
  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);
    }
  }
 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());
 }
 @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);
     }
   }
 }
  /**
   * 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());
  }
 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());
 }
Example #16
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());
  }
 /** 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));
        }
      }
    }
  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");
      }
    }
  }
Example #20
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);
  }
Example #21
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);
  }
    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 ");
      }
    }
  /**
   * 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();
  }
Example #24
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);
  }
Example #25
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());
  }
Example #26
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);
  }
  public static synchronized Properties getJTSProperties(
      ServiceLocator serviceLocator, boolean isORBAvailable) {
    if (orbAvailable == isORBAvailable && properties != null) {
      // We will need to update the properties if ORB availability changed
      return properties;
    }

    Properties jtsProperties = new Properties();
    if (serviceLocator != null) {
      jtsProperties.put(HABITAT, serviceLocator);
      ProcessEnvironment processEnv = serviceLocator.getService(ProcessEnvironment.class);
      if (processEnv.getProcessType().isServer()) {
        TransactionService txnService =
            serviceLocator.getService(
                TransactionService.class, ServerEnvironment.DEFAULT_INSTANCE_NAME);

        if (txnService != null) {
          jtsProperties.put(Configuration.HEURISTIC_DIRECTION, txnService.getHeuristicDecision());
          jtsProperties.put(Configuration.KEYPOINT_COUNT, txnService.getKeypointInterval());

          String automaticRecovery = txnService.getAutomaticRecovery();
          boolean isAutomaticRecovery =
              (isValueSet(automaticRecovery) && "true".equals(automaticRecovery));
          if (isAutomaticRecovery) {
            _logger.log(Level.FINE, "Recoverable J2EE Server");
            jtsProperties.put(Configuration.MANUAL_RECOVERY, "true");
          }

          boolean disable_distributed_transaction_logging = false;
          String dbLoggingResource = null;
          for (Property prop : txnService.getProperty()) {
            String name = prop.getName();
            String value = prop.getValue();

            if (name.equals("disable-distributed-transaction-logging")) {
              if (isValueSet(value) && "true".equals(value)) {
                disable_distributed_transaction_logging = true;
              }

            } else if (name.equals("xaresource-txn-timeout")) {
              if (isValueSet(value)) {
                _logger.log(Level.FINE, "XAResource transaction timeout is" + value);
                TransactionManagerImpl.setXAResourceTimeOut(Integer.parseInt(value));
              }

            } else if (name.equals("db-logging-resource")) {
              dbLoggingResource = value;
              _logger.log(Level.FINE, "Transaction DB Logging Resource Name" + dbLoggingResource);
              if (dbLoggingResource != null
                  && (" ".equals(dbLoggingResource) || "".equals(dbLoggingResource))) {
                dbLoggingResource = "jdbc/TxnDS";
              }

            } else if (name.equals("xa-servername")) {
              if (isValueSet(value)) {
                jtsProperties.put(JTS_XA_SERVER_NAME, value);
              }

            } else if (name.equals("pending-txn-cleanup-interval")) {
              if (isValueSet(value)) {
                jtsProperties.put("pending-txn-cleanup-interval", value);
              }

            } else if (name.equals(Configuration.COMMIT_ONE_PHASE_DURING_RECOVERY)) {
              if (isValueSet(value)) {
                jtsProperties.put(Configuration.COMMIT_ONE_PHASE_DURING_RECOVERY, value);
              }
            } else if (name.equals("add-wait-point-during-recovery")) {
              if (isValueSet(value)) {
                try {
                  FailureInducer.setWaitPointRecovery(Integer.parseInt(value));
                } catch (Exception e) {
                  _logger.log(Level.WARNING, e.getMessage());
                }
              }
            }
          }

          if (dbLoggingResource != null) {
            disable_distributed_transaction_logging = true;
            jtsProperties.put(Configuration.DB_LOG_RESOURCE, dbLoggingResource);
          }

          /**
           * JTS_SERVER_ID needs to be unique for each for server instance. This will be used as
           * recovery identifier along with the hostname for example: if the hostname is 'tulsa' and
           * iiop-listener-port is 3700 recovery identifier will be tulsa,P3700
           */
          int jtsServerId = DEFAULT_SERVER_ID; // default value

          if (isORBAvailable) {
            jtsServerId =
                serviceLocator
                    .<GlassFishORBHelper>getService(GlassFishORBHelper.class)
                    .getORBInitialPort();
            if (jtsServerId == 0) {
              // XXX Can this ever happen?
              jtsServerId = DEFAULT_SERVER_ID; // default value
            }
          }
          jtsProperties.put(JTS_SERVER_ID, String.valueOf(jtsServerId));

          /* ServerId is an J2SE persistent server activation
            API.  ServerId is scoped at the ORBD.  Since
            There is no ORBD present in J2EE the value of
            ServerId is meaningless - except it must have
            SOME value if persistent POAs are created.
          */

          // For clusters - all servers in the cluster MUST
          // have the same ServerId so when failover happens
          // and requests are delivered to a new server, the
          // ServerId in the request will match the new server.

          String serverId = String.valueOf(DEFAULT_SERVER_ID);
          System.setProperty(J2EE_SERVER_ID_PROP, serverId);

          ServerContext ctx = serviceLocator.getService(ServerContext.class);
          String instanceName = ctx.getInstanceName();

          /**
           * if the auto recovery is true, always transaction logs will be written irrespective of
           * disable_distributed_transaction_logging. if the auto recovery is false, then
           * disable_distributed_transaction_logging will be used to write transaction logs are
           * not.If disable_distributed_transaction_logging is set to false(by default false) logs
           * will be written, set to true logs won't be written.
           */
          if (!isAutomaticRecovery && disable_distributed_transaction_logging) {
            Configuration.disableFileLogging();
          } else {

            // if (dbLoggingResource == null) {
            Domain domain = serviceLocator.getService(Domain.class);
            Server server = domain.getServerNamed(instanceName);

            // Check if the server system property is set
            String logdir = getTXLogDir(server);

            // if not, check if the cluster system property is set
            if (logdir == null) {
              Cluster cluster = server.getCluster();
              if (cluster != null) {
                logdir = getTXLogDir(cluster);
              }
            }

            // No system properties are set - get tx log dir from transaction service
            if (logdir == null) {
              logdir = txnService.getTxLogDir();
            }

            if (logdir == null) {
              logdir = domain.getLogRoot();
              if (logdir == null) {
                // logdir = FileUtil.getAbsolutePath(".." + File.separator + "logs");
                logdir = ".." + File.separator + "logs";
              }
            } else if (!(new File(logdir)).isAbsolute()) {
              if (_logger.isLoggable(Level.FINE)) {
                _logger.log(
                    Level.FINE,
                    "Relative pathname specified for transaction log directory : " + logdir);
              }
              String logroot = domain.getLogRoot();
              if (logroot != null) {
                logdir = logroot + File.separator + logdir;
              } else {
                // logdir = FileUtil.getAbsolutePath(".." + File.separator + "logs"
                // + File.separator + logdir);
                logdir = ".." + File.separator + "logs" + File.separator + logdir;
              }
            }
            logdir += File.separator + instanceName + File.separator + "tx";

            if (_logger.isLoggable(Level.FINE)) {
              _logger.log(Level.FINE, "JTS log directory: " + logdir);
              _logger.log(Level.FINE, "JTS Server id " + jtsServerId);
            }

            jtsProperties.put(Configuration.LOG_DIRECTORY, logdir);
          }
          jtsProperties.put(Configuration.COMMIT_RETRY, txnService.getRetryTimeoutInSeconds());
          jtsProperties.put(Configuration.INSTANCE_NAME, instanceName);
        }
      }
    }

    properties = jtsProperties;
    orbAvailable = isORBAvailable;

    return properties;
  }
  private void bindProvidersAndResources(
      final Set<ComponentProvider> componentProviders,
      final ComponentBag componentBag,
      final Set<Class<?>> resourceClasses,
      final Set<Object> resourceInstances) {

    final JerseyResourceContext resourceContext = locator.getService(JerseyResourceContext.class);
    final DynamicConfiguration dc = Injections.getConfiguration(locator);
    final Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();

    // Merge programmatic resource classes with component classes.
    Set<Class<?>> classes = Sets.newIdentityHashSet();
    classes.addAll(
        Sets.filter(
            componentBag.getClasses(ComponentBag.EXCLUDE_META_PROVIDERS),
            new Predicate<Class<?>>() {
              @Override
              public boolean apply(Class<?> componentClass) {
                return Providers.checkProviderRuntime(
                    componentClass,
                    componentBag.getModel(componentClass),
                    RuntimeType.SERVER,
                    !registeredClasses.contains(componentClass),
                    resourceClasses.contains(componentClass));
              }
            }));
    classes.addAll(resourceClasses);

    // Bind classes.
    for (Class<?> componentClass : classes) {
      ContractProvider model = componentBag.getModel(componentClass);
      if (resourceClasses.contains(componentClass)) {
        if (bindWithComponentProvider(componentClass, model, componentProviders)) {
          continue;
        }

        if (!Resource.isAcceptable(componentClass)) {
          LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
          continue;
        }

        if (model != null
            && !Providers.checkProviderRuntime(
                componentClass,
                model,
                RuntimeType.SERVER,
                !registeredClasses.contains(componentClass),
                true)) {
          model = null;
        }
        resourceContext.unsafeBindResource(componentClass, model, dc);
      } else {
        ProviderBinder.bindProvider(componentClass, model, dc);
      }
    }

    // Merge programmatic resource instances with other component instances.
    Set<Object> instances = Sets.newHashSet();
    instances.addAll(
        Sets.filter(
            componentBag.getInstances(ComponentBag.EXCLUDE_META_PROVIDERS),
            new Predicate<Object>() {
              @Override
              public boolean apply(Object component) {
                final Class<?> componentClass = component.getClass();
                return Providers.checkProviderRuntime(
                    componentClass,
                    componentBag.getModel(componentClass),
                    RuntimeType.SERVER,
                    !registeredClasses.contains(componentClass),
                    resourceInstances.contains(component));
              }
            }));
    instances.addAll(resourceInstances);

    // Bind instances.
    for (Object component : instances) {
      ContractProvider model = componentBag.getModel(component.getClass());
      if (resourceInstances.contains(component)) {
        if (model != null
            && !Providers.checkProviderRuntime(
                component.getClass(),
                model,
                RuntimeType.SERVER,
                !registeredClasses.contains(component.getClass()),
                true)) {
          model = null;
        }
        resourceContext.unsafeBindResource(component, model, dc);
      } else {
        ProviderBinder.bindProvider(component, model, dc);
      }
    }

    dc.commit();
  }
Example #29
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();
  }
  /** Assumes the configuration field is initialized with a valid ResourceConfig. */
  private void initialize() {
    LOGGER.info(LocalizationMessages.INIT_MSG(Version.getBuildId()));

    // Lock original ResourceConfig.
    if (application instanceof ResourceConfig) {
      ((ResourceConfig) application).lock();
    }

    // add WADL support
    runtimeConfig.register(WadlModelProcessorFeature.class);

    // Configure binders and features.
    runtimeConfig.configureMetaProviders(locator);

    // Introspecting classes & instances
    final ResourceBag.Builder resourceBagBuilder = new ResourceBag.Builder();
    for (Class<?> c : runtimeConfig.getClasses()) {
      try {
        Resource resource = Resource.from(c);
        if (resource != null) {
          resourceBagBuilder.registerResource(c, resource);
        }
      } catch (IllegalArgumentException ex) {
        LOGGER.warning(ex.getMessage());
      }
    }

    for (Object o : runtimeConfig.getSingletons()) {
      try {
        Resource resource = Resource.from(o.getClass());
        if (resource != null) {
          resourceBagBuilder.registerResource(o, resource);
        }
      } catch (IllegalArgumentException ex) {
        LOGGER.warning(ex.getMessage());
      }
    }

    // Adding programmatic resource models
    for (Resource programmaticResource : runtimeConfig.getResources()) {
      resourceBagBuilder.registerProgrammaticResource(programmaticResource);
    }

    final ResourceBag resourceBag = resourceBagBuilder.build();

    runtimeConfig.lock();

    // Registering Injection Bindings
    final Set<ComponentProvider> componentProviders = new HashSet<ComponentProvider>();

    for (ComponentProvider provider : ServiceFinder.find(ComponentProvider.class)) {
      provider.initialize(locator);
      componentProviders.add(provider);
    }

    final ComponentBag componentBag = runtimeConfig.getComponentBag();
    bindProvidersAndResources(
        componentProviders, componentBag, resourceBag.classes, resourceBag.instances);
    for (ComponentProvider componentProvider : componentProviders) {
      componentProvider.done();
    }

    // scan for NameBinding annotations attached to the application class
    Collection<Class<? extends Annotation>> applicationNameBindings =
        ReflectionHelper.getAnnotationTypes(application.getClass(), NameBinding.class);

    // find all filters, interceptors and dynamic features
    final Iterable<RankedProvider<ContainerResponseFilter>> responseFilters =
        Providers.getAllRankedProviders(locator, ContainerResponseFilter.class);
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<ContainerResponseFilter>>
        nameBoundResponseFilters =
            filterNameBound(responseFilters, null, componentBag, applicationNameBindings);

    final Iterable<RankedProvider<ContainerRequestFilter>> requestFilters =
        Providers.getAllRankedProviders(locator, ContainerRequestFilter.class);
    final List<RankedProvider<ContainerRequestFilter>> preMatchFilters = Lists.newArrayList();
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<ContainerRequestFilter>>
        nameBoundRequestFilters =
            filterNameBound(requestFilters, preMatchFilters, componentBag, applicationNameBindings);

    final Iterable<RankedProvider<ReaderInterceptor>> readerInterceptors =
        Providers.getAllRankedProviders(locator, ReaderInterceptor.class);
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<ReaderInterceptor>>
        nameBoundReaderInterceptors =
            filterNameBound(readerInterceptors, null, componentBag, applicationNameBindings);

    final Iterable<RankedProvider<WriterInterceptor>> writerInterceptors =
        Providers.getAllRankedProviders(locator, WriterInterceptor.class);
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<WriterInterceptor>>
        nameBoundWriterInterceptors =
            filterNameBound(writerInterceptors, null, componentBag, applicationNameBindings);
    final Iterable<DynamicFeature> dynamicFeatures =
        Providers.getAllProviders(locator, DynamicFeature.class);

    ResourceModel resourceModel =
        new ResourceModel.Builder(resourceBag.getRootResources(), false).build();

    resourceModel = processResourceModel(resourceModel);
    // validate the models
    validate(resourceModel);

    bindEnhancingResourceClasses(resourceModel, resourceBag, componentProviders);

    final RuntimeModelBuilder runtimeModelBuilder = locator.getService(RuntimeModelBuilder.class);
    runtimeModelBuilder.setGlobalInterceptors(readerInterceptors, writerInterceptors);
    runtimeModelBuilder.setBoundProviders(
        nameBoundRequestFilters,
        nameBoundResponseFilters,
        nameBoundReaderInterceptors,
        nameBoundWriterInterceptors,
        dynamicFeatures);

    // assembly request processing chain
    /**
     * Root hierarchical request matching acceptor. Invoked in a single linear stage as part of the
     * main linear accepting chain.
     */
    final Router resourceRoutingRoot =
        runtimeModelBuilder.buildModel(resourceModel.getRuntimeResourceModel(), false);

    final ContainerFilteringStage preMatchRequestFilteringStage =
        locator
            .createAndInitialize(ContainerFilteringStage.Builder.class)
            .build(preMatchFilters, responseFilters);
    final RoutingStage routingStage =
        locator.createAndInitialize(RoutingStage.Builder.class).build(resourceRoutingRoot);
    final ContainerFilteringStage resourceFilteringStage =
        locator
            .createAndInitialize(ContainerFilteringStage.Builder.class)
            .build(requestFilters, null);
    final RoutedInflectorExtractorStage routedInflectorExtractorStage =
        locator.createAndInitialize(RoutedInflectorExtractorStage.class);
    /**
     * Root linear request acceptor. This is the main entry point for the whole request processing.
     */
    final Stage<ContainerRequest> rootStage =
        Stages.chain(locator.createAndInitialize(ReferencesInitializer.class))
            .to(locator.createAndInitialize(ContainerMessageBodyWorkersInitializer.class))
            .to(preMatchRequestFilteringStage)
            .to(routingStage)
            .to(resourceFilteringStage)
            .build(routedInflectorExtractorStage);

    // Inject instances.
    for (Object instance : componentBag.getInstances(ComponentBag.EXCLUDE_META_PROVIDERS)) {
      locator.inject(instance);
    }
    for (Object instance : resourceBag.instances) {
      locator.inject(instance);
    }

    // initiate resource model into JerseyResourceContext
    JerseyResourceContext jerseyResourceContext = locator.getService(JerseyResourceContext.class);
    jerseyResourceContext.setResourceModel(resourceModel);

    this.runtime = locator.createAndInitialize(ServerRuntime.Builder.class).build(rootStage);

    // inject self
    locator.inject(this);
  }