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;
}
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;
}
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");
}
}
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;
}
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()));
}
}
Aggregations