Esempio n. 1
0
  public void deploy(URL url, boolean master, ClassLoader cL, String remoteHost) {
    try {
      FileObject filetoScan = fsManager.resolveFile("jar:" + url.toString() + "!/");
      HashSet<Class<?>>[] classes = new HashSet[] {new HashSet()};

      VFSClassLoader jarCL;

      if (cL != null) {
        jarCL = new VFSClassLoader(new FileObject[] {filetoScan}, fsManager, cL);
      } else {
        jarCL =
            new VFSClassLoader(
                new FileObject[] {filetoScan},
                fsManager,
                Thread.currentThread().getContextClassLoader());
      }
      Class[] annot = new Class[] {DeployRMI.class};
      scanJar(filetoScan, classes, annot, jarCL);
      for (Class<?> rmiClass : classes[0]) {
        DeployRMI rmiAnnot = rmiClass.getAnnotation(DeployRMI.class);
        if (master) {
          rmiProxyHandler = new RMIProxyHandler(rmiAnnot.jndiBinding(), remoteObjects);
          rmiproxy =
              Proxy.newProxyInstance(
                  rmiClass.getClassLoader(), rmiClass.getInterfaces(), rmiProxyHandler);
          remoteobj =
              UnicastRemoteObject.exportObject(
                  (Remote) rmiproxy, Integer.parseInt(serverConfig.getRmiregistryport()));
          rmiproxyObjs.put(rmiAnnot.jndiBinding(), rmiproxy);
          rmiproxyHandler.put(rmiAnnot.jndiBinding(), rmiProxyHandler);
          remoteProxyObjs.put(rmiAnnot.jndiBinding(), remoteobj);
          ic.bind("java:/" + rmiAnnot.jndiBinding(), remoteobj);
          registry.bind(rmiAnnot.jndiBinding(), (Remote) remoteobj);
          cLMap.put(rmiAnnot.jndiBinding(), jarCL);
        } else {
          Remote remoteObj = (Remote) rmiClass.newInstance();
          remoteSlaveObjs.put(rmiAnnot.jndiBinding(), remoteObj);
          Object remoteobj =
              UnicastRemoteObject.exportObject(
                  (Remote) remoteObj, Integer.parseInt(serverConfig.getRmiregistryport()));
          ic.bind("java:/" + rmiAnnot.jndiBinding(), remoteobj);
          registry.bind(rmiAnnot.jndiBinding(), (Remote) remoteobj);
          if (remoteObjects.get(rmiAnnot.jndiBinding()) != null) {
            ConcurrentMap<String, Remote> remoteObjs = remoteObjects.get(rmiAnnot.jndiBinding());
            remoteObjs.put(remoteHost, (Remote) remoteobj);
          } else {
            ConcurrentHashMap<String, Remote> remoteObjs = new ConcurrentHashMap<String, Remote>();
            remoteObjs.put(remoteHost, (Remote) remoteobj);
            remoteObjects.put(rmiAnnot.jndiBinding(), remoteObjs);
          }
        }
      }
    } catch (Exception e) {
      log.error("unable to deploy the package " + url, e);
    }
  }
  public DigitalLibraryServer() {
    try {
      Properties properties = new Properties();
      properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
      properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
      properties.put(Context.PROVIDER_URL, "localhost");

      InitialContext jndi = new InitialContext(properties);
      ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory");
      connection = conFactory.createConnection();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      try {
        counterTopic = (Topic) jndi.lookup("counterTopic");
      } catch (NamingException NE1) {
        System.out.println("NamingException: " + NE1 + " : Continuing anyway...");
      }

      if (null == counterTopic) {
        counterTopic = session.createTopic("counterTopic");
        jndi.bind("counterTopic", counterTopic);
      }

      consumer = session.createConsumer(counterTopic);
      consumer.setMessageListener(this);
      System.out.println("Server started waiting for client requests");
      connection.start();
    } catch (NamingException NE) {
      System.out.println("Naming Exception: " + NE);
    } catch (JMSException JMSE) {
      System.out.println("JMS Exception: " + JMSE);
      JMSE.printStackTrace();
    }
  }
  /** Add the objects passed to the constructor to the JNDI Context addresses specified */
  public void setup() {

    try {
      InitialContext ic = new InitialContext();
      for (Iterator i = this.objectsToCreate.keySet().iterator(); i.hasNext(); ) {
        String name = (String) i.next();
        try {
          Name fullName = new CompositeName(name);
          Context currentContext = ic;
          while (fullName.size() > 1) {
            // Make contexts that are not already present
            try {
              currentContext = currentContext.createSubcontext(fullName.get(0));
            } catch (NamingException err) {
              currentContext = (Context) currentContext.lookup(fullName.get(0));
            }
            fullName = fullName.getSuffix(1);
          }
          ic.bind(name, this.objectsToCreate.get(name));
          Logger.log(Logger.FULL_DEBUG, JNDI_RESOURCES, "ContainerJNDIManager.BoundResource", name);
        } catch (NamingException err) {
          Logger.log(
              Logger.ERROR, JNDI_RESOURCES, "ContainerJNDIManager.ErrorBindingResource", name, err);
        }
      }
      Logger.log(
          Logger.DEBUG,
          JNDI_RESOURCES,
          "ContainerJNDIManager.SetupComplete",
          "" + this.objectsToCreate.size());
    } catch (NamingException err) {
      Logger.log(
          Logger.ERROR, JNDI_RESOURCES, "ContainerJNDIManager.ErrorGettingInitialContext", err);
    }
  }
Esempio n. 4
0
  @SuppressWarnings("unchecked")
  void jndiInJEE() throws NamingException {
    @SuppressWarnings("rawtypes")
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");

    InitialContext context = new InitialContext(env);

    DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/AccountDS");

    NamingEnumeration<Binding> bindings = context.listBindings("java:comp/env/jdbc");

    while (bindings.hasMore()) {
      Binding bd = (Binding) bindings.next();
      System.out.println("Name = " + bd.getName() + ", Object = " + bd.getObject());
    }

    context.bind("java:comp/env/jdbc/AccountDS", ds);

    // Directory search

    InitialDirContext dirContext = new InitialDirContext();

    SearchControls control = new SearchControls();

    ds = (DataSource) dirContext.search("java:comp/env/jdbc/AccountDS", "(ver=1.1)", control);

    // Or...

    BasicAttributes attrs = new BasicAttributes();
    attrs.put(new BasicAttribute("ver", "1.1"));

    ds = (DataSource) dirContext.search("java:comp/env/jdbc/AccountDS", attrs);
  }
 /**
  * Ensure that the given name is bound to a context.
  *
  * @param ctx
  * @param name
  * @throws NamingException
  */
 private void ensureCtx(InitialContext ctx, String name) throws NamingException {
   try {
     ctx.bind(name, new InitialContext());
   } catch (NameAlreadyBoundException e) {
     // this is ok
   }
 }
Esempio n. 6
0
 /**
  * Init the Derby Datasource in JNDI.
  *
  * @param context the naming context
  * @param name the dabase name in the context
  * @param datasourceName the datasource Name
  * @param user
  * @param password
  * @return <code>true</code> if initialized, <code>false</code> otherwise
  */
 public static boolean initDerbyDatasource(
     final InitialContext context,
     final String name,
     final String datasourceName,
     final String user,
     final String password) {
   boolean init = true;
   try {
     context.createSubcontext("java:");
     context.createSubcontext("java:/comp");
     context.createSubcontext("java:/comp/env");
     context.createSubcontext("java:/comp/env/jdbc");
     // Construct DataSource
     final EmbeddedConnectionPoolDataSource40 datasource =
         new EmbeddedConnectionPoolDataSource40();
     datasource.setDatabaseName(datasourceName);
     datasource.setUser("user");
     datasource.setPassword("password");
     LOGGER.info("Datasource created");
     validateDerbyConnection(datasource);
     context.bind("java:/comp/env/jdbc/" + name, datasource);
   } catch (NamingException e) {
     LOGGER.error("Naming Exception", e);
     init = false;
   }
   return init;
 }
Esempio n. 7
0
  protected ConfigurationBuilder getBuilder() throws Exception {
    QuickConfigurationBuilder builder = new QuickConfigurationBuilder();
    builder.disableAdminAgent();

    // create JNP connector
    jnpConnector = new JnpConnector();
    jnpConnector.setName("jnp");
    jnpConnector.setJndiInitialFactory(MuleInitialContextFactory.class.getName());
    jnpConnector.setSecurityPolicy("rmi.policy");

    // Required if connectoring to a Remote Jndi context
    // builder.getManager().registerAgent(new RmiRegistryAgent());

    // Create a local Jndi Context
    Hashtable env = new Hashtable();
    // env.put(Context.PROVIDER_URL, "rmi://localhost:1099");
    env.put(Context.INITIAL_CONTEXT_FACTORY, MuleInitialContextFactory.class.getName());
    InitialContext ic = new InitialContext(env);
    // Bind our servcie object
    ic.bind("TestService", new MatchingMethodsComponent());

    jnpConnector.setJndiContext(ic);
    builder.getManager().registerConnector(jnpConnector);
    return builder;
  }
Esempio n. 8
0
 // methods to do JNDI binding for remote access
 public void bind() {
   try {
     InitialContext ic = new InitialContext();
     ic.bind(JNDI_NAME, "Test");
   } catch (NamingException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 9
0
  @SuppressWarnings("unchecked")
  void referenceBinding() throws NamingException {
    @SuppressWarnings("rawtypes")
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
    InitialContext manningContext = new InitialContext(env);

    manningContext.bind(
        "Books", new Reference(File.class.getName(), "com.manning.FSObjectFactory", null));
  }
 @BeforeClass
 public static void setup() {
   try {
     InitialContext ctx = TestUtil.initialContext();
     TestUtil.ensureCtx(ctx, "java:/comp/env");
     TestUtil.ensureCtx(ctx, "java:/comp/env/jdbc");
     ds = createInMemoryDatasource();
     ctx.bind(DB_JNDI_LOC, ds);
     System.out.println("DataSource created and bound to JNDI: " + DB_JNDI_LOC);
   } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   }
 }
 @PostConstruct
 public void publishMetrics() {
   InitialContext ctx = null;
   try {
     ctx = new InitialContext();
     ctx.bind("java:global/Hawkular/Metrics", metricsService);
   } catch (Exception e) {
     throw new IllegalStateException("Could not register metrics in JNDI", e);
   } finally {
     if (ctx != null) {
       try {
         ctx.close();
       } catch (NamingException e) {
         // ignore
       }
     }
   }
 }
Esempio n. 12
0
  // @Test  TODO. commented out. Can't get test to work without an application server.
  public void testCreateSql2oFromJndi() throws Exception {
    System.setProperty(
        Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

    InitialContext ic = new InitialContext();

    ic.createSubcontext("java:");
    ic.createSubcontext("java:comp");
    ic.createSubcontext("java:comp/env");

    JDBCDataSource datasource = new JDBCDataSource();
    datasource.setUrl(url);
    datasource.setUser(user);
    datasource.setPassword(pass);

    ic.bind("java:comp/env/Sql2o", datasource);

    System.out.println("Datasource initialized.");

    Sql2o jndiSql2o = new Sql2o("Sql2o");

    assertTrue(jndiSql2o != null);
  }
Esempio n. 13
0
  /** Stuff to do before the server is started. */
  protected void preStart() throws Exception {
    if (ManagerTestUtils.getTestType() == TestType.jpa) {
      TestUtil.setProperty("apiman.hibernate.hbm2ddl.auto", "create-drop");
      TestUtil.setProperty(
          "apiman.hibernate.connection.datasource", "java:/comp/env/jdbc/ApiManagerDS");
      try {
        InitialContext ctx = new InitialContext();
        ensureCtx(ctx, "java:/comp/env");
        ensureCtx(ctx, "java:/comp/env/jdbc");
        String dbOutputPath = System.getProperty("apiman.test.h2-output-dir", null);
        if (dbOutputPath != null) {
          ds = createFileDatasource(new File(dbOutputPath));
        } else {
          ds = createInMemoryDatasource();
        }
        ctx.bind("java:/comp/env/jdbc/ApiManagerDS", ds);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    if (ManagerTestUtils.getTestType() == TestType.es && node == null) {
      System.out.println("Creating the ES node.");
      File esHome = new File("target/es");
      String esHomeSP = System.getProperty("apiman.test.es-home", null);
      if (esHomeSP != null) {
        esHome = new File(esHomeSP);
      }
      if (esHome.isDirectory()) {
        FileUtils.deleteDirectory(esHome);
      }
      Builder settings = NodeBuilder.nodeBuilder().settings();
      settings.put("path.home", esHome.getAbsolutePath());
      settings.put("http.port", "6500-6600");
      settings.put("transport.tcp.port", "6600-6700");
      settings.put("discovery.zen.ping.multicast.enabled", false);

      String clusterName = System.getProperty("apiman.test.es-cluster-name", ES_CLUSTER_NAME);

      boolean isPersistent =
          "true".equals(System.getProperty("apiman.test.es-persistence", "false"));
      if (!isPersistent) {
        System.out.println("Creating non-persistent ES");
        settings
            .put("index.store.type", "memory")
            .put("gateway.type", "none")
            .put("index.number_of_shards", 1)
            .put("index.number_of_replicas", 1);
        node =
            NodeBuilder.nodeBuilder()
                .client(false)
                .clusterName(clusterName)
                .data(true)
                .local(true)
                .settings(settings)
                .build();
      } else {
        System.out.println("Creating *persistent* ES here: " + esHome);
        node =
            NodeBuilder.nodeBuilder()
                .client(false)
                .clusterName(clusterName)
                .data(true)
                .local(false)
                .settings(settings)
                .build();
      }

      System.out.println("Starting the ES node.");
      node.start();
      System.out.println("ES node was successfully started.");

      // TODO parameterize this
      String connectionUrl = "http://localhost:6500";
      JestClientFactory factory = new JestClientFactory();
      factory.setHttpClientConfig(
          new HttpClientConfig.Builder(connectionUrl).multiThreaded(true).build());
      client = factory.getObject();
      ES_CLIENT = client;
    }
  }
Esempio n. 14
0
  @Before
  public void initJNDI() throws Exception {
    System.out.println("init [TestFlow]");
    this.setUp();
    // Create initial context
    System.setProperty(
        Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    final InitialContext ic = new InitialContext();

    try {
      ic.destroySubcontext("java:");
    } catch (final Exception e) {
    }

    ic.createSubcontext("java:");
    ic.createSubcontext("java:/comp");
    ic.createSubcontext("java:/comp/env");
    ic.createSubcontext("java:/comp/env/jdbc");
    ic.createSubcontext("java:/comp/env/cfg");
    ic.createSubcontext("java:/comp/env/cfg/Source");
    ic.createSubcontext("java:/comp/env/cfg/ConnectionParameters");

    final ConnectionParameters cp = new ConnectionParameters();
    ic.bind("java:/comp/env/cfg/ConnectionParameters/attributes", cp);
    ic.bind("java:/comp/env/cfg/ConnectionParameters/authentication", cp);

    ic.bind("java:/comp/env/cfg/Source/attributes", "FAKE");
    ic.bind("java:/comp/env/cfg/Source/authentication", "FAKE");
    ic.bind("java:/comp/env/cfg/bindQuery", "FAKE");
    ic.bind("java:/comp/env/cfg/restAuthPassword", "");
    ic.bind("java:/comp/env/cfg/restAuthUser", "flow");
    ic.bind("java:/comp/env/cfg/issuanceServiceURL", getBaseURI() + "issuance/");
    ic.bind("java:/comp/env/cfg/userServiceURL", getBaseURI() + "user/");
    ic.bind("java:/comp/env/cfg/verificationServiceURL", getBaseURI() + "verification/");
    ic.bind("java:/comp/env/cfg/verifierIdentity", "unknown");

    final SQLiteDataSource ds = new SQLiteDataSource();

    storageFile = File.createTempFile("test", "sql");

    ds.setUrl("jdbc:sqlite:" + storageFile.getPath());
    System.out.println(ds.getUrl());
    ic.rebind("java:/comp/env/jdbc/" + dbName, ds);
    ic.bind("java:/comp/env/cfg/useDbLocking", new Boolean(true));

    ic.close();

    RESTHelper.postRequest(issuanceServiceURL + "reset");
    RESTHelper.postRequest(verificationServiceURL + "reset");
    RESTHelper.postRequest(userServiceURL + "reset");

    // System.exit(1);
  }
  @SuppressWarnings("unchecked")
  @Override
  protected void setup(TestContainer container) throws Exception {
    AESEncrypter.generateKey();

    container.addBean(configService = Mockito.mock(APPConfigurationServiceBean.class));
    container.addBean(Mockito.mock(ServiceInstanceDAO.class));

    container.addBean(Mockito.mock(APPConcurrencyServiceBean.class));
    container.addBean(Mockito.mock(ProductProvisioningServiceFactoryBean.class));
    container.addBean(Mockito.mock(APPCommunicationServiceBean.class));

    serviceMock = Mockito.mock(Service.class);
    besDAO = Mockito.mock(BesDAO.class);
    subcriptionService = Mockito.mock(SubscriptionService.class);
    identityService = Mockito.mock(EnhancedIdentityService.class);
    Mockito.doReturn(Arrays.asList(new VOUserDetails()))
        .when(besDAO)
        .getBESTechnologyManagers(Matchers.any(ServiceInstance.class));

    Mockito.doReturn(identityService)
        .when(besDAO)
        .getBESWebService(Matchers.eq(IdentityService.class), Matchers.any(ServiceInstance.class));

    Mockito.doNothing()
        .when(besDAO)
        .setUserCredentialsInContext(
            Matchers.any(BindingProvider.class), Matchers.anyString(),
            Matchers.anyString(), Matchers.anyMap());

    Mockito.doReturn(subcriptionService)
        .when(besDAO)
        .getBESWebService(
            Matchers.eq(SubscriptionService.class), Matchers.any(ServiceInstance.class));

    Mockito.doNothing()
        .when(subcriptionService)
        .completeAsyncSubscription(
            Matchers.anyString(), Matchers.anyString(), Matchers.any(VOInstanceInfo.class));
    Mockito.doNothing()
        .when(subcriptionService)
        .abortAsyncSubscription(
            Matchers.anyString(), Matchers.anyString(), Matchers.anyListOf(VOLocalizedText.class));
    Mockito.doReturn(subcriptionService)
        .when(serviceMock)
        .getPort(Matchers.any(QName.class), Matchers.eq(SubscriptionService.class));

    Mockito.doReturn(serviceMock)
        .when(besDAO)
        .createWebService(Matchers.any(URL.class), Matchers.any(QName.class));

    Mockito.doReturn(identityService)
        .when(serviceMock)
        .getPort(Matchers.any(QName.class), Matchers.eq(IdentityService.class));

    container.addBean(besDAO);
    container.addBean(Mockito.mock(OperationDAO.class));

    container.addBean(Mockito.mock(ServiceInstanceDAO.class));
    container.addBean(Mockito.mock(OperationServiceBean.class));

    container.addBean(authService = Mockito.spy(new APPAuthenticationServiceBean()));
    container.addBean(Mockito.mock(OperationServiceBean.class));

    container.addBean(new APPlatformServiceBean());
    controller = Mockito.mock(APPlatformController.class);
    InitialContext context = new InitialContext();
    context.bind("bss/app/controller/ess.vmware", controller);
    container.addBean(controller);

    besDAO = container.get(BesDAO.class);

    platformService = container.get(APPlatformService.class);

    em = container.getPersistenceUnit("oscm-app");

    defaultAuth = new PasswordAuthentication("user", "password");
  }