Search in sources :

Example 51 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultSiddhiAppForAPILevelDefaultThrottlePolicy.

public static String createDefaultSiddhiAppForAPILevelDefaultThrottlePolicy() {
    APIPolicy apiPolicy = createDefaultAPIPolicy();
    String siddhiApp = "\n@App:name('resource_" + apiPolicy.getPolicyName() + "_default')" + "\n@App:description('ExecutionPlan for resource_" + apiPolicy.getPolicyName() + "_default')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))" + "\ndefine stream RequestStream (messageID string, appKey string," + " appTier string, subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string," + " resourceTier string, userId string,  apiContext string, apiVersion string, appTenant string," + " apiTenant string," + " appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text')," + "\nfactory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672'," + " destination='TEST.FOO', connection.factory.type='topic'," + "\nconnection.factory.jndi.name='TopicConnectionFactory')" + "\ndefine stream GlobalThrottleStream (throttleKey string, isThrottled bool," + " expiryTimeStamp long);\n" + "\nFROM RequestStream" + "\nSELECT messageID, (resourceTier == 'SampleAPIPolicy' AND " + "NOT(((3232238595l<=cast(map:get(propertiesMap,'ip'),'Long')" + " AND 3232258067l>=cast(map:get(propertiesMap,'ip'),'Long')) AND " + "(cast(map:get(propertiesMap,'ip'),'Long')==2066353720l)) " + "OR ((regex:find('Chrome',cast(map:get(propertiesMap,'Browser'),'string')))" + " AND (regex:find('attributed'," + "cast(map:get(propertiesMap,'/path/path2'),'string')))" + " AND (cast(map:get(propertiesMap,'Location'),'string')=='Colombo'))))" + " AS isEligible, resourceKey AS throttleKey, propertiesMap" + "\nINSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(1000 s, 0)" + "\nselect throttleKey, (count(messageID) >= 10000) as isThrottled," + " expiryTimeStamp group by throttleKey" + "\nINSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + "\nselect *" + "\ninsert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 52 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdDocumentsPost.

/**
 * Adds new document to an API
 *
 * @param apiId             UUID of API
 * @param body              DTO object including the document's meta information
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return newly added document meta info object
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdDocumentsPost(String apiId, DocumentDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    try {
        String username = RestApiUtil.getLoggedInUsername(request);
        APIPublisher apiProvider = RestAPIPublisherUtil.getApiPublisher(username);
        DocumentInfo documentation = MappingUtil.toDocumentInfo(body);
        if (body.getType() == DocumentDTO.TypeEnum.OTHER && StringUtils.isBlank(body.getOtherTypeName())) {
            // check otherTypeName for not null if doc type is OTHER
            RestApiUtil.handleBadRequest("otherTypeName cannot be empty if type is OTHER.", log);
        }
        String sourceUrl = body.getSourceUrl();
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (StringUtils.isBlank(sourceUrl) || !RestApiUtil.isURL(sourceUrl))) {
            RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
        }
        // this will fail if user does not have access to the API or the API does not exist
        String docid = apiProvider.addDocumentationInfo(apiId, documentation);
        documentation = apiProvider.getDocumentationSummary(docid);
        DocumentDTO newDocumentDTO = MappingUtil.toDocumentDTO(documentation);
        // Add initial inline content as empty String, if the Document type is INLINE
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.INLINE) {
            apiProvider.addDocumentationContent(docid, "");
            if (log.isDebugEnabled()) {
                log.debug("The updated source type of the document " + body.getName() + " is: " + body.getSourceType());
            }
        }
        return Response.status(Response.Status.CREATED).entity(newDocumentDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while create  document for api " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.DocumentDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 53 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdScopesPost.

@Override
public Response apisApiIdScopesPost(String apiId, ScopeDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    try {
        String username = RestApiUtil.getLoggedInUsername(request);
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        KeyMgtConfigurations keyManagerConfiguration = APIMConfigurationService.getInstance().getApimConfigurations().getKeyManagerConfigs();
        if (body.getBindings() != null && StringUtils.isNotEmpty(body.getBindings().getType())) {
            if (!keyManagerConfiguration.getScopeBindingType().equalsIgnoreCase(body.getBindings().getType())) {
                String message = "binding type not valid";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(message, 900313L, message);
                return Response.status(Response.Status.PRECONDITION_FAILED).entity(errorDTO).build();
            }
        }
        Scope scope = MappingUtil.toScope(body);
        apiPublisher.addScopeToTheApi(apiId, scope);
        URI location = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + "/scopes/" + scope.getName());
        return Response.created(location).entity(body).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while creating scope" + body.getName();
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        paramList.put(APIMgtConstants.ExceptionsConstants.SCOPE_NAME, body.getName());
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving source URI location of " + body.getName();
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : KeyMgtConfigurations(org.wso2.carbon.apimgt.core.configuration.models.KeyMgtConfigurations) Scope(org.wso2.carbon.apimgt.core.models.Scope) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 54 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdDocumentsDocumentIdContentPost.

/**
 * Uploads a document's content and attach to particular document
 *
 * @param apiId             UUID of API
 * @param documentId        UUID of the document
 * @param fileInputStream   file content stream
 * @param fileDetail        meta infomation about the file
 * @param inlineContent     inline documentation content
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return updated document meta information
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdDocumentsDocumentIdContentPost(String apiId, String documentId, InputStream fileInputStream, FileInfo fileDetail, String inlineContent, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    try {
        String username = RestApiUtil.getLoggedInUsername(request);
        APIPublisher apiProvider = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        if (fileInputStream != null && inlineContent != null) {
            String msg = "Only one of 'file' and 'inlineContent' should be specified";
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
            log.error(msg);
            return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
        }
        // retrieves the document and send 404 if not found
        DocumentInfo documentation = apiProvider.getDocumentationSummary(documentId);
        if (documentation == null) {
            String msg = "Documentation not found " + documentId;
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
            log.error(msg);
            return Response.status(Response.Status.NOT_FOUND).entity(errorDTO).build();
        }
        // add content depending on the availability of either input stream or inline content
        if (fileInputStream != null) {
            if (!documentation.getSourceType().equals(DocumentInfo.SourceType.FILE)) {
                String msg = "Source type of document " + documentId + " is not FILE";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
                log.error(msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
            apiProvider.uploadDocumentationFile(documentId, fileInputStream, fileDetail.getContentType());
        } else if (inlineContent != null) {
            if (!documentation.getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
                String msg = "Source type of document " + documentId + " is not INLINE";
                log.error(msg);
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900976L, msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
            apiProvider.addDocumentationContent(documentId, inlineContent);
        } else {
            String msg = "Either 'file' or 'inlineContent' should be specified";
            log.error(msg);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900976L, msg);
            return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
        }
        String newFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, null, null, request);
        return Response.status(Response.Status.CREATED).header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding content to document" + documentId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        paramList.put(APIMgtConstants.ExceptionsConstants.DOC_ID, documentId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 55 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project carbon-apimgt by wso2.

the class AbstractAPIManagerTestCase method testGetDocumentationContentInline.

@Test(description = "Getting Documentation content when source type is INLINE")
public void testGetDocumentationContentInline() throws APIManagementException, IOException {
    ApiDAO apiDAO = mock(ApiDAO.class);
    AbstractAPIManager apiPublisher = getApiPublisherImpl(apiDAO);
    DocumentInfo documentInfo = SampleTestObjectCreator.createDefaultDocumentationInfo();
    when(apiDAO.getDocumentInfo(DOC_ID)).thenReturn(documentInfo);
    when(apiDAO.getDocumentInlineContent(DOC_ID)).thenReturn(SampleTestObjectCreator.createDefaultInlineDocumentationContent());
    apiPublisher.getDocumentationContent(DOC_ID);
    verify(apiDAO, times(1)).getDocumentInlineContent(DOC_ID);
}
Also used : ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)22 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)15 ArrayList (java.util.ArrayList)11 CompilerOptions (org.wso2.ballerinalang.compiler.util.CompilerOptions)11 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)11 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)11 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)8 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)8 ParseTree (org.antlr.v4.runtime.tree.ParseTree)8 OMElement (org.apache.axiom.om.OMElement)8 TopLevelNode (org.ballerinalang.model.tree.TopLevelNode)8 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)8 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)8 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)8 Event (org.wso2.siddhi.core.event.Event)8 HashMap (java.util.HashMap)7 List (java.util.List)7 Compiler (org.wso2.ballerinalang.compiler.Compiler)7 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 SiddhiQLBaseVisitorImpl (org.wso2.siddhi.query.compiler.internal.SiddhiQLBaseVisitorImpl)6