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");
    }
  }
 static {
   String PORT_OFFSET = "Ports.Offset";
   String HOST_NAME = "HostName";
   int DEFAULT_HTTPS_PORT = 9443;
   CARBON_HOST_URL =
       "https://"
           + ServerConfiguration.getInstance().getFirstProperty(HOST_NAME)
           + ":"
           +
           // adds the offset defined in the server configs to the default 9763 port
           (Integer.parseInt(ServerConfiguration.getInstance().getFirstProperty(PORT_OFFSET))
               + DEFAULT_HTTPS_PORT);
 }
  public void init(ConfigurationContext configurationContext) {

    tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    String artifactPath = CarbonUtils.getCarbonRepository() + "gadgets";
    File artifactsDir = new File(artifactPath);

    // checking whether its the gadget server is so, setting the gadget path
    String serverName = ServerConfiguration.getInstance().getFirstProperty("Name").trim();

    if (serverName.contains(DashboardConstants.PRODUCT_SERVER_NAME)
        || serverName.contains(DashboardConstants.SERVICE_SERVER_NAME)) {
      REGISTRY_GADGET_STORAGE_PATH =
          DashboardConstants.GS_REGISTRY_ROOT + DashboardConstants.GADGET_PATH;
    }

    if (!artifactsDir.exists()) {
      // If the directory is not there create it
      boolean created = artifactsDir.mkdir();
      if (!created) {
        log.debug("Directory could not be created at : " + artifactPath);
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("Initializing Gadget Deployer..");
    }
  }
 protected Cache getGatewayKeyCache() {
   String apimGWCacheExpiry =
       ServiceReferenceHolder.getInstance()
           .getAPIManagerConfiguration()
           .getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY);
   if (!gatewayKeyCacheInit) {
     gatewayKeyCacheInit = true;
     if (apimGWCacheExpiry != null) {
       return APIUtil.getCache(
           APIConstants.API_MANAGER_CACHE_MANAGER,
           APIConstants.GATEWAY_KEY_CACHE_NAME,
           Long.parseLong(apimGWCacheExpiry),
           Long.parseLong(apimGWCacheExpiry));
     } else {
       long defaultCacheTimeout =
           Long.valueOf(
                   ServerConfiguration.getInstance()
                       .getFirstProperty(APIConstants.DEFAULT_CACHE_TIMEOUT))
               * 60;
       return APIUtil.getCache(
           APIConstants.API_MANAGER_CACHE_MANAGER,
           APIConstants.GATEWAY_KEY_CACHE_NAME,
           defaultCacheTimeout,
           defaultCacheTimeout);
     }
   }
   return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
       .getCache(APIConstants.GATEWAY_KEY_CACHE_NAME);
 }
 private void populateGetRequestProcessors() throws AxisFault {
   try {
     OMElement docEle = XMLUtils.toOM(ServerConfiguration.getInstance().getDocumentElement());
     if (docEle != null) {
       SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
       nsCtx.addNamespace("wsas", ServerConstants.CARBON_SERVER_XML_NAMESPACE);
       XPath xp = new AXIOMXPath("//wsas:HttpGetRequestProcessors/wsas:Processor");
       xp.setNamespaceContext(nsCtx);
       List nodeList = xp.selectNodes(docEle);
       for (Object aNodeList : nodeList) {
         OMElement processorEle = (OMElement) aNodeList;
         OMElement itemEle = processorEle.getFirstChildWithName(ITEM_QN);
         if (itemEle == null) {
           throw new ServletException("Required element, 'Item' not found!");
         }
         OMElement classEle = processorEle.getFirstChildWithName(CLASS_QN);
         org.wso2.carbon.core.transports.HttpGetRequestProcessor processor;
         if (classEle == null) {
           throw new ServletException("Required element, 'Class' not found!");
         } else {
           processor =
               (org.wso2.carbon.core.transports.HttpGetRequestProcessor)
                   Class.forName(classEle.getText().trim()).newInstance();
         }
         getRequestProcessors.put(itemEle.getText().trim(), processor);
       }
     }
   } catch (Exception e) {
     handleException("Error populating GetRequestProcessors", e);
   }
 }
  private void setServerURLParam(ConfigurationContext configurationContext) {
    // Adding server url as a parameter to webapps servlet context init parameter
    Map<String, WebApplicationsHolder> webApplicationsHolderList =
        WebAppUtils.getAllWebappHolders(configurationContext);

    WebContextParameter serverUrlParam =
        new WebContextParameter(
            "webServiceServerURL",
            CarbonUtils.getServerURL(ServerConfiguration.getInstance(), configurationContext));

    List<WebContextParameter> servletContextParameters =
        (ArrayList<WebContextParameter>)
            configurationContext.getProperty(CarbonConstants.SERVLET_CONTEXT_PARAMETER_LIST);

    if (servletContextParameters != null) {
      servletContextParameters.add(serverUrlParam);
    }

    for (WebApplicationsHolder webApplicationsHolder : webApplicationsHolderList.values()) {
      if (webApplicationsHolder != null) {
        for (WebApplication application : webApplicationsHolder.getStartedWebapps().values()) {
          application
              .getContext()
              .getServletContext()
              .setAttribute(serverUrlParam.getName(), serverUrlParam.getValue());
        }
      }
    }
  }
  public static String getHostName() throws IoTException {
    String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);

    try {
      if (hostName == null) {
        hostName = NetworkUtils.getLocalHostname();
      }
    } catch (SocketException e) {
      throw new IoTException("Error while trying to read hostname.", e);
    }

    return hostName;
  }
  protected Cache getResourceCache() {

    if (!resourceCacheInit) {
      resourceCacheInit = true;
      long defaultCacheTimeout =
          Long.valueOf(
                  ServerConfiguration.getInstance()
                      .getFirstProperty(APIConstants.DEFAULT_CACHE_TIMEOUT))
              * 60;
      return APIUtil.getCache(
          APIConstants.API_MANAGER_CACHE_MANAGER,
          APIConstants.RESOURCE_CACHE_NAME,
          defaultCacheTimeout,
          defaultCacheTimeout);
    }
    return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
        .getCache(APIConstants.RESOURCE_CACHE_NAME);
  }
  public void process(
      HttpRequest request,
      HttpResponse response,
      MessageContext messageContext,
      NHttpServerConnection conn,
      OutputStream outputStream,
      boolean b) {

    boolean isRequestHandled = false;

    String uri = request.getRequestLine().getUri();

    String servicePath = cfgCtx.getServiceContextPath();
    if (!servicePath.startsWith("/")) {
      servicePath = "/" + servicePath;
    }
    String serviceName = getServiceName(request);

    boolean loadBalancer = Boolean.parseBoolean(System.getProperty("wso2.loadbalancer", "false"));
    if (uri.equals("/favicon.ico")) {
      response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY);
      response.addHeader("Location", "http://wso2.org/favicon.ico");
      serverHandler.commitResponseHideExceptions(conn, response);
      isRequestHandled = true;
    } else if (uri.startsWith(servicePath) && (serviceName == null || serviceName.length() == 0)) {
      // check if service listing request is blocked
      if (isServiceListBlocked(uri)) {
        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        serverHandler.commitResponseHideExceptions(conn, response);
      } else {
        generateServicesList(response, conn, outputStream, servicePath);
      }
      try {
        outputStream.flush();
        outputStream.close();
      } catch (IOException ignore) {
      }
      isRequestHandled = true;
    } else {
      int pos = uri.indexOf('?');
      if (pos != -1) {
        String queryString = uri.substring(pos + 1);
        String requestUri = uri.substring(0, pos);
        String requestUrl = uri;
        if (requestUri.indexOf("://") == -1) {
          HttpInetConnection inetConn = (HttpInetConnection) conn;

          String hostName = "localhost";
          ServerConfiguration serverConfig = ServerConfiguration.getInstance();
          if (serverConfig.getFirstProperty("HostName") != null) {
            hostName = serverConfig.getFirstProperty("HostName");
          }

          requestUrl = "http://" + hostName + ":" + inetConn.getLocalPort() + requestUri;
        }

        String contextPath = cfgCtx.getServiceContextPath();
        int beginIndex = -1;
        if (requestUri.indexOf(contextPath) != -1) {
          beginIndex = requestUri.indexOf(contextPath) + contextPath.length() + 1;
        }

        /**
         * This reverseProxyMode was introduce to avoid LB exposing it's own services when invoked
         * through rest call. For a soap call this works well. But for a rest call this does not
         * work as intended. in LB it has to set system property "reverseProxyMode"
         */
        boolean reverseProxyMode = Boolean.parseBoolean(System.getProperty("reverseProxyMode"));
        AxisService axisService = null;
        if (!reverseProxyMode) {
          if (!(beginIndex < 0 || beginIndex > requestUri.length())) {
            serviceName = requestUri.substring(beginIndex);
            axisService = cfgCtx.getAxisConfiguration().getServiceForActivation(serviceName);
          }

          if (axisService == null && !loadBalancer && serviceName != null) {
            // Try to see whether the service is available in a tenant
            try {
              axisService = TenantAxisUtils.getAxisService(serviceName, cfgCtx);
            } catch (AxisFault axisFault) {
              axisFault.printStackTrace();
            }
          }
        }

        if (queryString != null) {
          for (String item : getRequestProcessors.keySet()) {
            if (queryString.indexOf(item) == 0
                && (queryString.equals(item)
                    || queryString.indexOf("&") == item.length()
                    || queryString.indexOf("=") == item.length())) {
              if (axisService == null) {
                continue;
              }

              try {
                processWithGetProcessor(
                    request,
                    response,
                    requestUri,
                    requestUrl,
                    queryString,
                    item,
                    outputStream,
                    conn);
              } catch (Exception e) {
                handleBrowserException(response, conn, outputStream, "Error processing request", e);
              }
              isRequestHandled = true;
              break;
            }
          }
        }
      }
    }

    if (!isRequestHandled) {
      processGetAndDelete(request, response, messageContext, conn, outputStream, "GET", b);
    }
  }