/** @throws Exception */
 private void initialize() throws Exception {
   loadSecurityScenarios();
   STSConfigAdmin.configureService(
       configContext.getAxisConfiguration(), this.registryService.getConfigSystemRegistry());
   STSConfigAdmin.configureGenericSTS();
   configContext.getAxisConfiguration().addObservers(new STSObserver());
 }
  /** {@inheritDoc} */
  public SynapseConfiguration createSynapseConfiguration() {

    String synapseXMLLocation = serverConfigurationInformation.getSynapseXMLLocation();
    Properties properties = SynapsePropertiesLoader.loadSynapseProperties();
    if (serverConfigurationInformation.getResolveRoot() != null) {
      properties.put(
          SynapseConstants.RESOLVE_ROOT, serverConfigurationInformation.getResolveRoot());
    }

    if (serverConfigurationInformation.getSynapseHome() != null) {
      properties.put(
          SynapseConstants.SYNAPSE_HOME, serverConfigurationInformation.getSynapseHome());
    }

    if (synapseXMLLocation != null) {
      synapseConfiguration =
          SynapseConfigurationBuilder.getConfiguration(synapseXMLLocation, properties);
    } else {
      log.warn(
          "System property or init-parameter '"
              + SynapseConstants.SYNAPSE_XML
              + "' is not specified. Using default configuration..");
      synapseConfiguration = SynapseConfigurationBuilder.getDefaultConfiguration();
    }

    Enumeration keys = properties.keys();
    while (keys.hasMoreElements()) {
      String key = (String) keys.nextElement();
      synapseConfiguration.setProperty(key, properties.getProperty(key));
    }

    // Set the Axis2 ConfigurationContext to the SynapseConfiguration
    synapseConfiguration.setAxisConfiguration(configurationContext.getAxisConfiguration());
    MessageContextCreatorForAxis2.setSynConfig(synapseConfiguration);

    // set the Synapse configuration into the Axis2 configuration
    Parameter synapseConfigurationParameter =
        new Parameter(SynapseConstants.SYNAPSE_CONFIG, synapseConfiguration);
    try {
      configurationContext.getAxisConfiguration().addParameter(synapseConfigurationParameter);
    } catch (AxisFault e) {
      handleFatal(
          "Could not set parameters '"
              + SynapseConstants.SYNAPSE_CONFIG
              + "' to the Axis2 configuration : "
              + e.getMessage(),
          e);
    }

    addServerIPAndHostEntries();

    return synapseConfiguration;
  }
예제 #3
0
  public static ConfigurationContext createClientConfigurationContext() throws AxisFault {
    File file = getAddressingMARFile();
    TestCase.assertTrue(file.exists());

    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            "target/test-resources/integrationRepo",
            "target/test-resources/integrationRepo/conf/axis2.xml");
    AxisModule axisModule =
        DeploymentEngine.buildModule(file, configContext.getAxisConfiguration());
    configContext.getAxisConfiguration().addModule(axisModule);
    return configContext;
  }
  private void addDeployers(ConfigurationContext configurationContext) {
    AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();
    DeploymentEngine deploymentEngine = (DeploymentEngine) axisConfig.getConfigurator();
    String carbonRepoPath = configurationContext.getAxisConfiguration().getRepository().getFile();

    String mediatorsPath = carbonRepoPath + File.separator + "mediators";
    String extensionsPath = carbonRepoPath + File.separator + "extensions";
    ExtensionDeployer deployer = new ExtensionDeployer();
    deploymentEngine.addDeployer(deployer, mediatorsPath, "xar");
    deploymentEngine.addDeployer(deployer, extensionsPath, "xar");
    deploymentEngine.addDeployer(deployer, mediatorsPath, "jar");
    deploymentEngine.addDeployer(deployer, extensionsPath, "jar");
  }
  /**
   * Adds the synapse handlers to the inflow Dispatch phase and starts the listener manager if the
   * axis2 instance is created by the Synapse
   */
  public void start() {

    // add the Synapse handlers
    if (configurationContext != null) {
      List<Phase> inflowPhases = configurationContext.getAxisConfiguration().getInFlowPhases();
      for (Phase inPhase : inflowPhases) {
        // we are interested about the Dispatch phase in the inflow
        if (PhaseMetadata.PHASE_DISPATCH.equals(inPhase.getPhaseName())) {
          try {
            inPhase.addHandler(prepareSynapseDispatcher());
            inPhase.addHandler(prepareMustUnderstandHandler());
          } catch (PhaseException e) {
            handleFatal("Couldn't start Synapse, " + "Cannot add the required Synapse handlers", e);
          }
        }
      }
    } else {
      handleFatal("Couldn't start Synapse, ConfigurationContext not found");
    }

    // if the axis2 instance is created by us, then start the listener manager
    if (serverConfigurationInformation.isCreateNewInstance()) {
      if (listenerManager != null) {
        listenerManager.start();
      } else {
        handleFatal("Couldn't start Synapse, ListenerManager not found");
      }
      /* if JMX Adapter has been configured and started, output usage information rather
      at the end of the startup process to make it more obvious */
      if (jmxAdapter != null && jmxAdapter.isRunning()) {
        log.info(
            "Management using JMX available via: " + jmxAdapter.getJmxInformation().getJmxUrl());
      }
    }
  }
예제 #6
0
  /**
   * Search the service artifacts stored in the registry and find the set of services that satisfy
   * the conditions stated in the given WS-D probe. If the probe does not impose any restrictions on
   * the result set, all the services in the registry will be returned.
   *
   * @param probe a WS-D probe describing the search criteria
   * @return an array of TargetService instances matching the probe or null
   * @throws Exception if an error occurs while accessing the registry
   */
  public static TargetService[] findServices(Probe probe) throws Exception {
    ServiceManager serviceManager = new ServiceManager(getRegistry());
    DiscoveryServiceFilter filter = new DiscoveryServiceFilter(probe);

    // Check whether the inactive services should be skipped when searching
    AxisConfiguration axisConfig;
    String tenantDomain =
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
    ConfigurationContext mainCfgCtx = ConfigHolder.getInstance().getServerConfigurationContext();
    if (tenantDomain != MultitenantConstants.SUPER_TENANT_DOMAIN_NAME) {
      axisConfig = TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, mainCfgCtx);
    } else {
      axisConfig = mainCfgCtx.getAxisConfiguration();
    }

    Parameter parameter = axisConfig.getParameter(DiscoveryConstants.SKIP_INACTIVE_SERVICES);
    filter.setSkipInactiveServices(parameter == null || "true".equals(parameter.getValue()));

    Service[] services = serviceManager.findServices(filter);
    if (services != null && services.length > 0) {
      TargetService[] targetServices = new TargetService[services.length];
      for (int i = 0; i < services.length; i++) {
        targetServices[i] = getTargetService(services[i]);
      }
      return targetServices;
    }
    return null;
  }
예제 #7
0
 public void testParameterEdit() throws Exception {
   ConfigurationContext configCtx = ConfigurationContextFactory.createEmptyConfigurationContext();
   AxisConfiguration axisConfig = configCtx.getAxisConfiguration();
   Parameter parameter = new Parameter();
   parameter.setValue("true");
   parameter.setName("enableMTOM");
   axisConfig.addParameter(parameter);
   parameter.setValue("true");
   AxisServiceGroup serviceGroup = new AxisServiceGroupImpl();
   serviceGroup.setName("testServiceGroup");
   AxisService service = new AxisService();
   service.setName("service");
   serviceGroup.addService(service);
   axisConfig.addServiceGroup(serviceGroup);
   parameter = serviceGroup.getParameter("enableMTOM");
   parameter.setValue("true");
   Parameter para2 = serviceGroup.getParameter("enableMTOM");
   assertEquals(para2.getValue(), "true");
   Parameter test = new Parameter();
   test.setName("test");
   test.setValue("test");
   serviceGroup.addParameter(test);
   Parameter para = serviceGroup.getParameter("test");
   assertNotNull(para);
   assertEquals(para.getValue(), "test");
   para.setValue("newValue");
   para = serviceGroup.getParameter("test");
   assertNotNull(para);
   assertEquals(para.getValue(), "newValue");
 }
예제 #8
0
  public void init(SynapseEnvironment synapseEnvironment) {
    ConfigurationContext cc =
        ((Axis2SynapseEnvironment) synapseEnvironment).getAxis2ConfigurationContext();
    if (!initialized) {
      // The check for clustering environment
      ClusteringAgent clusteringAgent = cc.getAxisConfiguration().getClusteringAgent();
      if (clusteringAgent != null && clusteringAgent.getStateManager() != null) {
        isClusteringEnabled = Boolean.TRUE;
      } else {
        isClusteringEnabled = Boolean.FALSE;
      }

      context =
          new EndpointContext(getName(), getDefinition(), isClusteringEnabled, cc, metricsMBean);
    }
    initialized = true;

    if (children != null) {
      for (Endpoint e : children) {
        e.init(synapseEnvironment);
      }
    }

    contentAware =
        definition != null
            && ((definition.getFormat() != null
                    && !definition.getFormat().equals(SynapseConstants.FORMAT_REST))
                || definition.isSecurityOn()
                || definition.isReliableMessagingOn()
                || definition.isAddressingOn()
                || definition.isUseMTOM()
                || definition.isUseSwa());
  }
  public void terminatingConfigurationContext(ConfigurationContext configurationContext) {
    String tenantDomain =
        SuperTenantCarbonContext.getCurrentContext(configurationContext).getTenantDomain();

    log.info("Shutting down the persistence manager for the tenant: " + tenantDomain);

    Parameter p =
        configurationContext
            .getAxisConfiguration()
            .getParameter(ServiceBusConstants.PERSISTENCE_MANAGER);
    if (p != null && p.getValue() instanceof MediationPersistenceManager) {
      ((MediationPersistenceManager) p.getValue()).destroy();
    }

    // unregister the service so that components get to know about the tenant termination
    int tenantId = SuperTenantCarbonContext.getCurrentContext(configurationContext).getTenantId();
    ServiceRegistration tenantRegistration =
        ConfigurationHolder.getInstance().getSynapseRegistration(tenantId);

    if (tenantRegistration != null) {
      ConfigurationHolder.getInstance()
          .getBundleContext()
          .ungetService(tenantRegistration.getReference());
    }
  }
예제 #10
0
 /**
  * Set the transports for the tenants
  *
  * @param mainConfigCtx The main config context
  * @throws AxisFault If an error occurs while initializing tenant transports
  */
 @SuppressWarnings("unchecked")
 public static void initializeTenantTransports(ConfigurationContext mainConfigCtx)
     throws AxisFault {
   AxisConfiguration mainAxisConfig = mainConfigCtx.getAxisConfiguration();
   Map<String, ConfigurationContext> tenantConfigContexts =
       getTenantConfigurationContexts(mainConfigCtx);
   if (tenantConfigContexts != null) {
     for (Map.Entry<String, ConfigurationContext> entry : tenantConfigContexts.entrySet()) {
       String tenantDomain = entry.getKey();
       ConfigurationContext tenantConfigCtx = entry.getValue();
       AxisConfiguration tenantAxisConfig = tenantConfigCtx.getAxisConfiguration();
       // Add the transports that are made available in the main axis2.xml file
       setTenantTransports(mainAxisConfig, tenantDomain, tenantAxisConfig);
     }
   }
 }
예제 #11
0
 private void notifyClusterDSChange(String dsName) throws DataSourceException {
   if (log.isDebugEnabled()) {
     log.debug("Notifying cluster DS change: " + dsName);
   }
   ConfigurationContextService configCtxService =
       DataSourceServiceComponent.getConfigContextService();
   if (configCtxService == null) {
     throw new DataSourceException(
         "ConfigurationContextService not available " + "for notifying the cluster");
   }
   ConfigurationContext configCtx = configCtxService.getServerConfigContext();
   ClusteringAgent agent = configCtx.getAxisConfiguration().getClusteringAgent();
   if (log.isDebugEnabled()) {
     log.debug("Clustering Agent: " + agent);
   }
   if (agent != null) {
     DataSourceStatMessage msg = new DataSourceStatMessage();
     msg.setTenantId(this.getTenantId());
     msg.setDsName(dsName);
     try {
       agent.sendMessage(msg, true);
     } catch (ClusteringFault e) {
       throw new DataSourceException("Error in sending out cluster message: " + e.getMessage(), e);
     }
   }
 }
예제 #12
0
 public static AxisConfiguration getTenantAxisConfiguration(
     String tenant, ConfigurationContext mainConfigCtx) {
   ConfigurationContext tenantConfigCtx = getTenantConfigurationContext(tenant, mainConfigCtx);
   if (tenantConfigCtx != null) {
     return tenantConfigCtx.getAxisConfiguration();
   }
   return null;
 }
예제 #13
0
 private String inferContentType() {
   Parameter param =
       cfgCtx.getAxisConfiguration().getParameter(NhttpConstants.REQUEST_CONTENT_TYPE);
   if (param != null) {
     return param.getValue().toString();
   }
   return null;
 }
예제 #14
0
  public static ServiceContext createAdressedEnabledClientSide(AxisService service)
      throws AxisFault {
    File file = getAddressingMARFile();
    TestCase.assertTrue(file.exists());
    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            "target/test-resources/integrationRepo", null);
    AxisModule axisModule =
        DeploymentEngine.buildModule(file, configContext.getAxisConfiguration());

    AxisConfiguration axisConfiguration = configContext.getAxisConfiguration();
    axisConfiguration.addModule(axisModule);
    axisConfiguration.addService(service);
    ServiceGroupContext serviceGroupContext =
        configContext.createServiceGroupContext((AxisServiceGroup) service.getParent());
    return serviceGroupContext.getServiceContext(service);
  }
 /**
  * Register a new ThreadContextMigrator.
  *
  * @param configurationContext
  * @param threadContextMigratorListID The name of the parameter in the AxisConfiguration that
  *     contains the list of migrators.
  * @param migrator
  */
 public static void addThreadContextMigrator(
     ConfigurationContext configurationContext,
     String threadContextMigratorListID,
     ThreadContextMigrator migrator)
     throws AxisFault {
   AxisConfiguration axisConfiguration = configurationContext.getAxisConfiguration();
   addThreadContextMigrator(axisConfiguration, threadContextMigratorListID, migrator);
 }
 /*
 Deploying CSV configuration
  */
 public void processDeployStreamConfig(DeploymentFileData deploymentFileData)
     throws DeploymentException {
   CSVFileInfo csvFileInfo =
       DeploymentHelper.getCSVFileInfo(
           deploymentFileData.getFile(), configurationContext.getAxisConfiguration());
   CarbonEventSimulator eventSimulator = EventSimulatorValueHolder.getEventSimulator();
   eventSimulator.addCSVFileInfo(csvFileInfo);
 }
  /**
   * Removes all Synapse proxy services from the Axis2 configuration.
   *
   * @throws AxisFault if an error occurs undeploying proxy services
   */
  private void undeployProxyServices() throws AxisFault {

    log.info("Undeploying Proxy services...");

    for (ProxyService proxy : synapseConfiguration.getProxyServices()) {
      configurationContext.getAxisConfiguration().removeService(proxy.getName());
    }
  }
  protected void setConfigurationContextService(ConfigurationContextService ccService) {
    ConfigurationContext serverCtx = ccService.getServerConfigContext();
    AxisConfiguration serverConfig = serverCtx.getAxisConfiguration();
    LocalTransportReceiver.CONFIG_CONTEXT = new ConfigurationContext(serverConfig);
    LocalTransportReceiver.CONFIG_CONTEXT.setServicePath("services");
    LocalTransportReceiver.CONFIG_CONTEXT.setContextRoot("local:/");

    Util.setConfigurationContextService(ccService);
  }
  private void initPersistence(
      String configName,
      ConfigurationContext configurationContext,
      ServerContextInformation contextInfo)
      throws RegistryException, AxisFault {
    // Initialize the mediation persistence manager if required
    ServerConfiguration serverConf = ServerConfiguration.getInstance();
    String persistence = serverConf.getFirstProperty(ServiceBusConstants.PERSISTENCE);
    org.wso2.carbon.registry.core.Registry configRegistry =
        (org.wso2.carbon.registry.core.Registry)
            SuperTenantCarbonContext.getCurrentContext(configurationContext)
                .getRegistry(RegistryType.SYSTEM_CONFIGURATION);

    // Check whether persistence is disabled
    if (!ServiceBusConstants.DISABLED.equals(persistence)) {

      // Check registry persistence is disabled or not
      String regPersistence = serverConf.getFirstProperty(ServiceBusConstants.REGISTRY_PERSISTENCE);
      UserRegistry registry =
          ServiceBusConstants.DISABLED.equals(regPersistence)
              ? null
              : (UserRegistry) configRegistry;

      // Check the worker interval is set or not
      String interval = serverConf.getFirstProperty(ServiceBusConstants.WORKER_INTERVAL);
      long intervalInMillis = 5000L;
      if (interval != null && !"".equals(interval)) {
        try {
          intervalInMillis = Long.parseLong(interval);
        } catch (NumberFormatException e) {
          log.error(
              "Invalid value "
                  + interval
                  + " specified for the mediation "
                  + "persistence worker interval, Using defaults",
              e);
        }
      }

      MediationPersistenceManager pm =
          new MediationPersistenceManager(
              registry,
              contextInfo.getServerConfigurationInformation().getSynapseXMLLocation(),
              contextInfo.getSynapseConfiguration(),
              intervalInMillis,
              configName);

      configurationContext
          .getAxisConfiguration()
          .addParameter(new Parameter(ServiceBusConstants.PERSISTENCE_MANAGER, pm));
    } else {
      log.info("Persistence for mediation configuration is disabled");
    }
  }
 /** Deploys the mediators in the mediator extensions folder. */
 private void deployMediatorExtensions() {
   log.info("Loading mediator extensions...");
   AxisConfigurator configurator = configurationContext.getAxisConfiguration().getConfigurator();
   if (configurator instanceof DeploymentEngine) {
     ((DeploymentEngine) configurator).getRepoListener().checkServices();
   } else {
     log.warn(
         "Unable to access the repository listener. Custom extensions will "
             + "not get loaded now!");
   }
 }
  /** Adds all Synapse proxy services to the Axis2 configuration. */
  private void deployProxyServices() {

    boolean failSafeProxyEnabled =
        SynapseConfigUtils.isFailSafeEnabled(SynapseConstants.FAIL_SAFE_MODE_PROXY_SERVICES);

    log.info("Deploying Proxy services...");
    String thisServerName = serverConfigurationInformation.getServerName();
    if (thisServerName == null || "".equals(thisServerName)) {
      thisServerName = serverConfigurationInformation.getHostName();
      if (thisServerName == null || "".equals(thisServerName)) {
        thisServerName = "localhost";
      }
    }

    for (ProxyService proxy : synapseConfiguration.getProxyServices()) {

      // start proxy service if either, pinned server name list is empty
      // or pinned server list has this server name
      List pinnedServers = proxy.getPinnedServers();
      if (pinnedServers != null && !pinnedServers.isEmpty()) {
        if (!pinnedServers.contains(thisServerName)) {
          log.info(
              "Server name not in pinned servers list."
                  + " Not deploying Proxy service : "
                  + proxy.getName());
          continue;
        }
      }

      try {
        AxisService proxyService =
            proxy.buildAxisService(
                synapseConfiguration, configurationContext.getAxisConfiguration());
        if (proxyService != null) {
          log.info("Deployed Proxy service : " + proxy.getName());
          if (!proxy.isStartOnLoad()) {
            proxy.stop(synapseConfiguration);
          }
        } else {
          log.warn("The proxy service " + proxy.getName() + " will NOT be available");
        }
      } catch (SynapseException e) {
        if (failSafeProxyEnabled) {
          log.warn(
              "The proxy service "
                  + proxy.getName()
                  + " cannot be deployed - "
                  + "Continue in Proxy Service fail-safe mode.");
        } else {
          handleException("The proxy service " + proxy.getName() + " : Deployment Error");
        }
      }
    }
  }
  /**
   * The mediation library deployer will handling the process of deploying the libararyArtifacts,
   * this is required since the library specific artifacts has to be initialized priorly for the
   * cases like connectors
   */
  private void deployMediationLibraryArtifacts() {
    if (configurationContext == null || synapseConfiguration == null) {
      return;
    }
    DeploymentEngine deploymentEngine =
        (DeploymentEngine) configurationContext.getAxisConfiguration().getConfigurator();
    String carbonRepoPath = configurationContext.getAxisConfiguration().getRepository().getPath();
    SynapseArtifactDeploymentStore deploymentStore =
        synapseConfiguration.getArtifactDeploymentStore();

    String synapseImportDir =
        synapseConfiguration.getPathToConfigFile()
            + File.separator
            + MultiXMLConfigurationBuilder.SYNAPSE_IMPORTS_DIR;

    /*Registering Import Deployer is not required here.*/
    // deploymentEngine.addDeployer(new ImportDeployer(), synapseImportDir, "xml");

    String libsPath = carbonRepoPath + File.separator + "synapse-libs";
    deploymentEngine.addDeployer(new LibraryArtifactDeployer(), libsPath, "zip");
  }
  public void uploadHumanTask(UploadedFileItem[] fileItems) throws AxisFault {

    // First lets filter for jar resources
    ConfigurationContext configurationContext = getConfigContext();
    String repo = configurationContext.getAxisConfiguration().getRepository().getPath();

    if (CarbonUtils.isURL(repo)) {
      throw new AxisFault("URL Repositories are not supported: " + repo);
    }

    // Writting the artifacts to the proper location
    String humantaskDirectory = getHumanTaskLocation(repo);

    String humantaskTemp =
        CarbonUtils.getCarbonHome()
            + File.separator
            + HumanTaskConstants.HUMANTASK_PACKAGE_TEMP_DIRECTORY;
    File humantaskTempDir = new File(humantaskTemp);
    if (!humantaskTempDir.exists() && !humantaskTempDir.mkdirs()) {
      throw new AxisFault("Fail to create the directory: " + humantaskTempDir.getAbsolutePath());
    }

    File humantaskDir = new File(humantaskDirectory);
    if (!humantaskDir.exists() && !humantaskDir.mkdirs()) {
      throw new AxisFault("Fail to create the directory: " + humantaskDir.getAbsolutePath());
    }

    for (UploadedFileItem uploadedFile : fileItems) {
      String fileName = uploadedFile.getFileName();

      if (fileName == null || fileName.equals("")) {
        throw new AxisFault("Invalid file name. File name is not available");
      }

      if (HumanTaskConstants.HUMANTASK_PACKAGE_EXTENSION.equals(uploadedFile.getFileType())) {
        try {
          writeResource(uploadedFile.getDataHandler(), humantaskTemp, fileName, humantaskDir);
        } catch (IOException e) {
          throw new AxisFault("IOError: Writing resource failed.", e);
        }
      } else {
        throw new AxisFault(
            "Invalid file type : "
                + uploadedFile.getFileType()
                + " ."
                + HumanTaskConstants.HUMANTASK_PACKAGE_EXTENSION
                + " file type is expected");
      }
    }
  }
 public void replicate(String key, ConcurrentAccessController concurrentAccessController) {
   try {
     ClusteringAgent clusteringAgent = configContext.getAxisConfiguration().getClusteringAgent();
     if (clusteringAgent != null) {
       if (log.isDebugEnabled()) {
         log.debug("Replicating ConcurrentAccessController " + key + " in a ClusterMessage.");
       }
       clusteringAgent.sendMessage(
           new ConcurrentAccessUpdateClusterMessage(key, concurrentAccessController), true);
     }
   } catch (ClusteringFault e) {
     if (log.isErrorEnabled()) {
       log.error("Could not replicate throttle data", e);
     }
   }
 }
예제 #25
0
  public ConfigurationContext getClientCfgCtx() throws Exception {
    ConfigurationContext cfgCtx =
        ConfigurationContextFactory.createConfigurationContext(new CustomAxisConfigurator());
    AxisConfiguration axisCfg = cfgCtx.getAxisConfiguration();
    axisCfg.engageModule("addressing");

    TransportInDescription trpInDesc = new TransportInDescription("udp");
    trpInDesc.setReceiver(new UDPListener());
    axisCfg.addTransportIn(trpInDesc);

    TransportOutDescription trpOutDesc = new TransportOutDescription("udp");
    trpOutDesc.setSender(new UDPSender());
    axisCfg.addTransportOut(trpOutDesc);

    return cfgCtx;
  }
예제 #26
0
 /**
  * Terminate the provided Tenant ConfigurationContext
  *
  * @param tenantCfgCtx The tenant ConfigurationContext which needs to be terminated
  */
 public static void terminateTenantConfigContext(ConfigurationContext tenantCfgCtx) {
   ConfigurationContext mainServerConfigContext =
       CarbonCoreDataHolder.getInstance().getMainServerConfigContext();
   Map<String, ConfigurationContext> tenantConfigContexts =
       getTenantConfigurationContexts(mainServerConfigContext);
   String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
   log.info("Starting to clean tenant : " + tenantDomain);
   tenantCfgCtx.getAxisConfiguration().getConfigurator().cleanup();
   try {
     doPreConfigContextTermination(tenantCfgCtx);
     tenantCfgCtx.terminate();
     doPostConfigContextTermination(tenantCfgCtx);
     tenantConfigContexts.remove(tenantDomain);
     log.info("Cleaned up tenant " + tenantDomain);
   } catch (AxisFault e) {
     log.error("Cannot cleanup ConfigurationContext of tenant " + tenantDomain, e);
   }
 }
예제 #27
0
  public boolean doThrottle(
      HttpServletRequest request,
      APIKeyValidationInfoDTO apiKeyValidationInfoDTO,
      String accessToken) {
    ThrottleManager throttleManager = new ThrottleManager(id, key);
    ConfigurationContext cc = DataHolder.getServerConfigContext();
    ClusteringAgent clusteringAgent = cc.getAxisConfiguration().getClusteringAgent();
    if (clusteringAgent != null && clusteringAgent.getStateManager() != null) {
      isClusteringEnable = true;
    }
    // check the availability of the ConcurrentAccessController
    // if this is a clustered environment
    if (isClusteringEnable) {
      concurrentAccessController = (ConcurrentAccessController) cc.getProperty(key);
    }
    initThrottle(cc);

    // perform concurrency throttling
    boolean canAccess = throttleManager.doThrottleByConcurrency(false, concurrentAccessController);

    if (canAccess) {
      String remoteIP = request.getRemoteAddr();
      canAccess =
          throttleManager.throttleByAccessRate(
                  remoteIP, remoteIP, cc, isClusteringEnable, concurrentAccessController, throttle)
              && throttleManager.doRoleBasedAccessThrottling(
                  isClusteringEnable, cc, apiKeyValidationInfoDTO, accessToken, throttle);
    }
    // All the replication functionality of the access rate based throttling handled by itself
    // Just replicate the current state of ConcurrentAccessController
    if (isClusteringEnable && concurrentAccessController != null) {
      if (cc != null) {
        try {
          Replicator.replicate(cc);
        } catch (ClusteringFault clusteringFault) {
          handleException("Error during the replicating  states ", clusteringFault);
        }
      }
    }
    if (!canAccess) {
      return false;
    }
    return true;
  }
  /**
   * Adds Synapse Service to Axis2 configuration which enables the main message mediation.
   *
   * @throws AxisFault if an error occurs during Axis2 service initialization
   */
  private void deploySynapseService() throws AxisFault {

    log.info("Deploying the Synapse service...");
    // Dynamically initialize the Synapse Service and deploy it into Axis2
    AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
    AxisService synapseService = new AxisService(SynapseConstants.SYNAPSE_SERVICE_NAME);
    AxisOperation mediateOperation =
        new InOutAxisOperation(SynapseConstants.SYNAPSE_OPERATION_NAME);
    mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
    synapseService.addOperation(mediateOperation);
    List<String> transports = new ArrayList<String>();
    transports.add(Constants.TRANSPORT_HTTP);
    transports.add(Constants.TRANSPORT_HTTPS);
    synapseService.setExposedTransports(transports);
    AxisServiceGroup synapseServiceGroup = new AxisServiceGroup(axisCfg);
    synapseServiceGroup.setServiceGroupName(SynapseConstants.SYNAPSE_SERVICE_NAME);
    synapseServiceGroup.addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    synapseServiceGroup.addService(synapseService);
    axisCfg.addServiceGroup(synapseServiceGroup);
  }
 protected void activate(ComponentContext ctxt) {
   try {
     BundleContext bundleContext = ctxt.getBundleContext();
     // registering ServiceUnloader as an OSGi service
     ServiceUnloader serviceUnloader = new ServiceUnloader();
     bundleContext.registerService(ArtifactUnloader.class.getName(), serviceUnloader, null);
     if (serviceAdmin != null) {
       serviceAdmin.setConfigurationContext(configCtx);
     }
     try {
       // Registering ServiceAdmin as an OSGi service
       ServiceAdmin serviceAdmin = new ServiceAdmin(configCtx.getAxisConfiguration());
       bundleContext.registerService(ServiceAdmin.class.getName(), serviceAdmin, null);
     } catch (Exception exception) {
       String msg = "An error occured while initializing ServiceAdmin as an OSGi Service";
       log.error(msg, exception);
     }
   } catch (Throwable e) {
     log.error("Failed to activate the ServiceManagementServiceComponent", e);
   }
 }
  @Override
  public void init(ConfigurationContext cfgCtx, TransportInDescription transportIn)
      throws AxisFault {

    super.init(cfgCtx, transportIn);
    DatagramDispatcherCallback callback =
        new DatagramDispatcherCallback() {
          public void receive(DatagramEndpoint endpoint, byte[] data, int length) {
            workerPool.execute(new ProcessPacketTask(endpoint, data, length));
          }
        };
    try {
      dispatcher = createDispatcher(callback);
    } catch (IOException ex) {
      throw new AxisFault("Unable to create selector", ex);
    }
    try {
      defaultIp = org.apache.axis2.util.Utils.getIpAddress(cfgCtx.getAxisConfiguration());
    } catch (SocketException ex) {
      throw new AxisFault("Unable to determine the host's IP address", ex);
    }
  }