Search in sources :

Example 1 with Request

use of org.wso2.msf4j.Request in project siddhi by wso2.

the class SiddhiDebuggerClient method start.

/**
 * Start the {@link SiddhiDebuggerClient} and configure the breakpoints.
 *
 * @param siddhiApp the Siddhi query
 * @param input         the user input as a whole text
 */
public void start(final String siddhiApp, String input) {
    SiddhiManager siddhiManager = new SiddhiManager();
    info("Deploying the siddhi app");
    final SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);
    // Add callbacks for all the streams
    final Set<String> streamNames = SiddhiCompiler.parse(siddhiApp).getStreamDefinitionMap().keySet();
    for (String streamName : streamNames) {
        final String stream = streamName;
        siddhiAppRuntime.addCallback(stream, new StreamCallback() {

            @Override
            public void receive(Event[] events) {
                info("@Receive: Stream: " + stream + ", Event: " + Arrays.deepToString(events));
            }
        });
    }
    SiddhiDebugger siddhiDebugger = siddhiAppRuntime.debug();
    final InputFeeder inputFeeder = new InputFeeder(siddhiAppRuntime, input);
    System.out.println("Configure the breakpoints.\nYou can use the following commands:\n - " + ADD_BREAKPOINT + "<query name>:<IN/OUT>\n - " + REMOVE_BREAKPOINT + "<query name>:<IN/OUT>\n - " + START + "\n - " + STOP);
    printNextLine();
    final Scanner scanner = new Scanner(System.in, "UTF-8");
    while (scanner.hasNextLine()) {
        String userInput = scanner.nextLine().trim();
        String command = userInput.toLowerCase();
        if (command.startsWith(ADD_BREAKPOINT)) {
            if (!command.contains(QUERY_DELIMITER)) {
                error("Invalid add query. The query must be " + ADD_BREAKPOINT + "<query " + "name>:<IN/OUT>. Please try again");
                printNextLine();
                continue;
            }
            String[] components = userInput.substring(ADD_BREAKPOINT.length(), userInput.length()).split(QUERY_DELIMITER);
            String queryName = components[0];
            String terminal = components[1].toLowerCase();
            if (IN.equals(terminal)) {
                siddhiDebugger.acquireBreakPoint(queryName, SiddhiDebugger.QueryTerminal.IN);
                info("Added a breakpoint at the IN terminal of " + queryName);
                printNextLine();
            } else if (OUT.equals(terminal)) {
                siddhiDebugger.acquireBreakPoint(queryName, SiddhiDebugger.QueryTerminal.OUT);
                info("Added a breakpoint at the OUT terminal of " + queryName);
                printNextLine();
            } else {
                error("The terminal must be either IN or OUT but found: " + terminal.toUpperCase() + ". Please try again");
                printNextLine();
            }
        } else if (command.startsWith(REMOVE_BREAKPOINT)) {
            if (!command.contains(QUERY_DELIMITER)) {
                error("Invalid add query. The query must be " + REMOVE_BREAKPOINT + "<query " + "name>:<IN/OUT>. Please try again");
                printNextLine();
                continue;
            }
            String[] components = command.substring(ADD_BREAKPOINT.length(), command.length()).split(QUERY_DELIMITER);
            String queryName = components[0];
            String terminal = components[1];
            if (IN.equals(terminal)) {
                siddhiDebugger.releaseBreakPoint(queryName, SiddhiDebugger.QueryTerminal.IN);
                info("Removed the breakpoint at the IN terminal of " + queryName);
                printNextLine();
            } else if (OUT.equals(terminal)) {
                siddhiDebugger.releaseBreakPoint(queryName, SiddhiDebugger.QueryTerminal.OUT);
                info("Removed the breakpoint at the OUT terminal of " + queryName);
                printNextLine();
            } else {
                error("The terminal must be either IN or OUT but found: " + terminal.toUpperCase());
                printNextLine();
            }
        } else if (STOP.equals(command)) {
            inputFeeder.stop();
            siddhiAppRuntime.shutdown();
            break;
        } else if (START.equals(command)) {
            inputFeeder.start();
            info("Siddhi Debugger starts sending input to Siddhi");
            System.out.println("You can use the following commands:\n - " + NEXT + "\n - " + PLAY + "\n - " + STATE + ":<query name>\n - " + STOP);
            break;
        } else {
            error("Invalid command: " + command);
            printNextLine();
        }
    }
    siddhiDebugger.setDebuggerCallback(new SiddhiDebuggerCallback() {

        @Override
        public void debugEvent(ComplexEvent event, String queryName, SiddhiDebugger.QueryTerminal queryTerminal, SiddhiDebugger debugger) {
            info("@Debug: Query: " + queryName + ", Terminal: " + queryTerminal + ", Event: " + event);
            printNextLine();
            while (scanner.hasNextLine()) {
                String command = scanner.nextLine().trim().toLowerCase();
                if (STOP.equals(command)) {
                    debugger.releaseAllBreakPoints();
                    debugger.play();
                    inputFeeder.stop();
                    siddhiAppRuntime.shutdown();
                    break;
                } else if (NEXT.equals(command)) {
                    debugger.next();
                    break;
                } else if (PLAY.equals(command)) {
                    debugger.play();
                    break;
                } else if (command.startsWith(STATE)) {
                    if (!command.contains(QUERY_DELIMITER)) {
                        error("Invalid get state request. The query must be " + STATE + ":<query " + "name>. Please try again");
                        printNextLine();
                        continue;
                    }
                    String[] components = command.split(QUERY_DELIMITER);
                    String requestQueryName = components[1];
                    Map<String, Object> state = debugger.getQueryState(requestQueryName.trim());
                    System.out.println("Query '" + requestQueryName + "' state : ");
                    for (Map.Entry<String, Object> entry : state.entrySet()) {
                        System.out.println("    '" + entry.getKey() + "' : " + entry.getValue());
                    }
                    printNextLine();
                    continue;
                } else {
                    error("Invalid command: " + command);
                    printNextLine();
                }
            }
        }
    });
    inputFeeder.join();
    if (inputFeeder.isRunning()) {
        info("Input feeder has sopped sending all inputs. If you want to stop the execution, use " + "the STOP command");
        printNextLine();
        while (scanner.hasNextLine()) {
            String command = scanner.nextLine().trim().toLowerCase();
            if (STOP.equals(command)) {
                inputFeeder.stop();
                siddhiAppRuntime.shutdown();
                break;
            } else {
                error("Invalid command: " + command);
                printNextLine();
            }
        }
    }
    scanner.close();
    info("Siddhi Debugger is stopped successfully");
}
Also used : Scanner(java.util.Scanner) StreamCallback(org.wso2.siddhi.core.stream.output.StreamCallback) ComplexEvent(org.wso2.siddhi.core.event.ComplexEvent) SiddhiAppRuntime(org.wso2.siddhi.core.SiddhiAppRuntime) ComplexEvent(org.wso2.siddhi.core.event.ComplexEvent) Event(org.wso2.siddhi.core.event.Event) Map(java.util.Map) SiddhiManager(org.wso2.siddhi.core.SiddhiManager)

Example 2 with Request

use of org.wso2.msf4j.Request in project siddhi by wso2.

the class TestSiddhiLatency method isThrottled.

public static boolean isThrottled(Object[] throttleRequest) {
    log.info("Start latency =" + (System.currentTimeMillis() - (Long) throttleRequest[7]));
    if (ruleCount.get() != 0) {
        String uniqueKey = (String) throttleRequest[0];
        ResultContainer result = new ResultContainer(ruleCount.get());
        resultMap.put(uniqueKey.toString(), result);
        for (InputHandler inputHandler : requestStreamInputHandlerMap.values()) {
            try {
                inputHandler.send(Arrays.copyOf(throttleRequest, throttleRequest.length));
            } catch (InterruptedException e) {
                // interrupt current thread so that interrupt can propagate
                Thread.currentThread().interrupt();
                log.error(e.getMessage(), e);
            }
        }
        log.info("sending latency =" + (System.currentTimeMillis() - (Long) throttleRequest[7]));
        // Blocked call to return synchronous result
        boolean isThrottled = false;
        try {
            isThrottled = result.isThrottled();
            log.info("After result latency =" + (System.currentTimeMillis() - (Long) throttleRequest[7]));
            if (log.isDebugEnabled()) {
                log.debug("Throttling status for request to API " + throttleRequest[2] + " is " + isThrottled);
            }
        } catch (InterruptedException e) {
            // interrupt current thread so that interrupt can propagate
            Thread.currentThread().interrupt();
        // log.error(e.getMessage(), e);
        }
        if (!isThrottled) {
            // Converting properties map into json compatible String
            if (throttleRequest[6] != null) {
                throttleRequest[6] = (throttleRequest[6]).toString();
            }
        // Only send served throttleRequest to global throttler
        // sendToGlobalThrottler(throttleRequest);
        }
        resultMap.remove(uniqueKey);
        log.info("Return latency =" + (System.currentTimeMillis() - (Long) throttleRequest[7]));
        return isThrottled;
    } else {
        return false;
    }
}
Also used : InputHandler(org.wso2.siddhi.core.stream.input.InputHandler)

Example 3 with Request

use of org.wso2.msf4j.Request in project siddhi by wso2.

the class SiddhiApiServiceImpl method siddhiArtifactUndeploySiddhiAppGet.

@Override
public Response siddhiArtifactUndeploySiddhiAppGet(String siddhiAppName) throws NotFoundException {
    String jsonString = new Gson().toString();
    if (siddhiAppName != null) {
        if (siddhiAppRunTimeMap.containsKey(siddhiAppName)) {
            siddhiAppRunTimeMap.remove(siddhiAppName);
            siddhiAppConfigurationMap.remove(siddhiAppName);
            siddhiAppSpecificInputHandlerMap.remove(siddhiAppName);
            jsonString = new Gson().toJson(new ApiResponseMessage(ApiResponseMessage.OK, "Siddhi app removed successfully"));
        } else {
            jsonString = new Gson().toJson(new ApiResponseMessage(ApiResponseMessage.ERROR, "There is no siddhi app exist " + "with provided name : " + siddhiAppName));
        }
    } else {
        jsonString = new Gson().toJson(new ApiResponseMessage(ApiResponseMessage.ERROR, "nvalid Request"));
    }
    return Response.ok().entity(jsonString).build();
}
Also used : ApiResponseMessage(org.wso2.siddhi.service.api.ApiResponseMessage) Gson(com.google.gson.Gson)

Example 4 with Request

use of org.wso2.msf4j.Request in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method getScopeOfResourcePath.

@Override
public String getScopeOfResourcePath(String resourceConfigsJSON, Request request, ServiceMethodInfo serviceMethodInfo) throws APIManagementException {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(resourceConfigsJSON);
    String basepath = swagger.getBasePath();
    String verb = (String) request.getProperty(APIMgtConstants.HTTP_METHOD);
    // TODO change to this if msf4j2.3.0-m2 or higher
    // Method resourceMethod = (Method) request.getProperty("method");
    Method resourceMethod = serviceMethodInfo.getMethod();
    if (resourceMethod == null || verb == null) {
        String message = "Could not read required properties from HTTP Request. HTTP_METHOD=" + verb + " resourceTemplate=" + resourceMethod;
        log.error(message);
        throw new APIManagementException(message, ExceptionCodes.SWAGGER_URL_MALFORMED);
    }
    String apiPrefix = resourceMethod.getDeclaringClass().getAnnotation(javax.ws.rs.ApplicationPath.class).value();
    String pathTemplate = "";
    if (resourceMethod.getAnnotation(javax.ws.rs.Path.class) != null) {
        pathTemplate = resourceMethod.getAnnotation(javax.ws.rs.Path.class).value();
    }
    String nameSpace = getNamespaceFromBasePath(basepath);
    if (basepath.contains(APIMgtConstants.APPType.PUBLISHER)) {
        nameSpace = APIMgtConstants.NAMESPACE_PUBLISHER_API;
    } else if (basepath.contains(APIMgtConstants.APPType.STORE)) {
        nameSpace = APIMgtConstants.NAMESPACE_STORE_API;
    } else if (basepath.contains(APIMgtConstants.APPType.ADMIN)) {
        nameSpace = APIMgtConstants.NAMESPACE_ADMIN_API;
    } else if (basepath.contains(APIMgtConstants.APPType.ANALYTICS)) {
        nameSpace = APIMgtConstants.NAMESPACE_ANALYTICS_API;
    }
    // if namespace is not available in local cache add it.
    if (nameSpace != null && !localConfigMap.containsKey(nameSpace)) {
        localConfigMap.put(nameSpace, new ConcurrentHashMap<>());
    }
    if (nameSpace != null && localConfigMap.containsKey(nameSpace) && localConfigMap.get(nameSpace).isEmpty()) {
        populateConfigMapForScopes(swagger, nameSpace);
    }
    String resourceConfig = verb + "_" + apiPrefix + pathTemplate;
    if (localConfigMap.get(nameSpace).containsKey(resourceConfig)) {
        return localConfigMap.get(nameSpace).get(resourceConfig).toString();
    }
    return null;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) Path(io.swagger.models.Path) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Swagger(io.swagger.models.Swagger) Method(java.lang.reflect.Method) HttpMethod(io.swagger.models.HttpMethod)

Example 5 with Request

use of org.wso2.msf4j.Request in project carbon-apimgt by wso2.

the class RestCallUtilImpl method getResponse.

/**
 * To get a response from service.
 *
 * @param httpConnection Connection used to make the request
 * @return HttpResponse from service
 * @throws IOException In case of any failures, when trying to get the response from service
 */
private HttpResponse getResponse(HttpURLConnection httpConnection) throws IOException {
    HttpResponse response = new HttpResponse();
    response.setResponseCode(httpConnection.getResponseCode());
    response.setResponseMessage(httpConnection.getResponseMessage());
    if (response.getResponseCode() / 100 == 2) {
        try (BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder results = new StringBuilder();
            String line;
            while ((line = responseBuffer.readLine()) != null) {
                results.append(line).append("\n");
            }
            response.setHeaderFields(httpConnection.getHeaderFields());
            response.setResults(results.toString());
        }
    }
    return response;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)194 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)143 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)136 Request (org.wso2.msf4j.Request)126 HashMap (java.util.HashMap)123 Response (javax.ws.rs.core.Response)102 Test (org.junit.Test)92 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)89 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)79 ArrayList (java.util.ArrayList)64 Test (org.testng.annotations.Test)63 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)48 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)44 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)40 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)37 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)30 Map (java.util.Map)29 IOException (java.io.IOException)27 Produces (javax.ws.rs.Produces)27 HttpMessageDataStreamer (org.wso2.transport.http.netty.message.HttpMessageDataStreamer)26