Search in sources :

Example 76 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class BaseExecutionService method createExecutionVariable.

protected Response createExecutionVariable(Execution execution, boolean override, int variableType, HttpServletRequest httpServletRequest, UriInfo uriInfo) {
    Object result = null;
    Response.ResponseBuilder responseBuilder = Response.ok();
    List<RestVariable> inputVariables = new ArrayList<>();
    List<RestVariable> resultVariables = new ArrayList<>();
    if (Utils.isApplicationJsonRequest(httpServletRequest)) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) objectMapper.readValue(httpServletRequest.getInputStream(), List.class);
            for (Object restObject : variableObjects) {
                RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
                inputVariables.add(restVariable);
            }
        } catch (Exception e) {
            throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
        }
    } else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(new StreamSource(httpServletRequest.getInputStream()));
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller.unmarshal(xmlReader);
            if (restVariableCollection == null) {
                throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable Collection instance.");
            }
            List<RestVariable> restVariableList = restVariableCollection.getRestVariables();
            if (restVariableList.size() == 0) {
                throw new ActivitiIllegalArgumentException("xml request body could not identify any rest " + "variables to be updated");
            }
            for (RestVariable restVariable : restVariableList) {
                inputVariables.add(restVariable);
            }
        } catch (JAXBException | IOException | XMLStreamException e) {
            throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable instance.", e);
        }
    }
    if (inputVariables.size() == 0) {
        throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create.");
    }
    RestVariable.RestVariableScope sharedScope = null;
    RestVariable.RestVariableScope varScope = null;
    Map<String, Object> variablesToSet = new HashMap<String, Object>();
    for (RestVariable var : inputVariables) {
        // Validate if scopes match
        varScope = var.getVariableScope();
        if (var.getName() == null) {
            throw new ActivitiIllegalArgumentException("Variable name is required");
        }
        if (varScope == null) {
            varScope = RestVariable.RestVariableScope.LOCAL;
        }
        if (sharedScope == null) {
            sharedScope = varScope;
        }
        if (varScope != sharedScope) {
            throw new ActivitiIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
        }
        if (!override && hasVariableOnScope(execution, var.getName(), varScope)) {
            throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'.");
        }
        Object actualVariableValue = new RestResponseFactory().getVariableValue(var);
        variablesToSet.put(var.getName(), actualVariableValue);
        resultVariables.add(new RestResponseFactory().createRestVariable(var.getName(), actualVariableValue, varScope, execution.getId(), variableType, false, uriInfo.getBaseUri().toString()));
    }
    if (!variablesToSet.isEmpty()) {
        RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
        if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
            runtimeService.setVariablesLocal(execution.getId(), variablesToSet);
        } else {
            if (execution.getParentId() != null) {
                // Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists
                runtimeService.setVariables(execution.getParentId(), variablesToSet);
            } else {
                // Standalone task, no global variables possible
                throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process.");
            }
        }
    }
    RestVariableCollection restVariableCollection = new RestVariableCollection();
    restVariableCollection.setRestVariables(resultVariables);
    responseBuilder.entity(restVariableCollection);
    return responseBuilder.status(Response.Status.CREATED).build();
}
Also used : BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) XMLStreamReader(javax.xml.stream.XMLStreamReader) JAXBContext(javax.xml.bind.JAXBContext) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) Unmarshaller(javax.xml.bind.Unmarshaller) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) RuntimeService(org.activiti.engine.RuntimeService) StreamSource(javax.xml.transform.stream.StreamSource) ActivitiException(org.activiti.engine.ActivitiException) BPMNContentNotSupportedException(org.wso2.carbon.bpmn.rest.common.exception.BPMNContentNotSupportedException) XMLStreamException(javax.xml.stream.XMLStreamException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) JAXBException(javax.xml.bind.JAXBException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 77 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-business-process by wso2.

the class HTRenderingApiImpl method getRenderingInputElements.

/**
 * @param taskIdentifier : interested task identifier
 * @return set of input renderings wrapped within InputType
 * @throws IllegalArgumentFault : error occured while retrieving renderings from task definition
 * @throws IOException          If an error occurred while reading from the input source
 * @throws SAXException         If the content in the input source is invalid
 */
private InputType getRenderingInputElements(URI taskIdentifier) throws IllegalArgumentFault, IOException, SAXException, IllegalOperationFault, IllegalAccessFault, IllegalStateFault, XPathExpressionException {
    // TODO Chaching : check cache against task id for input renderings
    QName renderingType = new QName(htRenderingNS, "input", "wso2");
    String inputRenderings = (String) taskOps.getRendering(taskIdentifier, renderingType);
    // Create input element
    InputType renderingInputs = null;
    // check availability of input renderings
    if (inputRenderings != null && inputRenderings.length() > 0) {
        // parse input renderings
        Element inputRenderingsElement = DOMUtils.stringToDOM(inputRenderings);
        // retrieve input elements
        NodeList inputElementList = inputRenderingsElement.getElementsByTagNameNS(htRenderingNS, "element");
        Element taskInputMsgElement = DOMUtils.stringToDOM((String) taskOps.getInput(taskIdentifier, null));
        if (inputElementList != null && inputElementList.getLength() > 0) {
            // hold number of input element
            int inputElementNum = inputElementList.getLength();
            InputElementType[] inputElements = new InputElementType[inputElementNum];
            for (int i = 0; i < inputElementNum; i++) {
                Element tempElement = (Element) inputElementList.item(i);
                String label = tempElement.getElementsByTagNameNS(htRenderingNS, "label").item(0).getTextContent();
                String value = tempElement.getElementsByTagNameNS(htRenderingNS, "value").item(0).getTextContent();
                // if the value starts with '/' then considered as an xpath and evaluate over received Input Message
                if (value.startsWith("/") && taskInputMsgElement != null) {
                    // value represents xpath. evaluate against the input message
                    String xpathValue = evaluateXPath(value, taskInputMsgElement, inputRenderingsElement.getOwnerDocument());
                    if (xpathValue != null) {
                        value = xpathValue;
                    }
                }
                inputElements[i] = new InputElementType();
                inputElements[i].setLabel(label);
                inputElements[i].setValue(value);
            }
            renderingInputs = new InputType();
            renderingInputs.setElement(inputElements);
        // TODO cache renderingInputs against task instance id
        }
    }
    return renderingInputs;
}
Also used : InputElementType(org.wso2.carbon.humantask.rendering.api.InputElementType) InputType(org.wso2.carbon.humantask.rendering.api.InputType) QName(javax.xml.namespace.QName) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList)

Example 78 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project product-iots by wso2.

the class DeviceTypeServiceImpl method getSensorStats.

/**
 * Retrieve Sensor data for the given time period.
 *
 * @param deviceId unique identifier for given device type instance
 * @param from     starting time
 * @param to       ending time
 * @return response with List<SensorRecord> object which includes sensor data which is requested
 */
@Path("device/stats/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, @QueryParam("to") long to, @QueryParam("sensorType") String sensorType) {
    String fromDate = String.valueOf(from);
    String toDate = String.valueOf(to);
    String query = "meta_deviceId:" + deviceId + " AND meta_deviceType:" + DeviceTypeConstants.DEVICE_TYPE + " AND meta_time : [" + fromDate + " TO " + toDate + "]";
    String sensorTableName = null;
    if (sensorType.equals(DeviceTypeConstants.SENSOR_TYPE1)) {
        sensorTableName = DeviceTypeConstants.SENSOR_TYPE1_EVENT_TABLE;
    } else if (sensorType.equals(DeviceTypeConstants.SENSOR_TYPE2)) {
        sensorTableName = DeviceTypeConstants.SENSOR_TYPE2_EVENT_TABLE;
    }
    try {
        if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
            return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
        }
        if (sensorTableName != null) {
            List<SortByField> sortByFields = new ArrayList<>();
            SortByField sortByField = new SortByField("meta_time", SortType.ASC);
            sortByFields.add(sortByField);
            List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
            return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
        }
    } catch (AnalyticsException e) {
        String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
        log.error(errorMsg);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
    } catch (DeviceAccessAuthorizationException e) {
        log.error(e.getErrorMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
    return Response.status(Response.Status.BAD_REQUEST).build();
}
Also used : SortByField(org.wso2.carbon.analytics.dataservice.commons.SortByField) DeviceAccessAuthorizationException(org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException) AnalyticsException(org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException) ArrayList(java.util.ArrayList) SensorRecord(org.wso2.iot.sampledevice.api.dto.SensorRecord) DeviceIdentifier(org.wso2.carbon.device.mgt.common.DeviceIdentifier) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 79 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project product-iots by wso2.

the class DeviceTypeServiceImpl method downloadSketch.

/**
 * To download device type agent source code as zip file.
 *
 * @param deviceName name for the device type instance
 * @param sketchType folder name where device type agent was installed into server
 * @return Agent source code as zip file
 */
@Path("/device/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
    try {
        ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
        Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
        response.status(Response.Status.OK);
        response.type("application/zip");
        response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
        Response resp = response.build();
        zipFile.getZipFile().delete();
        return resp;
    } catch (IllegalArgumentException ex) {
        // bad request
        return Response.status(400).entity(ex.getMessage()).build();
    } catch (DeviceManagementException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (JWTClientException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (APIManagerException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (UserStoreException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagerException(org.wso2.carbon.apimgt.application.extension.exception.APIManagerException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive) IOException(java.io.IOException) JWTClientException(org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 80 with Instance

use of org.wso2.carbon.bpel.core.ode.integration.jmx.Instance in project carbon-apimgt by wso2.

the class ApiDAOImpl method addAPI.

/**
 * Add a new instance of an API
 *
 * @param api The {@link API} object to be added
 * @throws APIMgtDAOException if error occurs while accessing data layer
 */
@Override
public void addAPI(final API api) throws APIMgtDAOException {
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(API_INSERT)) {
        try {
            connection.setAutoCommit(false);
            addAPIRelatedInformation(connection, statement, api);
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            throw new APIMgtDAOException("adding API: " + api.getProvider() + "-" + api.getName() + "-" + api.getVersion(), e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "adding API: " + api.getProvider() + " - " + api.getName() + " - " + api.getVersion(), e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Aggregations

ArrayList (java.util.ArrayList)28 Test (org.junit.Test)23 Response (javax.ws.rs.core.Response)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)21 APIManagerFactory (org.wso2.carbon.apimgt.core.impl.APIManagerFactory)20 HashMap (java.util.HashMap)15 Path (javax.ws.rs.Path)15 RuntimeService (org.activiti.engine.RuntimeService)15 HistoricProcessInstance (org.activiti.engine.history.HistoricProcessInstance)15 InstanceManagementException (org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)14 Produces (javax.ws.rs.Produces)13 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)13 IOException (java.io.IOException)12 APIMgtAdminServiceImpl (org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl)12 GET (javax.ws.rs.GET)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)10 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)9 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8