org.wso2.carbon.utils.NetworkUtils Java Examples

The following examples show how to use org.wso2.carbon.utils.NetworkUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultServiceURLBuilder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private String resolveHostName(String hostName) throws URLBuilderException {

        try {
            if (StringUtils.isBlank(hostName)) {
                hostName = NetworkUtils.getLocalHostname();
            }
        } catch (SocketException e) {
            throw new URLBuilderException(String.format("Error while trying to resolve the hostname %s from the " +
                    "system", hostName), e);
        }

        if (StringUtils.isNotBlank(hostName) && hostName.endsWith("/")) {
            hostName = hostName.substring(0, hostName.length() - 1);
        }
        return hostName;
    }
 
Example #2
Source File: JMXClient.java    From product-es with Apache License 2.0 6 votes vote down vote up
/**
 * connect to org.wso2.carbon to invoke different operations
 *
 * @param userName       user name to connect to org.wso2.carbon
 * @param password       password to connect to org.wso2.carbon
 * @param connectionType
 * @param operation
 * @throws Exception
 */
public void connect(String userName, String password, String connectionType, String operation)
        throws Exception {
    try {
        JMXServiceURL url =
                new JMXServiceURL("service:jmx:rmi://" +
                                  NetworkUtils.getLocalHostname() + ":" +
                                  RMIServerPort + "/jndi/rmi://" +
                                  NetworkUtils.getLocalHostname() + ":" +
                                  RMIRegistryPort + "/jmxrmi");
        Hashtable<String, String[]> hashT = new Hashtable<>();
        String[] credentials = new String[]{userName, password};
        hashT.put("jmx.remote.credentials", credentials);
        jmxc = JMXConnectorFactory.connect(url, hashT);
        mbsc = jmxc.getMBeanServerConnection();
        nodeAgent = new ObjectName(connectionType);
        mbsc.invoke(nodeAgent, operation, null, null);
    } catch (Exception ex) {
        log.error("infoAdminServiceStub Initialization fail ");
        throw new Exception("infoAdminServiceStub Initialization fail " + ex.getMessage());
    }
}
 
Example #3
Source File: JMXClient.java    From product-es with Apache License 2.0 6 votes vote down vote up
/**
 * connect to org.wso2.carbon for JMX monitoring
 *
 * @param userName user name to connect to org.wso2.carbon
 * @param password password to connect to org.wso2.carbon
 * @throws Exception
 */
public void connect(String userName, String password) throws Exception {
    try {
        JMXServiceURL url =
                new JMXServiceURL("service:jmx:rmi://" +
                                  NetworkUtils.getLocalHostname() + ":" +
                                  RMIServerPort + "/jndi/rmi://" +
                                  NetworkUtils.getLocalHostname() + ":" +
                                  RMIRegistryPort + "/jmxrmi");
        Hashtable<String, String[]> hashT = new Hashtable<>();
        String[] credentials = new String[]{userName, password};
        hashT.put("jmx.remote.credentials", credentials);
        jmxc = JMXConnectorFactory.connect(url, hashT);
        mbsc = jmxc.getMBeanServerConnection();
        nodeAgent = new ObjectName(CONNECTION_NAME);
    } catch (Exception ex) {
        log.error("infoAdminServiceStub Initialization fail ");
        throw new Exception("infoAdminServiceStub Initialization fail " + ex.getMessage());
    }
}
 
Example #4
Source File: WSDL2Code.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private String getWsdlInformation(String serviceName, AxisConfiguration axisConfig)
        throws AxisFault {
    String ip;
    try {
        ip = NetworkUtils.getLocalHostname();
    } catch (SocketException e) {
        throw new AxisFault("Cannot get local host name", e);
    }
    TransportInDescription http = axisConfig.getTransportIn("http");
    if (http != null) {
        EndpointReference epr =
                ((HttpTransportListener) http.getReceiver()).
                getEPRForService(serviceName, ip);
        String wsdlUrlPrefix = epr.getAddress();
        if (wsdlUrlPrefix.endsWith("/")) {
            wsdlUrlPrefix = wsdlUrlPrefix.substring(0, wsdlUrlPrefix.length() - 1);
        }
        return wsdlUrlPrefix + "?wsdl";
    }
    return null;
}
 
Example #5
Source File: AuthenticationClient.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public boolean authenticate(String username, String password) throws AuthenticationExceptionException,
        RemoteException {
    try {
        boolean isAuthenticated = stub.login(username,password,NetworkUtils.getLocalHostname());
        if(isAuthenticated){
            ServiceContext serviceContext;
            serviceContext = stub._getServiceClient().getLastOperationContext().getServiceContext();
            String sessionCookie;
            sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);

            this.sessionCookie = sessionCookie;
        }else{
            throw new AuthenticationExceptionException("Authentication Failed");
        }
        return isAuthenticated;
    } catch (SocketException e) {
        throw new AuthenticationExceptionException(e);
    }
}
 
Example #6
Source File: Util.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static String getWsdlInformation(String serviceName,
                                          AxisConfiguration axisConfig) throws AxisFault {
    String ip;
    try {
        ip = NetworkUtils.getLocalHostname();
    } catch (SocketException e) {
        throw new AxisFault("Cannot get local host name", e);
    }

    TransportInDescription transportInDescription = axisConfig.getTransportIn("http");

    if (transportInDescription == null) {
        transportInDescription = axisConfig.getTransportIn("https");
    }

    if (transportInDescription != null) {
        EndpointReference[] epr =
                transportInDescription.getReceiver().getEPRsForService(serviceName, ip);
        String wsdlUrlPrefix = epr[0].getAddress();
        if (wsdlUrlPrefix.endsWith("/")) {
            wsdlUrlPrefix = wsdlUrlPrefix.substring(0, wsdlUrlPrefix.length() - 1);
        }
        return wsdlUrlPrefix + "?wsdl";
    }
    return null;
}
 
Example #7
Source File: URLPrinterStartupHandler.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private String getServerUrl() {
    // Hostname
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }
    // HTTPS port
    String mgtConsoleTransport = CarbonUtils.getManagementTransport();
    ConfigurationContextService configContextService =
            UrlPrinterDataHolder.getInstance().getConfigurationContextService();
    int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
    int httpsProxyPort =
            CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), mgtConsoleTransport);
    if (httpsProxyPort > 0) {
        port = httpsProxyPort;
    }
    return "https://" + hostName + ":" + port + "/devicemgt";
}
 
Example #8
Source File: DeviceManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static String getServerBaseHttpUrl() {
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }
    ConfigurationContextService configContextService =
            DeviceManagementDataHolder.getInstance().getConfigurationContextService();
    int port = CarbonUtils.getTransportPort(configContextService, "http");
    int httpProxyPort =
            CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                    "http");
    if (httpProxyPort > 0) {
        port = httpProxyPort;
    }
    return "http://" + hostName + ":" + port;
}
 
Example #9
Source File: DeviceManagerUtil.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public static String getServerBaseHttpsUrl() {
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }
    String mgtConsoleTransport = CarbonUtils.getManagementTransport();
    ConfigurationContextService configContextService =
            DeviceManagementDataHolder.getInstance().getConfigurationContextService();
    int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
    int httpsProxyPort =
            CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                    mgtConsoleTransport);
    if (httpsProxyPort > 0) {
        port = httpsProxyPort;
    }
    return "https://" + hostName + ":" + port;
}
 
Example #10
Source File: DefaultServiceURLBuilderTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {

    mockStatic(CarbonUtils.class);
    mockStatic(ServerConfiguration.class);
    mockStatic(NetworkUtils.class);
    mockStatic(IdentityCoreServiceComponent.class);
    mockStatic(IdentityTenantUtil.class);
    mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedCarbonContext = mock(PrivilegedCarbonContext.class);

    when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    when(ServerConfiguration.getInstance()).thenReturn(mockServerConfiguration);
    when(IdentityCoreServiceComponent.getConfigurationContextService()).thenReturn(mockConfigurationContextService);
    when(mockConfigurationContextService.getServerConfigContext()).thenReturn(mockConfigurationContext);
    when(mockConfigurationContext.getAxisConfiguration()).thenReturn(mockAxisConfiguration);
    try {
        when(NetworkUtils.getLocalHostname()).thenReturn("localhost");
    } catch (SocketException e) {
        // Mock behaviour, hence ignored
    }

    System.setProperty(IdentityConstants.CarbonPlaceholders.CARBON_PORT_HTTP_PROPERTY, "9763");
    System.setProperty(IdentityConstants.CarbonPlaceholders.CARBON_PORT_HTTPS_PROPERTY, "9443");
}
 
Example #11
Source File: EntitlementServiceComponent.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Read the thrift hostname from identity.xml which overrides the hostName from carbon.xml on facilitating
 * identifying the host for thrift server .
 */
private String readThriftHostName() throws SocketException {

    String thriftHostName = IdentityUtil.getProperty(ThriftConfigConstants.PARAM_HOST_NAME);

    //if the thrift host name doesn't exist in config, load from carbon.xml
    if (thriftHostName != null) {
        return thriftHostName;
    } else {
        return NetworkUtils.getLocalHostname();
    }
}
 
Example #12
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the host name of the server.
 * @return Hostname
 */
public static String getHostName() {

    String hostName = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME);
    if (hostName == null) {
        try {
            hostName = NetworkUtils.getLocalHostname();
        } catch (SocketException e) {
            throw IdentityRuntimeException.error("Error while trying to read hostname.", e);
        }
    }
    return hostName;
}
 
Example #13
Source File: IdentityUtilTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    mockStatic(CarbonUtils.class);
    mockStatic(ServerConfiguration.class);
    mockStatic(NetworkUtils.class);
    mockStatic(IdentityCoreServiceComponent.class);
    mockStatic(IdentityConfigParser.class);
    mockStatic(CarbonUtils.class);
    mockStatic(IdentityTenantUtil.class);

    when(ServerConfiguration.getInstance()).thenReturn(mockServerConfiguration);
    when(IdentityCoreServiceComponent.getConfigurationContextService()).thenReturn(mockConfigurationContextService);
    when(mockConfigurationContextService.getServerConfigContext()).thenReturn(mockConfigurationContext);
    when(mockConfigurationContext.getAxisConfiguration()).thenReturn(mockAxisConfiguration);
    when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService);
    when(mockRealmService.getTenantManager()).thenReturn(mockTenantManager);
    when(CarbonUtils.getCarbonHome()).thenReturn("carbon.home");
    when(mockRequest.getRemoteAddr()).thenReturn("127.0.0.1");
    when(mockUserStoreManager.getRealmConfiguration()).thenReturn(mockRealmConfiguration);
    when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockRealmConfiguration);
    when(mockUserRealm.getUserStoreManager()).thenReturn(mockUserStoreManager);
    try {
        when(NetworkUtils.getLocalHostname()).thenReturn("localhost");
    } catch (SocketException e) {
        // Mock behaviour, hence ignored
    }

    System.setProperty(IdentityConstants.CarbonPlaceholders.CARBON_PORT_HTTP_PROPERTY, "9763");
    System.setProperty(IdentityConstants.CarbonPlaceholders.CARBON_PORT_HTTPS_PROPERTY, "9443");
}
 
Example #14
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get the host name of the server.
 *
 * @return Hostname
 */
public static String getHostName() {

    String hostName = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME);
    if (hostName == null) {
        try {
            hostName = NetworkUtils.getLocalHostname();
        } catch (SocketException e) {
            throw IdentityRuntimeException.error("Error while trying to read hostname.", e);
        }
    }
    return hostName;
}
 
Example #15
Source File: CarbonUIUtil.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns url to admin console.
 *
 * @param context Webapp context root of the Carbon webapp
 * @return The URL of the Admin Console
 */
public static String getAdminConsoleURL(String context) {
    // Hostname
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }

    // HTTPS port
    String mgtConsoleTransport = CarbonUtils.getManagementTransport();
    ConfigurationContextService configContextService = CarbonUIServiceComponent
        .getConfigurationContextService();
    int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
    int httpsProxyPort =
        CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                                          mgtConsoleTransport);
    // Context
    if ("/".equals(context)) {
        context = "";
    }

    String proxyContextPath = CarbonUIUtil.getProxyContextPath(false);

    String adminConsoleURL =  "https://" + hostName + ":" + (httpsProxyPort != -1 ? httpsProxyPort : httpsPort) +
            proxyContextPath + context + "/carbon/";

    if(log.isDebugEnabled()){
        log.debug("Generated admin console URL: " + adminConsoleURL);
    }

    return adminConsoleURL;
}
 
Example #16
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to return a URL with a proxy context path, a web context root and the tenant domain (If
 * required) when provided with a URL context.
 *
 * @param endpoint            Endpoint.
 * @param addProxyContextPath Add proxy context path to the URL.
 * @param addWebContextRoot   Add web context path to the URL.
 * @return Complete URL for the given URL context.
 * @throws IdentityRuntimeException If error occurred while constructing the URL
 */
public static String getServerURL(String endpoint, boolean addProxyContextPath, boolean addWebContextRoot)
        throws IdentityRuntimeException {

    String hostName = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME);

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

    String mgtTransport = CarbonUtils.getManagementTransport();
    AxisConfiguration axisConfiguration = IdentityCoreServiceComponent.getConfigurationContextService().
            getServerConfigContext().getAxisConfiguration();
    int mgtTransportPort = CarbonUtils.getTransportProxyPort(axisConfiguration, mgtTransport);
    if (mgtTransportPort <= 0) {
        mgtTransportPort = CarbonUtils.getTransportPort(axisConfiguration, mgtTransport);
    }
    if (hostName.endsWith("/")) {
        hostName = hostName.substring(0, hostName.length() - 1);
    }
    StringBuilder serverUrl = new StringBuilder(mgtTransport).append("://").append(hostName.toLowerCase());
    // If it's well known HTTPS port, skip adding port
    if (mgtTransportPort != IdentityCoreConstants.DEFAULT_HTTPS_PORT) {
        serverUrl.append(":").append(mgtTransportPort);
    }

    appendContextToUri(endpoint, addProxyContextPath, addWebContextRoot, serverUrl);
    return serverUrl.toString();
}
 
Example #17
Source File: EntitlementServiceComponent.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Read the thrift hostname from identity.xml which overrides the hostName from carbon.xml on facilitating
 * identifying the host for thrift server .
 */
private String readThriftHostName() throws SocketException {

    String thriftHostName = IdentityUtil.getProperty(ThriftConfigConstants.PARAM_HOST_NAME);

    //if the thrift host name doesn't exist in config, load from carbon.xml
    if (thriftHostName != null) {
        return thriftHostName;
    } else {
        return NetworkUtils.getLocalHostname();
    }
}
 
Example #18
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public static String getServerURL(String endpoint, boolean addProxyContextPath, boolean addWebContextRoot)
        throws IdentityRuntimeException {
    String hostName = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME);

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

    String mgtTransport = CarbonUtils.getManagementTransport();
    AxisConfiguration axisConfiguration = IdentityCoreServiceComponent.getConfigurationContextService().
            getServerConfigContext().getAxisConfiguration();
    int mgtTransportPort = CarbonUtils.getTransportProxyPort(axisConfiguration, mgtTransport);
    if (mgtTransportPort <= 0) {
        mgtTransportPort = CarbonUtils.getTransportPort(axisConfiguration, mgtTransport);
    }
    StringBuilder serverUrl = new StringBuilder(mgtTransport).append("://").append(hostName.toLowerCase());
    // If it's well known HTTPS port, skip adding port
    if (mgtTransportPort != IdentityCoreConstants.DEFAULT_HTTPS_PORT) {
        serverUrl.append(":").append(mgtTransportPort);
    }

    // If ProxyContextPath is defined then append it
    if(addProxyContextPath) {
        // If ProxyContextPath is defined then append it
        String proxyContextPath = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants
                .PROXY_CONTEXT_PATH);
        if (StringUtils.isNotBlank(proxyContextPath)) {
            if (!serverUrl.toString().endsWith("/") && proxyContextPath.trim().charAt(0) != '/') {
                serverUrl.append("/").append(proxyContextPath.trim());
            } else if (serverUrl.toString().endsWith("/") && proxyContextPath.trim().charAt(0) == '/') {
                serverUrl.append(proxyContextPath.trim().substring(1));
            } else {
                serverUrl.append(proxyContextPath.trim());
            }
        }
    }

    // If webContextRoot is defined then append it
    if (addWebContextRoot) {
        String webContextRoot = ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants
                .WEB_CONTEXT_ROOT);
        if (StringUtils.isNotBlank(webContextRoot)) {
            if (!serverUrl.toString().endsWith("/") && webContextRoot.trim().charAt(0) != '/') {
                serverUrl.append("/").append(webContextRoot.trim());
            } else if (serverUrl.toString().endsWith("/") && webContextRoot.trim().charAt(0) == '/') {
                serverUrl.append(webContextRoot.trim().substring(1));
            } else {
                serverUrl.append(webContextRoot.trim());
            }
        }
    }
    if (StringUtils.isNotBlank(endpoint)) {
        if (!serverUrl.toString().endsWith("/") && endpoint.trim().charAt(0) != '/') {
            serverUrl.append("/").append(endpoint.trim());
        } else if (serverUrl.toString().endsWith("/") && endpoint.trim().charAt(0) == '/') {
            serverUrl.append(endpoint.trim().substring(1));
        } else {
            serverUrl.append(endpoint.trim());
        }
    }
    if (serverUrl.toString().endsWith("/")) {
        serverUrl.deleteCharAt(serverUrl.length() - 1);
    }
    return serverUrl.toString();
}
 
Example #19
Source File: AbstractClient.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
protected String getBackendServerURLHTTP() throws SocketException {
    String contextRoot = ReportingTemplateComponent.getConfigurationContextService().getServerConfigContext().getContextRoot();
    return "http://" + NetworkUtils.getLocalHostname() + ":" +
            CarbonUtils.getTransportPort(ReportingTemplateComponent.getConfigurationContextService(), "http") + contextRoot;

}
 
Example #20
Source File: AbstractClient.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
protected String getBackendServerURLHTTPS() throws SocketException {
    String contextRoot = ReportingTemplateComponent.getConfigurationContextService().getServerConfigContext().getContextRoot();
    return "https://" + NetworkUtils.getLocalHostname() + ":" +
            CarbonUtils.getTransportPort(ReportingTemplateComponent.getConfigurationContextService(), "https") + contextRoot;

}
 
Example #21
Source File: SystemStatistics.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
public void update(AxisConfiguration axisConfig) throws AxisFault {

        int tenantId =  PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        Parameter systemStartTime =
                axisConfig.getParameter(CarbonConstants.SERVER_START_TIME);
        long startTime = 0;
        if (systemStartTime != null) {
            startTime = Long.parseLong((String) systemStartTime.getValue());
        }
        Date stTime = new Date(startTime);

        // only super admin can view serverStartTime and systemUpTime
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            serverStartTime = dateFormatter.format(stTime);
            systemUpTime = (getTime((System.currentTimeMillis() - startTime) / 1000));
        }
        try {
            totalRequestCount = statService.getTotalSystemRequestCount(axisConfig);
            totalResponseCount = statService.getSystemResponseCount(axisConfig);
            totalFaultCount = statService.getSystemFaultCount(axisConfig);
            avgResponseTime = statService.getAvgSystemResponseTime(axisConfig);
            maxResponseTime = statService.getMaxSystemResponseTime(axisConfig);
            minResponseTime = statService.getMinSystemResponseTime(axisConfig);

        } catch (Exception e) {
            throw AxisFault.makeFault(e);
        }

        Runtime runtime = Runtime.getRuntime();

        // only super admin can view usedMemory and totalMemory
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            usedMemory = formatMemoryValue(runtime.totalMemory() - runtime.freeMemory());
            totalMemory = formatMemoryValue(runtime.totalMemory());
        }
        wso2wsasVersion = ServerConfiguration.getInstance().getFirstProperty("Version");

        int activeServices = 0;
        for (Iterator services = axisConfig.getServices().values().iterator();
             services.hasNext(); ) {
            AxisService axisService = (AxisService) services.next();
            AxisServiceGroup asGroup = (AxisServiceGroup) axisService.getParent();
            if (axisService.isActive() &&
                !axisService.isClientSide() &&
                !SystemFilter.isFilteredOutService(asGroup)) {
                activeServices++;
            }
        }

        this.services = activeServices;
        try {
            // only susper admin is allow to view serverName.
            if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
                serverName = NetworkUtils.getLocalHostname();
            }
        } catch (SocketException ignored) {
        }
    }
 
Example #22
Source File: CarbonUIUtil.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns url to admin console. eg: https://192.168.1.201:9443/wso2/carbon
 *
 * @param request The HTTPServletRequest
 * @return The URL of the Admin Console
 */
public static String getAdminConsoleURL(HttpServletRequest request) {

    // Hostname
    String hostName = "localhost";
    try {
        hostName = NetworkUtils.getMgtHostName();
    } catch (Exception ignored) {
    }

    // HTTPS port
    String mgtConsoleTransport = CarbonUtils.getManagementTransport();
    ConfigurationContextService configContextService = CarbonUIServiceComponent
        .getConfigurationContextService();
    int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
    int httpsProxyPort =
        CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
                                          mgtConsoleTransport);

    // Context
    String context = request.getContextPath();
    if ("/".equals(context)) {
        context = "";
    }

    String proxyContextPath = CarbonUIUtil.getProxyContextPath(false);

    if (httpsPort == -1) {
        return null;
    }
    
    String adminConsoleURL = null;
    String enableHTTPAdminConsole = CarbonUIServiceComponent.getServerConfiguration()
            .getFirstProperty(CarbonConstants.ENABLE_HTTP_ADMIN_CONSOLE);

    if (enableHTTPAdminConsole != null
            && "true".equalsIgnoreCase(enableHTTPAdminConsole.trim())) {
        int httpPort = CarbonUtils.getTransportPort(
                CarbonUIServiceComponent.getConfigurationContextService(), "http");
        adminConsoleURL = "http://" + hostName + ":" + httpPort + proxyContextPath + context + "/carbon/";
    } else {
        adminConsoleURL = "https://" + hostName + ":"
                + (httpsProxyPort != -1 ? httpsProxyPort : httpsPort) + proxyContextPath + context + "/carbon/";
    }

    if(log.isDebugEnabled()){
        log.debug("Generated admin console URL: " + adminConsoleURL);
    }
    return adminConsoleURL;
}