Search in sources :

Example 46 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class APIUtil method replaceSystemProperty.

/**
 * Resolves system properties and replaces in given in text
 *
 * @param text
 * @return System properties resolved text
 */
public static String replaceSystemProperty(String text) {
    int indexOfStartingChars = -1;
    int indexOfClosingBrace;
    // and are assumed to be System properties
    while (indexOfStartingChars < text.indexOf("${") && (indexOfStartingChars = text.indexOf("${")) != -1 && (indexOfClosingBrace = text.indexOf('}')) != -1) {
        // Is a
        // property
        // used?
        String sysProp = text.substring(indexOfStartingChars + 2, indexOfClosingBrace);
        String propValue = System.getProperty(sysProp);
        if (propValue == null) {
            if ("carbon.context".equals(sysProp)) {
                propValue = ServiceReferenceHolder.getContextService().getServerConfigContext().getContextRoot();
            } else if ("admin.username".equals(sysProp) || "admin.password".equals(sysProp)) {
                try {
                    RealmConfiguration realmConfig = new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
                    if ("admin.username".equals(sysProp)) {
                        propValue = realmConfig.getAdminUserName();
                    } else {
                        propValue = realmConfig.getAdminPassword();
                    }
                } catch (UserStoreException e) {
                    // Can't throw an exception because the server is
                    // starting and can't be halted.
                    log.error("Unable to build the Realm Configuration", e);
                    return null;
                }
            }
        }
        // Derive original text value with resolved system property value
        if (propValue != null) {
            text = text.substring(0, indexOfStartingChars) + propValue + text.substring(indexOfClosingBrace + 1);
        }
        if ("carbon.home".equals(sysProp) && propValue != null && ".".equals(propValue)) {
            text = new File(".").getAbsolutePath() + File.separator + text;
        }
    }
    return text;
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) RealmConfigXMLProcessor(org.wso2.carbon.user.core.config.RealmConfigXMLProcessor) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 47 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class RecommenderDetailsExtractor method getRecommendations.

public String getRecommendations(String userName, String tenantDomain) {
    String recommendationEndpointURL = recommendationEnvironment.getRecommendationServerURL() + APIConstants.RECOMMENDATIONS_GET_RESOURCE;
    AccessTokenGenerator accessTokenGenerator = ServiceReferenceHolder.getInstance().getAccessTokenGenerator();
    try {
        String userID = apiMgtDAO.getUserID(userName);
        URL serverURL = new URL(recommendationEndpointURL);
        int serverPort = serverURL.getPort();
        String serverProtocol = serverURL.getProtocol();
        HttpGet method = new HttpGet(recommendationEndpointURL);
        HttpClient httpClient = APIUtil.getHttpClient(serverPort, serverProtocol);
        if (recommendationEnvironment.getOauthURL() != null) {
            String accessToken = accessTokenGenerator.getAccessToken();
            method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BEARER + accessToken);
        } else {
            byte[] credentials = org.apache.commons.codec.binary.Base64.encodeBase64((recommendationEnvironment.getUserName() + ":" + recommendationEnvironment.getPassword()).getBytes(StandardCharsets.UTF_8));
            method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
        }
        method.setHeader(APIConstants.RECOMMENDATIONS_USER_HEADER, userID);
        method.setHeader(APIConstants.RECOMMENDATIONS_ACCOUNT_HEADER, tenantDomain);
        HttpResponse httpResponse = httpClient.execute(method);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            log.info("Recommendations received for the user " + userName + " from recommendations server");
            String contentString = EntityUtils.toString(httpResponse.getEntity());
            if (log.isDebugEnabled()) {
                log.debug("Recommendations received for user " + userName + " is " + contentString);
            }
            return contentString;
        } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED && accessTokenGenerator != null) {
            log.warn("Error getting recommendations from server. Invalid credentials used");
            accessTokenGenerator.removeInvalidToken(new String[] { APIConstants.OAUTH2_DEFAULT_SCOPE });
        } else {
            log.warn("Error getting recommendations from server. Server responded with " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        log.error("Connection failure for the recommendation engine", e);
    } catch (APIManagementException e) {
        log.error("Error while getting recommendations for user " + userName, e);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 48 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class RecommenderDetailsExtractor method publishAPIDetails.

@Override
public void publishAPIDetails(API api, String tenantDomain) throws IOException {
    String apiName = api.getId().getApiName();
    String apiStatus = api.getStatus();
    String apiId = api.getUUID();
    if (apiStatus == null) {
        apiStatus = APIConstants.DELETED_STATUS;
    }
    if (apiStatus.equals(APIConstants.PUBLISHED_STATUS) && APIConstants.ADD_API.equals(publishingDetailType)) {
        String apiDescription = api.getDescription();
        String apiContext = api.getContext();
        String apiTags = api.getTags().toString();
        Set<URITemplate> uriTemplates = api.getUriTemplates();
        JSONObject swaggerDef = null;
        if (api.getSwaggerDefinition() != null) {
            swaggerDef = new JSONObject(api.getSwaggerDefinition());
        }
        JSONArray resourceArray = new JSONArray();
        JSONObject resourceObj;
        for (URITemplate uriTemplate : uriTemplates) {
            resourceObj = new JSONObject();
            String resource = uriTemplate.getUriTemplate();
            String resourceMethod = uriTemplate.getHTTPVerb();
            resourceObj.put("resource", resource);
            if (swaggerDef != null) {
                String summary = getDescriptionFromSwagger(swaggerDef, resource, resourceMethod, "summary");
                String description = getDescriptionFromSwagger(swaggerDef, resource, resourceMethod, "description");
                resourceObj.put("summary", summary);
                resourceObj.put("description", description);
            }
            resourceArray.put(resourceObj);
        }
        JSONObject obj = new JSONObject();
        obj.put("api_id", apiId);
        obj.put("api_name", apiName);
        obj.put("description", apiDescription);
        obj.put("context", apiContext);
        obj.put("tenant", tenantDomain);
        obj.put("tags", apiTags);
        obj.put("resources", resourceArray);
        JSONObject payload = new JSONObject();
        payload.put("action", APIConstants.ADD_API);
        payload.put("payload", obj);
        publishEvent(payload.toString());
        log.info("Add API event for " + apiName + " API was published to the recommendation server");
    } else {
        JSONObject obj = new JSONObject();
        obj.put("api_name", apiName);
        obj.put("tenant", tenantDomain);
        JSONObject payload = new JSONObject();
        payload.put(APIConstants.ACTION_STRING, APIConstants.DELETE_API);
        payload.put(APIConstants.PAYLOAD_STRING, obj);
        publishEvent(payload.toString());
        log.info("Delete API event for " + apiName + " API was published to the recommendation server");
    }
}
Also used : JSONObject(org.json.JSONObject) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) JSONArray(org.json.JSONArray)

Example 49 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method addAPIClientCertificate.

@Override
public Response addAPIClientCertificate(String apiId, InputStream certificateInputStream, Attachment certificateDetail, String alias, String tier, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(apiId)) {
            RestApiUtil.handleBadRequest("The alias and/ or apiId should not be empty", log);
        }
        if (StringUtils.isBlank(fileName)) {
            RestApiUtil.handleBadRequest("Certificate addition failed. Proper Certificate file should be provided", log);
        }
        // validate if api exists
        validateAPIExistence(apiId);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
        int responseCode = apiProvider.addClientCertificate(userName, api.getId(), base64EncodedCert, alias, tier, organization);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Add certificate operation response code : %d", responseCode));
        }
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO certificateDTO = new ClientCertMetadataDTO();
            certificateDTO.setAlias(alias);
            certificateDTO.setApiId(apiId);
            certificateDTO.setTier(tier);
            URI createdCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.created(createdCertUri).entity(certificateDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Internal server error while adding the client certificate to " + "API " + apiId, log);
        } else if (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceAlreadyExistsError("The alias '" + alias + "' already exists in the trust store.", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while adding the certificate to the API " + apiId + ". " + "Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("APIManagement exception while adding the certificate to the API " + apiId + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("IOException while generating the encoded certificate for the API " + apiId, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 50 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class APIMgtGoogleAnalyticsTrackingHandler method trackPageView.

/**
 * Track a page view, updates all the cookies and campaign tracker, makes a
 * server side request to Google Analytics and writes the transparent gif
 * byte data to the response.
 *
 * @throws Exception
 */
private void trackPageView(MessageContext msgCtx) throws Exception {
    @SuppressWarnings("rawtypes") Map headers = (Map) ((Axis2MessageContext) msgCtx).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String host = (String) headers.get(HttpHeaders.HOST);
    String domainName = host;
    if (host != null && host.indexOf(":") != -1) {
        domainName = host.substring(0, host.indexOf(":"));
    }
    if (isEmpty(domainName)) {
        domainName = "";
    }
    // Get client IP
    String xForwardedFor = (String) headers.get(org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.X_FORWARDED_FOR_HEADER);
    String userIP;
    if (xForwardedFor == null || xForwardedFor.isEmpty()) {
        userIP = (String) ((Axis2MessageContext) msgCtx).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);
    } else {
        userIP = xForwardedFor.split(",")[0];
    }
    String path = (String) msgCtx.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
    String documentPath = path;
    if (isEmpty(documentPath)) {
        documentPath = "";
    }
    String account = config.googleAnalyticsTrackingID;
    String userAgent = (String) headers.get(HttpHeaders.USER_AGENT);
    if (isEmpty(userAgent)) {
        userAgent = "";
    }
    String visitorId = getVisitorId(account, userAgent, msgCtx);
    /* Set the visitorId in MessageContext */
    msgCtx.setProperty(COOKIE_NAME, visitorId);
    String httpMethod = (String) ((Axis2MessageContext) msgCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    GoogleAnalyticsData data = new GoogleAnalyticsData.DataBuilder(account, GOOGLE_ANALYTICS_TRACKER_VERSION, visitorId, GoogleAnalyticsConstants.HIT_TYPE_PAGEVIEW).setDocumentPath(documentPath).setDocumentHostName(domainName).setDocumentTitle(httpMethod).setSessionControl("end").setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId()).setIPOverride(userIP).build();
    String payload = GoogleAnalyticsDataPublisher.buildPayloadString(data);
    if (log.isDebugEnabled()) {
        log.debug("Publishing https GET from gateway to Google analytics" + " with ID: " + msgCtx.getMessageID() + " started at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
    GoogleAnalyticsDataPublisher.publishGET(payload, userAgent, false);
    if (log.isDebugEnabled()) {
        log.debug("Publishing https GET from gateway to Google analytics" + " with ID: " + msgCtx.getMessageID() + " ended at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
}
Also used : GoogleAnalyticsData(org.wso2.carbon.ganalytics.publisher.GoogleAnalyticsData) HashMap(java.util.HashMap) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 IOException (java.io.IOException)19 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)14 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 File (java.io.File)8 JSONObject (org.json.simple.JSONObject)7 MalformedURLException (java.net.MalformedURLException)6 URL (java.net.URL)6 OMElement (org.apache.axiom.om.OMElement)6 JSONObject (org.json.JSONObject)6 URI (java.net.URI)5 URISyntaxException (java.net.URISyntaxException)5 Test (org.testng.annotations.Test)5 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)5 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)5 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)5 Connection (java.sql.Connection)4 SQLException (java.sql.SQLException)4 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4