Search in sources :

Example 86 with Operation

use of org.wso2.ballerinalang.compiler.semantics.model.iterable.Operation in project siddhi by wso2.

the class SetUpdateInMemoryTableTestCase method updateFromTableTest5.

@Test
public void updateFromTableTest5() throws InterruptedException, SQLException {
    log.info("SET-RDBMS-update test case 5: assignment expression containing an output attribute " + "with a basic arithmatic operation.");
    SiddhiManager siddhiManager = new SiddhiManager();
    String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream UpdateStockStream (symbol string, price float, volume long); " + "define table StockTable (symbol string, price float, volume long); ";
    String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from UpdateStockStream " + "select price + 100 as newPrice , symbol " + "update StockTable " + "set StockTable.price = newPrice + 100 " + "   on StockTable.symbol == symbol ;";
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);
    InputHandler stockStream = siddhiAppRuntime.getInputHandler("StockStream");
    InputHandler updateStockStream = siddhiAppRuntime.getInputHandler("UpdateStockStream");
    siddhiAppRuntime.start();
    stockStream.send(new Object[] { "WSO2", 55.6f, 100L });
    stockStream.send(new Object[] { "IBM", 75.6f, 100L });
    stockStream.send(new Object[] { "WSO2", 57.6f, 100L });
    updateStockStream.send(new Object[] { "IBM", 100f, 100L });
    Thread.sleep(1000);
    siddhiAppRuntime.shutdown();
}
Also used : InputHandler(org.wso2.siddhi.core.stream.input.InputHandler) SiddhiAppRuntime(org.wso2.siddhi.core.SiddhiAppRuntime) SiddhiManager(org.wso2.siddhi.core.SiddhiManager) Test(org.testng.annotations.Test)

Example 87 with Operation

use of org.wso2.ballerinalang.compiler.semantics.model.iterable.Operation in project charon by wso2.

the class JSONDecoder method decodeRequest.

/*
     * This method is to extract operations from the PATCH request body and create separate PatchOperation objects
     * for each operation
     * @param scimResourceString
     * @return
     */
public ArrayList<PatchOperation> decodeRequest(String scimResourceString) throws BadRequestException {
    ArrayList<PatchOperation> operationList = new ArrayList<PatchOperation>();
    try {
        // decode the string into json representation
        JSONObject decodedJsonObj = new JSONObject(new JSONTokener(scimResourceString));
        // obtain the Operations values
        JSONArray operationJsonList = (JSONArray) decodedJsonObj.opt(SCIMConstants.OperationalConstants.OPERATIONS);
        // for each operation, create a PatchOperation object and add the relevant values to it
        for (int count = 0; count < operationJsonList.length(); count++) {
            JSONObject operation = (JSONObject) operationJsonList.get(count);
            PatchOperation patchOperation = new PatchOperation();
            String op = (String) operation.opt(SCIMConstants.OperationalConstants.OP);
            if (op.equalsIgnoreCase(SCIMConstants.OperationalConstants.ADD)) {
                patchOperation.setOperation(SCIMConstants.OperationalConstants.ADD);
            } else if (op.equalsIgnoreCase(SCIMConstants.OperationalConstants.REMOVE)) {
                patchOperation.setOperation(SCIMConstants.OperationalConstants.REMOVE);
            } else if (op.equalsIgnoreCase(SCIMConstants.OperationalConstants.REPLACE)) {
                patchOperation.setOperation(SCIMConstants.OperationalConstants.REPLACE);
            }
            patchOperation.setPath((String) operation.opt(SCIMConstants.OperationalConstants.PATH));
            patchOperation.setValues(operation.opt(SCIMConstants.OperationalConstants.VALUE));
            operationList.add(patchOperation);
        }
    } catch (JSONException e) {
        logger.error("json error in decoding the request");
        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
    }
    return operationList;
}
Also used : JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) PatchOperation(org.wso2.charon3.core.utils.codeutils.PatchOperation) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException)

Example 88 with Operation

use of org.wso2.ballerinalang.compiler.semantics.model.iterable.Operation in project charon by wso2.

the class UserResourceManager method create.

/*
     * Returns SCIMResponse based on the sucess or failure of the create user operation
     *
     * @param scimObjectString -raw string containing user info
     * @return usermanager - usermanager instance defined by the external implementor of charon
     */
public SCIMResponse create(String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) {
    JSONEncoder encoder = null;
    try {
        // obtain the json encoder
        encoder = getEncoder();
        // obtain the json decoder
        JSONDecoder decoder = getDecoder();
        // obtain the schema corresponding to user
        // unless configured returns core-user schema or else returns extended user schema)
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        // decode the SCIM User object, encoded in the submitted payload.
        User user = (User) decoder.decodeResource(scimObjectString, schema, new User());
        // validate the created user.
        ServerSideValidator.validateCreatedSCIMObject(user, schema);
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        User createdUser;
        if (userManager != null) {
            /*handover the SCIM User object to the user usermanager provided by the SP.
            need to send back the newly created user in the response payload*/
            createdUser = userManager.createUser(user, requiredAttributes);
        } else {
            String error = "Provided user manager handler is null.";
            // throw internal server error.
            throw new InternalErrorException(error);
        }
        // encode the newly created SCIM user object and add id attribute to Location header.
        String encodedUser;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        if (createdUser != null) {
            // create a deep copy of the user object since we are going to change it.
            User copiedUser = (User) CopyUtil.deepCopy(createdUser);
            // need to remove password before returning
            ServerSideValidator.validateReturnedAttributes(copiedUser, attributes, excludeAttributes);
            encodedUser = encoder.encodeSCIMObject(copiedUser);
            // add location header
            responseHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.USER_ENDPOINT) + "/" + createdUser.getId());
            responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Newly created User resource is null.";
            throw new InternalErrorException(error);
        }
        // put the uri of the User object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_CREATED, encodedUser, responseHeaders);
    } catch (CharonException e) {
        // because inside API code throws CharonException.
        if (e.getStatus() == -1) {
            e.setStatus(ResponseCodeConstants.CODE_INTERNAL_ERROR);
        }
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (ConflictException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotFoundException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    }
}
Also used : User(org.wso2.charon3.core.objects.User) HashMap(java.util.HashMap) ConflictException(org.wso2.charon3.core.exceptions.ConflictException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) JSONEncoder(org.wso2.charon3.core.encoder.JSONEncoder) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 89 with Operation

use of org.wso2.ballerinalang.compiler.semantics.model.iterable.Operation in project charon by wso2.

the class UserResourceManager method updateWithPATCH.

/**
 * Update the user resource by sequence of operations.
 *
 * @param existingId
 * @param scimObjectString
 * @param userManager
 * @param attributes
 * @param excludeAttributes
 * @return
 */
public SCIMResponse updateWithPATCH(String existingId, String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) {
    try {
        if (userManager == null) {
            String error = "Provided user manager handler is null.";
            throw new InternalErrorException(error);
        }
        // obtain the json decoder.
        JSONDecoder decoder = getDecoder();
        // decode the SCIM User object, encoded in the submitted payload.
        List<PatchOperation> opList = decoder.decodeRequest(scimObjectString);
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        // get the user from the user core
        User oldUser = userManager.getUser(existingId, ResourceManagerUtil.getAllAttributeURIs(schema));
        if (oldUser == null) {
            throw new NotFoundException("No user with the id : " + existingId + " in the user store.");
        }
        // make a copy of the original user
        User copyOfOldUser = (User) CopyUtil.deepCopy(oldUser);
        // make another copy of original user.
        // this will be used to restore to the original condition if failure occurs.
        User originalUser = (User) CopyUtil.deepCopy(copyOfOldUser);
        User newUser = null;
        for (PatchOperation operation : opList) {
            if (operation.getOperation().equals(SCIMConstants.OperationalConstants.ADD)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchAdd(operation, getDecoder(), oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchAdd(operation, getDecoder(), newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else if (operation.getOperation().equals(SCIMConstants.OperationalConstants.REMOVE)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchRemove(operation, oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchRemove(operation, newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else if (operation.getOperation().equals(SCIMConstants.OperationalConstants.REPLACE)) {
                if (newUser == null) {
                    newUser = (User) PatchOperationUtil.doPatchReplace(operation, getDecoder(), oldUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                } else {
                    newUser = (User) PatchOperationUtil.doPatchReplace(operation, getDecoder(), newUser, copyOfOldUser, schema);
                    copyOfOldUser = (User) CopyUtil.deepCopy(newUser);
                }
            } else {
                throw new BadRequestException("Unknown operation.", ResponseCodeConstants.INVALID_SYNTAX);
            }
        }
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        User validatedUser = (User) ServerSideValidator.validateUpdatedSCIMObject(originalUser, newUser, schema);
        newUser = userManager.updateUser(validatedUser, requiredAttributes);
        // encode the newly created SCIM user object and add id attribute to Location header.
        String encodedUser;
        Map<String, String> httpHeaders = new HashMap<String, String>();
        if (newUser != null) {
            // create a deep copy of the user object since we are going to change it.
            User copiedUser = (User) CopyUtil.deepCopy(newUser);
            // need to remove password before returning
            ServerSideValidator.validateReturnedAttributes(copiedUser, attributes, excludeAttributes);
            encodedUser = getEncoder().encodeSCIMObject(copiedUser);
            // add location header
            httpHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.USER_ENDPOINT) + "/" + newUser.getId());
            httpHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Updated User resource is null.";
            throw new CharonException(error);
        }
        // put the URI of the User object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedUser, httpHeaders);
    } catch (NotFoundException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotImplementedException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (CharonException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (RuntimeException e) {
        CharonException e1 = new CharonException("Error in performing the patch operation on user resource.", e);
        return AbstractResourceManager.encodeSCIMException(e1);
    }
}
Also used : User(org.wso2.charon3.core.objects.User) HashMap(java.util.HashMap) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) PatchOperation(org.wso2.charon3.core.utils.codeutils.PatchOperation) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 90 with Operation

use of org.wso2.ballerinalang.compiler.semantics.model.iterable.Operation in project charon by wso2.

the class PatchOperationUtil method doPatchReplaceOnPathWithFilters.

/*
     * This method is to do patch replace for level three attributes with a filter and path value present.
     * @param oldResource
     * @param copyOfOldResource
     * @param schema
     * @param decoder
     * @param operation
     * @param parts
     * @throws NotImplementedException
     * @throws BadRequestException
     * @throws CharonException
     * @throws JSONException
     * @throws InternalErrorException
     */
private static void doPatchReplaceOnPathWithFilters(AbstractSCIMObject oldResource, SCIMResourceTypeSchema schema, JSONDecoder decoder, PatchOperation operation, String[] parts) throws NotImplementedException, BadRequestException, CharonException, JSONException, InternalErrorException {
    if (parts.length != 1) {
        // currently we only support simple filters here.
        String[] filterParts = parts[1].split(" ");
        ExpressionNode expressionNode = new ExpressionNode();
        expressionNode.setAttributeValue(filterParts[0]);
        expressionNode.setOperation(filterParts[1]);
        expressionNode.setValue(filterParts[2]);
        if (expressionNode.getOperation().equalsIgnoreCase((SCIMConstants.OperationalConstants.EQ).trim())) {
            if (parts.length == 3) {
                parts[0] = parts[0] + parts[2];
            }
            String[] attributeParts = parts[0].split("[\\.]");
            if (attributeParts.length == 1) {
                doPatchReplaceWithFiltersForLevelOne(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            } else if (attributeParts.length == 2) {
                doPatchReplaceWithFiltersForLevelTwo(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            } else if (attributeParts.length == 3) {
                doPatchReplaceWithFiltersForLevelThree(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            }
        } else {
            throw new NotImplementedException("Only Eq filter is supported");
        }
    }
}
Also used : ExpressionNode(org.wso2.charon3.core.utils.codeutils.ExpressionNode) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException)

Aggregations

Test (org.testng.annotations.Test)34 HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)29 HashMap (java.util.HashMap)19 ArrayList (java.util.ArrayList)16 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)15 HumanTaskRuntimeException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)12 QueryVariable (org.wso2.carbon.bpmn.rest.engine.variable.QueryVariable)11 List (java.util.List)10 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)10 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)9 Map (java.util.Map)8 ActivitiIllegalArgumentException (org.activiti.engine.ActivitiIllegalArgumentException)8 Operation (io.swagger.models.Operation)7 Attribute (org.wso2.charon3.core.attributes.Attribute)7 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)7 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)7 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)7 Operation (org.wso2.ballerinalang.compiler.semantics.model.iterable.Operation)6 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 AttributeSchema (org.wso2.charon3.core.schema.AttributeSchema)6