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());
    }
  }
Ejemplo n.º 2
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;
  }
  private void addServerIPAndHostEntries() {
    String hostName = serverConfigurationInformation.getHostName();
    String ipAddress = serverConfigurationInformation.getIpAddress();
    if (hostName != null && !"".equals(hostName)) {
      Entry entry = new Entry(SynapseConstants.SERVER_HOST);
      entry.setValue(hostName);
      synapseConfiguration.addEntry(SynapseConstants.SERVER_HOST, entry);
    }

    if (ipAddress != null && !"".equals(ipAddress)) {
      Entry entry = new Entry(SynapseConstants.SERVER_IP);
      entry.setValue(ipAddress);
      if (synapseConfiguration.getAxisConfiguration().getTransportsIn() != null) {
        Map<String, TransportInDescription> transportInConfigMap =
            synapseConfiguration.getAxisConfiguration().getTransportsIn();
        if (transportInConfigMap != null) {
          TransportInDescription transportInDescription = transportInConfigMap.get("http");
          if (transportInDescription != null) {
            Parameter bindAddressParam = transportInDescription.getParameter("bind-address");
            if (bindAddressParam != null) {
              entry.setValue(bindAddressParam.getValue());
            }
          }
        }
      }
      synapseConfiguration.addEntry(SynapseConstants.SERVER_IP, entry);
    }
  }
Ejemplo n.º 4
0
 private String inferContentType() {
   Parameter param =
       cfgCtx.getAxisConfiguration().getParameter(NhttpConstants.REQUEST_CONTENT_TYPE);
   if (param != null) {
     return param.getValue().toString();
   }
   return null;
 }
Ejemplo n.º 5
0
  /**
   * Return the connection factory name for this service. If this service refers to an invalid
   * factory or defaults to a non-existent default factory, this returns null
   *
   * @param service the AxisService
   * @return the JMSConnectionFactory to be used, or null if reference is invalid
   */
  public JMSConnectionFactory getConnectionFactory(AxisService service) {

    Parameter conFacParam = service.getParameter(JMSConstants.PARAM_JMS_CONFAC);
    // validate connection factory name (specified or default)
    if (conFacParam != null) {
      return connFacManager.getJMSConnectionFactory((String) conFacParam.getValue());
    } else {
      return connFacManager.getJMSConnectionFactory(JMSConstants.DEFAULT_CONFAC_NAME);
    }
  }
  private static Map<String, String> getServiceStringParameters(List<Parameter> list) {

    Map<String, String> map = new HashMap<String, String>();
    for (Parameter p : list) {
      if (p.getValue() instanceof String) {
        map.put(p.getName(), (String) p.getValue());
      }
    }
    return map;
  }
Ejemplo n.º 7
0
 /**
  * Helper method to get a value of a parameters in the AxisConfiguration
  *
  * @param axisConfiguration AxisConfiguration instance
  * @param paramKey The name / key of the parameter
  * @return The value of the parameter
  */
 private static String getAxis2ParameterValue(
     AxisConfiguration axisConfiguration, String paramKey) {
   Parameter parameter = axisConfiguration.getParameter(paramKey);
   if (parameter == null) {
     return null;
   }
   Object value = parameter.getValue();
   if (value != null && value instanceof String) {
     return (String) parameter.getValue();
   } else {
     return null;
   }
 }
  /**
   * Register a new ThreadContextMigrator.
   *
   * @param axisConfiguration
   * @param threadContextMigratorListID The name of the parameter in the AxisConfiguration that
   *     contains the list of migrators.
   * @param migrator
   */
  public static void addThreadContextMigrator(
      AxisConfiguration axisConfiguration,
      String threadContextMigratorListID,
      ThreadContextMigrator migrator)
      throws AxisFault {
    Parameter param = axisConfiguration.getParameter(threadContextMigratorListID);

    if (param == null) {
      param = new Parameter(threadContextMigratorListID, new LinkedList());
      axisConfiguration.addParameter(param);
    }

    List migratorList = (List) param.getValue();
    migratorList.add(migrator);
  }
  /**
   * Activate any registered ThreadContextMigrators to move context info to the thread of execution.
   *
   * @param threadContextMigratorListID The name of the parameter in the AxisConfiguration that
   *     contains the list of migrators.
   * @param msgContext
   * @throws AxisFault
   */
  public static void performMigrationToThread(
      String threadContextMigratorListID, MessageContext msgContext) throws AxisFault {
    if (msgContext == null) {
      return;
    }

    AxisConfiguration axisConfiguration =
        msgContext.getConfigurationContext().getAxisConfiguration();
    Parameter param = axisConfiguration.getParameter(threadContextMigratorListID);

    if (param != null) {
      List migratorList = (List) param.getValue();
      ListIterator threadContextMigrators = migratorList.listIterator();
      while (threadContextMigrators.hasNext()) {
        ((ThreadContextMigrator) threadContextMigrators.next()).migrateContextToThread(msgContext);
      }
    }
  }
Ejemplo n.º 10
0
 protected void build() throws IOException {
   InputStream jsFileStream = null;
   Parameter implInfoParam = service.getParameter(MashupConstants.SERVICE_JS);
   if (implInfoParam == null) {
     throw new AxisFault("Parameter 'ServiceJS' not specified");
   }
   Object value = implInfoParam.getValue();
   // We are reading the stream from the axis2 parameter
   jsFileStream =
       new ByteArrayInputStream(
           ((String) service.getParameter(MashupConstants.SERVICE_JS_STREAM).getValue())
               .getBytes());
   // We are reading the stream from the axis2 parameter
   try {
     sourceReader = new StringReader(HostObjectUtil.streamToString(jsFileStream));
   } catch (ScriptException e) {
     throw new IOException(e);
   }
 }
Ejemplo n.º 11
0
 @Override
 protected void doInit() throws AxisFault {
   super.doInit();
   try {
     StandardFileSystemManager fsm = new StandardFileSystemManager();
     fsm.setConfiguration(getClass().getClassLoader().getResource("providers.xml"));
     fsm.init();
     this.workerPool = super.workerPool;
     fsManager = fsm;
     Parameter lockFlagParam =
         getTransportInDescription().getParameter(VFSConstants.TRANSPORT_FILE_LOCKING);
     if (lockFlagParam != null) {
       String strLockingFlag = lockFlagParam.getValue().toString();
       // by-default enabled, if explicitly specified as "disable" make it disable
       if (VFSConstants.TRANSPORT_FILE_LOCKING_DISABLED.equals(strLockingFlag)) {
         globalFileLockingFlag = false;
       }
     }
   } catch (FileSystemException e) {
     handleException("Error initializing the file transport : " + e.getMessage(), e);
   }
 }
Ejemplo n.º 12
0
  public void processEditServicePara(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    String serviceName = req.getParameter("axisService");
    if (req.getParameter("changePara") != null) {
      AxisService service = configContext.getAxisConfiguration().getService(serviceName);
      if (service != null) {
        for (Parameter parameter : service.getParameters()) {
          String para = req.getParameter(serviceName + "_" + parameter.getName());
          service.addParameter(new Parameter(parameter.getName(), para));
        }

        for (Iterator<AxisOperation> iterator = service.getOperations(); iterator.hasNext(); ) {
          AxisOperation axisOperation = iterator.next();
          String op_name = axisOperation.getName().getLocalPart();

          for (Parameter parameter : axisOperation.getParameters()) {
            String para = req.getParameter(op_name + "_" + parameter.getName());

            axisOperation.addParameter(new Parameter(parameter.getName(), para));
          }
        }
      }
      res.setContentType("text/html");
      req.setAttribute("status", "Parameters Changed Successfully.");
      req.getSession().removeAttribute(Constants.SERVICE);
    } else {
      AxisService serviceTemp =
          configContext.getAxisConfiguration().getServiceForActivation(serviceName);
      if (serviceTemp.isActive()) {

        if (serviceName != null) {
          req.getSession()
              .setAttribute(
                  Constants.SERVICE, configContext.getAxisConfiguration().getService(serviceName));
        }
      } else {
        req.setAttribute(
            "status",
            "Service "
                + serviceName
                + " is not an active service"
                + ". \n Only parameters of active services can be edited.");
      }
    }
    renderView(SERVICE_PARA_EDIT_JSP_NAME, req, res);
  }
Ejemplo n.º 13
0
  /**
   * Populates service from corresponding OM.
   *
   * @param service_element an OMElement for the &lt;service&gt; tag
   * @return a filled-in AxisService, configured from the passed XML
   * @throws DeploymentException if there is a problem
   */
  public AxisService populateService(OMElement service_element) throws DeploymentException {
    try {
      // Determine whether service should be activated.
      String serviceActivate = service_element.getAttributeValue(new QName(ATTRIBUTE_ACTIVATE));
      if (serviceActivate != null) {
        if ("true".equals(serviceActivate)) {
          service.setActive(true);
        } else if ("false".equals(serviceActivate)) {
          service.setActive(false);
        }
      }

      // Processing service level parameters
      OMAttribute serviceNameatt = service_element.getAttribute(new QName(ATTRIBUTE_NAME));

      // If the service name is explicitly specified in the services.xml
      // then use that as the service name
      if (serviceNameatt != null) {
        if (!"".equals(serviceNameatt.getAttributeValue().trim())) {
          AxisService wsdlService = wsdlServiceMap.get(serviceNameatt.getAttributeValue());
          if (wsdlService != null) {
            wsdlService.setClassLoader(service.getClassLoader());
            wsdlService.setParent(service.getAxisServiceGroup());
            service = wsdlService;
            service.setWsdlFound(true);
            service.setCustomWsdl(true);
          }
          service.setName(serviceNameatt.getAttributeValue());
          // To be on the safe side
          if (service.getDocumentation() == null) {
            service.setDocumentation(serviceNameatt.getAttributeValue());
          }
        }
      }

      Iterator itr = service_element.getChildrenWithName(new QName(TAG_PARAMETER));
      processParameters(itr, service, service.getParent());

      Parameter childFirstClassLoading =
          service.getParameter(Constants.Configuration.ENABLE_CHILD_FIRST_CLASS_LOADING);
      if (childFirstClassLoading != null) {
        ClassLoader cl = service.getClassLoader();
        if (cl instanceof DeploymentClassLoader) {
          DeploymentClassLoader deploymentClassLoader = (DeploymentClassLoader) cl;
          if (JavaUtils.isTrueExplicitly(childFirstClassLoading.getValue())) {
            deploymentClassLoader.setChildFirstClassLoading(true);
          } else if (JavaUtils.isFalseExplicitly(childFirstClassLoading.getValue())) {
            deploymentClassLoader.setChildFirstClassLoading(false);
          }
        }
      }

      // If multiple services in one service group have different values
      // for the PARENT_FIRST
      // parameter then the final value become the value specified by the
      // last service in the group
      // Parameter parameter =
      // service.getParameter(DeploymentClassLoader.PARENT_FIRST);
      // if (parameter !=null && "false".equals(parameter.getValue())) {
      // ClassLoader serviceClassLoader = service.getClassLoader();
      // ((DeploymentClassLoader)serviceClassLoader).setParentFirst(false);
      // }
      // process service description
      OMElement descriptionElement =
          service_element.getFirstChildWithName(new QName(TAG_DESCRIPTION));
      if (descriptionElement != null) {
        OMElement descriptionValue = descriptionElement.getFirstElement();
        if (descriptionValue != null) {
          service.setDocumentation(descriptionValue);
        } else {
          service.setDocumentation(descriptionElement.getText());
        }
      } else {
        serviceNameatt = service_element.getAttribute(new QName(ATTRIBUTE_NAME));

        if (serviceNameatt != null) {
          if (!"".equals(serviceNameatt.getAttributeValue().trim())
              && service.getDocumentation() == null) {
            service.setDocumentation(serviceNameatt.getAttributeValue());
          }
        }
      }

      if (service.getParameter("ServiceClass") == null) {
        log.debug("The Service " + service.getName() + " does not specify a Service Class");
      }

      // Process WS-Addressing flag attribute
      OMAttribute addressingRequiredatt =
          service_element.getAttribute(new QName(ATTRIBUTE_WSADDRESSING));
      if (addressingRequiredatt != null) {
        String addressingRequiredString = addressingRequiredatt.getAttributeValue();
        AddressingHelper.setAddressingRequirementParemeterValue(service, addressingRequiredString);
      }

      // Setting service target namespace if any
      OMAttribute targetNameSpace = service_element.getAttribute(new QName(TARGET_NAME_SPACE));

      if (targetNameSpace != null) {
        String nameSpeceVale = targetNameSpace.getAttributeValue();
        if (nameSpeceVale != null && !"".equals(nameSpeceVale)) {
          service.setTargetNamespace(nameSpeceVale);
        }
      } else {
        if (service.getTargetNamespace() == null || "".equals(service.getTargetNamespace())) {
          service.setTargetNamespace(Java2WSDLConstants.DEFAULT_TARGET_NAMESPACE);
        }
      }

      // Processing service lifecycle attribute
      OMAttribute serviceLifeCycleClass = service_element.getAttribute(new QName(TAG_CLASS_NAME));
      if (serviceLifeCycleClass != null) {
        String className = serviceLifeCycleClass.getAttributeValue();
        loadServiceLifeCycleClass(className);
      }
      // Setting schema namespece if any
      OMElement schemaElement = service_element.getFirstChildWithName(new QName(SCHEMA));
      if (schemaElement != null) {
        OMAttribute schemaNameSpace = schemaElement.getAttribute(new QName(SCHEMA_NAME_SPACE));
        if (schemaNameSpace != null) {
          String nameSpeceVale = schemaNameSpace.getAttributeValue();
          if (nameSpeceVale != null && !"".equals(nameSpeceVale)) {
            service.setSchemaTargetNamespace(nameSpeceVale);
          }
        }
        OMAttribute elementFormDefault =
            schemaElement.getAttribute(new QName(SCHEMA_ELEMENT_QUALIFIED));
        if (elementFormDefault != null) {
          String value = elementFormDefault.getAttributeValue();
          if ("true".equals(value)) {
            service.setElementFormDefault(true);
          } else if ("false".equals(value)) {
            service.setElementFormDefault(false);
          }
        }

        // package to namespace mapping. This will be an element that
        // maps pkg names to a namespace
        // when this is doing AxisService.getSchemaTargetNamespace will
        // be overridden
        // This will be <mapping/> with @namespace and @package
        Iterator mappingIterator = schemaElement.getChildrenWithName(new QName(MAPPING));
        if (mappingIterator != null) {
          Map<String, String> pkg2nsMap = new Hashtable<String, String>();
          while (mappingIterator.hasNext()) {
            OMElement mappingElement = (OMElement) mappingIterator.next();
            OMAttribute namespaceAttribute =
                mappingElement.getAttribute(new QName(ATTRIBUTE_NAMESPACE));
            OMAttribute packageAttribute =
                mappingElement.getAttribute(new QName(ATTRIBUTE_PACKAGE));
            if (namespaceAttribute != null && packageAttribute != null) {
              String namespaceAttributeValue = namespaceAttribute.getAttributeValue();
              String packageAttributeValue = packageAttribute.getAttributeValue();
              if (namespaceAttributeValue != null && packageAttributeValue != null) {
                pkg2nsMap.put(packageAttributeValue.trim(), namespaceAttributeValue.trim());
              } else {
                log.warn(
                    "Either value of @namespce or @packagename not available. Thus, generated will be selected.");
              }
            } else {
              log.warn(
                  "Either @namespce or @packagename not available. Thus, generated will be selected.");
            }
          }
          service.setP2nMap(pkg2nsMap);
        }
      }

      // processing Default Message receivers
      OMElement messageReceiver =
          service_element.getFirstChildWithName(new QName(TAG_MESSAGE_RECEIVERS));
      if (messageReceiver != null) {
        HashMap<String, MessageReceiver> mrs =
            processMessageReceivers(service.getClassLoader(), messageReceiver);
        for (Map.Entry<String, MessageReceiver> entry : mrs.entrySet()) {
          service.addMessageReceiver(entry.getKey(), entry.getValue());
        }
      }

      // Removing exclude operations
      OMElement excludeOperations =
          service_element.getFirstChildWithName(new QName(TAG_EXCLUDE_OPERATIONS));
      ArrayList<String> excludeops = null;
      if (excludeOperations != null) {
        excludeops = processExcludeOperations(excludeOperations);
      }
      if (excludeops == null) {
        excludeops = new ArrayList<String>();
      }
      Utils.addExcludeMethods(excludeops);

      // <schema targetNamespace="http://x.y.z"/>
      // setting the PolicyInclude
      // processing <wsp:Policy> .. </..> elements
      Iterator policyElements =
          service_element.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY));

      if (policyElements != null && policyElements.hasNext()) {
        processPolicyElements(policyElements, service.getPolicySubject());
      }

      // processing <wsp:PolicyReference> .. </..> elements
      Iterator policyRefElements =
          service_element.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY_REF));

      if (policyRefElements != null && policyRefElements.hasNext()) {
        processPolicyRefElements(policyRefElements, service.getPolicySubject());
      }

      // processing service scope
      String sessionScope = service_element.getAttributeValue(new QName(ATTRIBUTE_SCOPE));
      if (sessionScope != null) {
        service.setScope(sessionScope);
      }

      // processing service-wide modules which required to engage globally
      Iterator moduleRefs = service_element.getChildrenWithName(new QName(TAG_MODULE));

      processModuleRefs(moduleRefs);

      // processing transports
      OMElement transports = service_element.getFirstChildWithName(new QName(TAG_TRANSPORTS));
      if (transports != null) {
        Iterator transport_itr = transports.getChildrenWithName(new QName(TAG_TRANSPORT));
        ArrayList<String> trs = new ArrayList<String>();
        while (transport_itr.hasNext()) {
          OMElement trsEle = (OMElement) transport_itr.next();
          String transportName = trsEle.getText().trim();
          if (axisConfig.getTransportIn(transportName) == null) {
            log.warn(
                "Service [ "
                    + service.getName()
                    + "] is trying to expose in a transport : "
                    + transportName
                    + " and which is not available in Axis2");
          } else {
            trs.add(transportName);
          }
        }

        if (trs.isEmpty()) {
          throw new AxisFault(
              "Service ["
                  + service.getName()
                  + "] is trying expose in tranpsorts: "
                  + transports
                  + " and which is/are not available in Axis2");
        }
        service.setExposedTransports(trs);
      }
      // processing operations
      Iterator operationsIterator = service_element.getChildrenWithName(new QName(TAG_OPERATION));
      ArrayList ops = processOperations(operationsIterator);

      for (int i = 0; i < ops.size(); i++) {
        AxisOperation operationDesc = (AxisOperation) ops.get(i);
        ArrayList wsamappings = operationDesc.getWSAMappingList();
        if (wsamappings == null) {
          continue;
        }
        if (service.getOperation(operationDesc.getName()) == null) {
          service.addOperation(operationDesc);
        }
        for (int j = 0; j < wsamappings.size(); j++) {
          String mapping = (String) wsamappings.get(j);
          if (mapping.length() > 0) {
            service.mapActionToOperation(mapping, operationDesc);
          }
        }
      }
      String objectSupplierValue = (String) service.getParameterValue(TAG_OBJECT_SUPPLIER);
      if (objectSupplierValue != null) {
        loadObjectSupplierClass(objectSupplierValue);
      }
      // Set the default message receiver for the operations that were
      // not listed in the services.xml
      setDefaultMessageReceivers();
      Utils.processBeanPropertyExclude(service);
      if (!service.isUseUserWSDL()) {
        // Generating schema for the service if the impl class is Java
        if (!service.isWsdlFound()) {
          // trying to generate WSDL for the service using JAM and
          // Java reflection
          try {
            if (generateWsdl(service)) {
              Utils.fillAxisService(service, axisConfig, excludeops, null);
            } else {
              ArrayList nonRpcOperations = getNonRPCMethods(service);
              Utils.fillAxisService(service, axisConfig, excludeops, nonRpcOperations);
            }
          } catch (Exception e) {
            throw new DeploymentException(
                Messages.getMessage("errorinschemagen", e.getMessage()), e);
          }
        }
      }
      if (service.isCustomWsdl()) {
        OMElement mappingElement =
            service_element.getFirstChildWithName(new QName(TAG_PACKAGE2QNAME));
        if (mappingElement != null) {
          processTypeMappings(mappingElement);
        }
      }

      for (String opName : excludeops) {
        service.removeOperation(new QName(opName));
      }

      // Need to call the same logic towice
      setDefaultMessageReceivers();
      Iterator moduleConfigs = service_element.getChildrenWithName(new QName(TAG_MODULE_CONFIG));
      processServiceModuleConfig(moduleConfigs, service, service);

      // Loading Data Locator(s) configured
      OMElement dataLocatorElement =
          service_element.getFirstChildWithName(new QName(DRConstants.DATA_LOCATOR_ELEMENT));
      if (dataLocatorElement != null) {
        processDataLocatorConfig(dataLocatorElement, service);
      }

      processEndpoints(service);
      processPolicyAttachments(service_element, service);

    } catch (AxisFault axisFault) {
      throw new DeploymentException(axisFault);
    }

    startupServiceLifecycle();
    return service;
  }
  @Override
  public void deleteApplication(String applicationName, String tenantDomain, String userName)
      throws IdentityApplicationManagementException {
    try {

      startTenantFlow(tenantDomain, userName);

      // invoking the listeners
      List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();

      for (ApplicationMgtListener listener : listeners) {
        listener.deleteApplication(applicationName);
      }

      if (!ApplicationMgtUtil.isUserAuthorized(applicationName)) {
        log.warn(
            "Illegal Access! User "
                + CarbonContext.getThreadLocalCarbonContext().getUsername()
                + " does not have access to the application "
                + applicationName);
        throw new IdentityApplicationManagementException("User not authorized");
      }

      ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
      ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
      appDAO.deleteApplication(applicationName);

      ApplicationMgtUtil.deleteAppRole(applicationName);
      ApplicationMgtUtil.deletePermissions(applicationName);

      if (serviceProvider != null
          && serviceProvider.getInboundAuthenticationConfig() != null
          && serviceProvider
                  .getInboundAuthenticationConfig()
                  .getInboundAuthenticationRequestConfigs()
              != null) {

        InboundAuthenticationRequestConfig[] configs =
            serviceProvider
                .getInboundAuthenticationConfig()
                .getInboundAuthenticationRequestConfigs();

        for (InboundAuthenticationRequestConfig config : configs) {

          if (IdentityApplicationConstants.Authenticator.SAML2SSO.NAME.equalsIgnoreCase(
                  config.getInboundAuthType())
              && config.getInboundAuthKey() != null) {

            SAMLApplicationDAO samlDAO =
                ApplicationMgtSystemConfig.getInstance().getSAMLClientDAO();
            samlDAO.removeServiceProviderConfiguration(config.getInboundAuthKey());

          } else if (IdentityApplicationConstants.OAuth2.NAME.equalsIgnoreCase(
                  config.getInboundAuthType())
              && config.getInboundAuthKey() != null) {
            OAuthApplicationDAO oathDAO =
                ApplicationMgtSystemConfig.getInstance().getOAuthOIDCClientDAO();
            oathDAO.removeOAuthApplication(config.getInboundAuthKey());

          } else if ("kerberos".equalsIgnoreCase(config.getInboundAuthType())
              && config.getInboundAuthKey() != null) {

            DirectoryServerManager directoryServerManager = new DirectoryServerManager();
            directoryServerManager.removeServer(config.getInboundAuthKey());

          } else if (IdentityApplicationConstants.Authenticator.WSTrust.NAME.equalsIgnoreCase(
                  config.getInboundAuthType())
              && config.getInboundAuthKey() != null) {
            try {
              AxisService stsService = getAxisConfig().getService(ServerConstants.STS_NAME);
              Parameter origParam =
                  stsService.getParameter(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());

              if (origParam != null) {
                OMElement samlConfigElem =
                    origParam
                        .getParameterElement()
                        .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG);

                SAMLTokenIssuerConfig samlConfig = new SAMLTokenIssuerConfig(samlConfigElem);
                samlConfig.getTrustedServices().remove(config.getInboundAuthKey());
                setSTSParameter(samlConfig);
                removeTrustedService(
                    ServerConstants.STS_NAME, ServerConstants.STS_NAME, config.getInboundAuthKey());
              } else {
                throw new IdentityApplicationManagementException(
                    "missing parameter : "
                        + SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
              }
            } catch (Exception e) {
              String error = "Error while removing a trusted service";
              log.error(error, e);
              throw new IdentityApplicationManagementException(error, e);
            }
          }
        }
      }

    } catch (Exception e) {
      String error = "Error occurred while deleting the application";
      log.error(error, e);
      throw new IdentityApplicationManagementException(error, e);
    } finally {
      endTenantFlow();
    }
  }
Ejemplo n.º 15
0
  public AxisConfiguration populateAxisConfiguration(InputStream in) throws DeploymentException {
    axisConfig = TenantAxisConfiguration.createInstance();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getCurrentContext(axisConfig);
    carbonContext.setTenantId(tenantId);
    carbonContext.setTenantDomain(tenantDomain);

    boolean isUrlRepo = CarbonUtils.isURL(repoLocation);
    if (repoLocation != null && repoLocation.trim().length() != 0) {
      try {
        if (isUrlRepo) {
          URL axis2Repository = new URL(repoLocation);
          axisConfig.setRepository(axis2Repository);
        } else {
          axisConfig.setRepository(new URL("file://" + repoLocation));
        }
      } catch (MalformedURLException e) {
        throw new DeploymentException("Invalid URL " + repoLocation, e);
      }
    }

    // Notify all observers
    if (bundleContext != null) {
      ServiceTracker tracker =
          new ServiceTracker(
              bundleContext, PreAxisConfigurationPopulationObserver.class.getName(), null);
      tracker.open();
      Object[] services = tracker.getServices();
      if (services != null) {
        for (Object service : services) {
          ((PreAxisConfigurationPopulationObserver) service).createdAxisConfiguration(axisConfig);
        }
      }
      tracker.close();
    }
    try {
      // Add the relevant AxisObservers to the tenantAxisConfig
      if (bundleContext != null) {
        ServiceTracker tracker =
            new ServiceTracker(bundleContext, AxisObserver.class.getName(), null);
        tracker.open();
        ServiceReference[] serviceRefs = tracker.getServiceReferences();
        if (serviceRefs != null) {
          for (ServiceReference serviceRef : serviceRefs) {
            if (serviceRef.getProperty(MultitenantConstants.TENANT_ID) != null
                && tenantId == (Integer) serviceRef.getProperty(MultitenantConstants.TENANT_ID)) {
              axisConfig.addObservers((AxisObserver) bundleContext.getService(serviceRef));
            }
          }
        }
        tracker.close();
      }

      // Set services dir
      File servicesDir =
          new File(repoLocation + File.separator + CarbonUtils.getAxis2ServicesDir(axisConfig));
      if (!servicesDir.exists() && !servicesDir.mkdirs()) {
        throw new DeploymentException(
            "Could not create services directory " + servicesDir.getAbsolutePath());
      }

      // Set modules dir
      String modulesDirName = "axis2modules";
      File modulesDir = new File(repoLocation + File.separator + modulesDirName);
      if (!modulesDir.exists() && !modulesDir.mkdirs()) {
        throw new DeploymentException(
            "Could not create modules directory " + modulesDir.getAbsolutePath());
      }
      axisConfig.addParameter(new Parameter(DeploymentConstants.MODULE_DRI_PATH, modulesDirName));
    } catch (AxisFault e) {
      String msg =
          "Cannot add DeploymentConstants.SERVICE_DIR_PATH or "
              + "DeploymentConstants.MODULE_DIR_PATH parameters";
      log.error(msg, e);
      throw new DeploymentException(msg, e);
    }

    carbonContext.setRegistry(RegistryType.SYSTEM_CONFIGURATION, registry);
    try {
      // TODO: The governance system registry should be passed into the tenant axis
      // configurator like the config system registry - Senaka.
      carbonContext.setRegistry(
          RegistryType.SYSTEM_GOVERNANCE,
          CarbonCoreDataHolder.getInstance()
              .getRegistryService()
              .getGovernanceSystemRegistry(tenantId));
      carbonContext.setRegistry(
          RegistryType.LOCAL_REPOSITORY,
          CarbonCoreDataHolder.getInstance().getRegistryService().getLocalRepository(tenantId));
    } catch (Exception ignored) {
      // We are not worried about the exception in here.
    }

    // The following two lines of code are kept for backward compatibility. Remove this once we
    // are certain that this is not required. -- Senaka.
    // Please also note that we no longer need to set the user realm to the configuration
    // explicitly.
    setRegistry();
    setUserRealm();

    // Add the DeploymentInterceptor for the tenant AxisConfigurations
    DeploymentInterceptor interceptor = new DeploymentInterceptor();
    interceptor.setRegistry(registry);
    interceptor.init(axisConfig);
    axisConfig.addObservers(interceptor);

    setHostName(axisConfig);

    // TCCL will be based on OSGi
    AxisConfigBuilder builder = new AxisConfigBuilder(in, axisConfig, this);
    builder.populateConfig();
    try {
      if (in != null) {
        in.close();
      }
    } catch (IOException e) {
      String msg = "error in closing input stream";
      log.error(msg, e);
    }
    axisConfig.setConfigurator(this);
    Parameter disableArtifactLoading = axisConfig.getParameter("DisableArtifactLoading");
    if (disableArtifactLoading == null || "false".equals(disableArtifactLoading.getValue())) {
      moduleDeployer = new ModuleDeployer(axisConfig);
      new Axis2ModuleRegistry(axisConfig).register(moduleBundles);
      // Add Ghost deployer registry only if ghost is on
      if (GhostDeployerUtils.isGhostOn()) {
        new GhostDeployerRegistry(axisConfig).register(deployerBundles);
      } else {
        new Axis2DeployerRegistry(axisConfig).register(deployerBundles);
      }
    }
    return axisConfig;
  }
Ejemplo n.º 16
0
 private boolean axisSecurityEnabled() {
   Parameter parameter =
       configContext.getAxisConfiguration().getParameter(Constants.ADMIN_SECURITY_DISABLED);
   return parameter == null || !"true".equals(parameter.getValue());
 }
Ejemplo n.º 17
0
  public void init(ServiceContext serviceContext) throws AxisFault {
    if (initialization == INITIALIZATION_ERROR) {
      throw new AxisFault("CreationService not available: configuration failed!");
    }

    if (initialization == INITIALIZATION_OK) {
      return;
    }

    ConfigurationContext configurationContext = serviceContext.getConfigurationContext();

    if (configurationContext == null) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: ConfigurationContext not found!");
      return;
    }

    AxisConfiguration axisConfiguration = configurationContext.getAxisConfiguration();
    if (axisConfiguration == null) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: AxisConfiguration not found!");
      return;
    }

    AxisService axisService = axisConfiguration.getService("ActivityCreationService");
    if (axisService == null) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: AxisService 'CreationService' not found!");
      return;
    }

    Parameter parameter = axisService.getParameter("serviceLogConfigurationFile");
    if (parameter != null) {
      LogManager.resetConfiguration();
      PropertyConfigurator.configure((String) parameter.getValue());
    }

    ServiceConfig serviceConfig = ServiceConfig.getConfiguration();
    if (serviceConfig == null) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: cannot initialize the ServiceConfig");
      return;
    }

    logger.info("starting the CreationService initialization...");

    CommandManagerInterface commandManager = null;
    try {
      commandManager = CommandManager.getInstance();
    } catch (Throwable t) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: cannot get instance of CommandManager: " + t.getMessage());
      return;
    }

    if (!commandManager.checkCommandExecutor("ActivityExecutor", ActivityCmd.ACTIVITY_MANAGEMENT)) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: ActivityExecutor not loaded!");
      return;
    }

    if (!commandManager.checkCommandExecutor(
        "DelegationExecutor", DelegationCommand.DELEGATION_MANAGEMENT)) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: DelegationExecutor not loaded!");
      return;
    }

    try {
      String hostName = InetAddress.getLocalHost().getCanonicalHostName();
      activityManagerURL =
          "https://" + hostName + ":8443/ce-cream-es/services/ActivityManagementService";
      resourceInfoEndpointURL =
          "https://" + hostName + ":8443/ce-cream-es/services/ResourceInfoService";
      gsiURL = "gsiftp://" + hostName;
    } catch (Throwable t) {
      initialization = INITIALIZATION_ERROR;
      logger.error("Configuration error: cannot get the host name: " + t.getMessage());
      return;
    }

    initialization = INITIALIZATION_OK;
    logger.info("CreationService initialization done!");
    logger.info("CreationService started!");
  }
Ejemplo n.º 18
0
  /**
   * Initialize the transport sender, and execute reactor in new separate thread
   *
   * @param cfgCtx the Axis2 configuration context
   * @param transportOut the description of the http/s transport from Axis2 configuration
   * @throws AxisFault thrown on an error
   */
  public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut)
      throws AxisFault {
    this.configurationContext = cfgCtx;

    cfg = NHttpConfiguration.getInstance();
    params = new BasicHttpParams();
    params
        .setIntParameter(
            CoreConnectionPNames.SO_TIMEOUT,
            cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000))
        .setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT,
            cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000))
        .setIntParameter(
            CoreConnectionPNames.SOCKET_BUFFER_SIZE,
            cfg.getProperty(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024))
        .setParameter(CoreProtocolPNames.USER_AGENT, "Synapse-HttpComponents-NIO");
    //                .setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,
    //
    // cfg.getStringValue(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,HTTP.DEFAULT_PROTOCOL_CHARSET));
    // //TODO:This does not works with HTTPCore 4.3

    name = transportOut.getName().toUpperCase(Locale.US) + " Sender";

    ClientConnFactoryBuilder contextBuilder = initConnFactoryBuilder(transportOut);
    connFactory = contextBuilder.createConnFactory(params);

    connpool = new ConnectionPool();

    proxyConfig = new ProxyConfigBuilder().build(transportOut);
    log.info(proxyConfig.logProxyConfig());

    Parameter param = transportOut.getParameter("warnOnHTTP500");
    if (param != null) {
      String[] warnOnHttp500 = ((String) param.getValue()).split("\\|");
      cfgCtx.setNonReplicableProperty("warnOnHTTP500", warnOnHttp500);
    }

    IOReactorConfig ioReactorConfig = new IOReactorConfig();
    ioReactorConfig.setIoThreadCount(NHttpConfiguration.getInstance().getClientIOWorkers());
    ioReactorConfig.setSoTimeout(cfg.getProperty(NhttpConstants.SO_TIMEOUT_RECEIVER, 60000));
    ioReactorConfig.setConnectTimeout(
        cfg.getProperty(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000));
    ioReactorConfig.setTcpNoDelay(cfg.getProperty(CoreConnectionPNames.TCP_NODELAY, 1) == 1);
    if (cfg.getBooleanValue("http.nio.interest-ops-queueing", false)) {
      ioReactorConfig.setInterestOpQueued(true);
    }

    try {
      String prefix = name + " I/O dispatcher";
      ioReactor =
          new DefaultConnectingIOReactor(
              ioReactorConfig,
              new NativeThreadFactory(new ThreadGroup(prefix + " thread group"), prefix));
      ioReactor.setExceptionHandler(
          new IOReactorExceptionHandler() {
            public boolean handle(IOException ioException) {
              log.warn(
                  "System may be unstable: IOReactor encountered a checked exception : "
                      + ioException.getMessage(),
                  ioException);
              return true;
            }

            public boolean handle(RuntimeException runtimeException) {
              log.warn(
                  "System may be unstable: IOReactor encountered a runtime exception : "
                      + runtimeException.getMessage(),
                  runtimeException);
              return true;
            }
          });
    } catch (IOException e) {
      log.error("Error starting the IOReactor", e);
      throw new AxisFault(e.getMessage(), e);
    }

    metrics = new NhttpMetricsCollector(false, transportOut.getName());
    handler = new ClientHandler(connpool, connFactory, proxyConfig, cfgCtx, params, metrics);
    iodispatch = new ClientIODispatch(handler, connFactory);
    final IOEventDispatch ioEventDispatch = iodispatch;

    // start the Sender in a new seperate thread
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  ioReactor.execute(ioEventDispatch);
                } catch (InterruptedIOException ex) {
                  log.fatal("Reactor Interrupted");
                } catch (IOException e) {
                  log.fatal("Encountered an I/O error: " + e.getMessage(), e);
                }
                log.info(name + " Shutdown");
              }
            },
            "HttpCoreNIOSender");
    t.start();
    log.info(name + " starting");

    // register with JMX
    mbeanSupport = new TransportMBeanSupport(this, "nio-" + transportOut.getName());
    mbeanSupport.register();

    state = BaseConstants.STARTED;
  }