changes in UI after refactoring

revert-70aa11f8
ayyoob 8 years ago
parent 4292442aa5
commit 44ac6b13b5

@ -42,6 +42,10 @@ public class ConfigurationBasedFeatureManager implements FeatureManager {
private static final String QUERY_PARAMS = "queryParams";
private static final String FORM_PARAMS = "formParams";
private static final Pattern PATH_PARAM_REGEX = Pattern.compile("\\{(.*?)\\}");
private List<String> pathParams = new ArrayList<>();
private List<String> queryParams = new ArrayList<>();
private List<String> formParams = new ArrayList<>();
public ConfigurationBasedFeatureManager(
List<org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.Feature> features) {
@ -55,17 +59,16 @@ public class ConfigurationBasedFeatureManager implements FeatureManager {
Map<String, Object> apiParams = new HashMap<>();
apiParams.put(METHOD, operation.getMethod().toUpperCase());
apiParams.put(URI, operation.getContext());
List<String> pathParams = getPathParams(operation.getContext());
if (!pathParams.isEmpty()) {
setPathParams(operation.getContext());
apiParams.put(PATH_PARAMS, pathParams);
}
if (operation.getQueryParameters() != null) {
apiParams.put(QUERY_PARAMS, operation.getQueryParameters().getParameter());
queryParams = operation.getQueryParameters().getParameter();
}
apiParams.put(QUERY_PARAMS, queryParams);
if (operation.getFormParameters() != null) {
apiParams.put(FORM_PARAMS, operation.getFormParameters().getParameter());
formParams = operation.getFormParameters().getParameter();
}
apiParams.put(FORM_PARAMS, formParams);
List<Feature.MetadataEntry> metadataEntries = new ArrayList<>();
Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry();
metadataEntry.setId(-1);
@ -113,12 +116,10 @@ public class ConfigurationBasedFeatureManager implements FeatureManager {
return false;
}
private List<String> getPathParams(String context) {
List<String> matchList = new ArrayList<String>();
private void setPathParams(String context) {
Matcher regexMatcher = PATH_PARAM_REGEX.matcher(context);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
pathParams.add(regexMatcher.group(1));
}
return matchList;
}
}

@ -71,6 +71,11 @@ public class GCMNotificationStrategy implements NotificationStrategy {
return null;
}
@Override
public void undeploy() {
}
private void sendWakeUpCall(String message,
Device device) throws IOException, PushNotificationExecutionFailedException {
OutputStream os = null;

@ -101,4 +101,9 @@ public class MQTTNotificationStrategy implements NotificationStrategy {
return null;
}
@Override
public void undeploy() {
MQTTDataHolder.getInstance().getOutputEventAdapterService().destroy(mqttAdapterName);
}
}

@ -89,4 +89,9 @@ public class XMPPNotificationStrategy implements NotificationStrategy {
return null;
}
@Override
public void undeploy() {
XMPPDataHolder.getInstance().getOutputEventAdapterService().destroy(xmppAdapterName);
}
}

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.common.operation.mgt;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import java.util.List;
@ -93,4 +94,16 @@ public interface OperationManager {
int getActivityCountUpdatedAfter(long timestamp) throws OperationManagementException;
/**
* Operation manger implementation can have a push notification stratergy
* @param notificationStrategy eg: mqtt/xmpp
*/
void setNotificationStrategy(NotificationStrategy notificationStrategy);
/**
* retrive the push notification strategy.
* @return NotificationStrategy
*/
NotificationStrategy getNotificationStrategy();
}

@ -26,4 +26,9 @@ public interface NotificationStrategy {
NotificationContext buildContext();
/**
* This will be executed when undeploying the device type.
*/
void undeploy();
}

@ -99,8 +99,15 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName, providerTenantId);
providers.remove(deviceTypeIdentifier);
}
OperationManager operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier);
if (operationManager != null) {
NotificationStrategy notificationStrategy = operationManager.getNotificationStrategy();
if (notificationStrategy != null) {
notificationStrategy.undeploy();
}
operationManagerRepository.removeOperationManager(deviceTypeIdentifier);
}
}
public DeviceManagementService getDeviceManagementService(String type, int tenantId) {
//Priority need to be given to the tenant before public.

@ -83,6 +83,14 @@ public class OperationManagerImpl implements OperationManager {
enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
}
public NotificationStrategy getNotificationStrategy() {
return notificationStrategy;
}
public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
this.notificationStrategy = notificationStrategy;
}
public OperationManagerImpl(NotificationStrategy notificationStrategy) {
this();
this.notificationStrategy = notificationStrategy;

@ -136,4 +136,14 @@ public class PushNotificationBasedOperationManager implements OperationManager {
return this.operationManager.getActivityCountUpdatedAfter(timestamp);
}
@Override
public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
}
@Override
public NotificationStrategy getNotificationStrategy() {
return notificationProvider;
}
}

@ -30,8 +30,10 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) {
//NOTE: We are only interested in Content-Type headers. Appending all request headers to the back-end call
// will cause unforeseen security issues.
var contentType = request.getHeader(constants.CONTENT_TYPE_IDENTIFIER);
var acceptType = request.getHeader(constants.ACCEPT_IDENTIFIER);
var requestHeaders = [];
requestHeaders.push({"name": constants.CONTENT_TYPE_IDENTIFIER, "value" : contentType});
requestHeaders.push({"name": constants.ACCEPT_IDENTIFIER, "value" : acceptType});
var restAPIRequestDetails = request.getContent();

@ -63,6 +63,7 @@ var CONTENT_TYPE_IDENTIFIER = "Content-Type";
var CONTENT_DISPOSITION_IDENTIFIER = "Content-Disposition";
var APPLICATION_JSON = "application/json";
var APPLICATION_ZIP = "application/zip";
var STREAMING_FILES_ACCEPT_HEADERS = ["application/zip", "application/pdf", "application/octet-stream"];
var ACCEPT_IDENTIFIER = "Accept";
var AUTHORIZATION_HEADER= "Authorization";
var BEARER_PREFIX = "Bearer ";

@ -301,6 +301,7 @@ var invokers = function () {
var Header = Packages.org.apache.commons.httpclient.Header;
var contentTypeFound = false;
var acceptTypeFound = false;
var acceptTypeValue = constants["APPLICATION_JSON"];
for (var i in headers) {
var header = new Header();
header.setName(headers[i].name);
@ -312,6 +313,7 @@ var invokers = function () {
}
if(constants["ACCEPT_IDENTIFIER"] == headers[i].name){
acceptTypeFound = true;
acceptTypeValue = headers[i].value;
}
}
@ -356,10 +358,8 @@ var invokers = function () {
client.executeMethod(httpMethodObject);
//noinspection JSUnresolvedFunction
var status = httpMethodObject.getStatusCode();
if (status == 200) {
var responseContentDispositionHeader = httpMethodObject.getResponseHeader(
constants["CONTENT_DISPOSITION_IDENTIFIER"]);
if (responseContentDispositionHeader) {
if (status >= 200 && status < 300) {
if (constants["STREAMING_FILES_ACCEPT_HEADERS"].indexOf(acceptTypeValue) > -1) {
return successCallback(httpMethodObject.getResponseBodyAsStream(),
httpMethodObject.getResponseHeaders());
} else {

@ -28,7 +28,7 @@ function onRequest(context) {
}
});
var page = {};
var policyModule = require("/app/modules/business-controllers/group.js")["groupModule"];
var policyModule = require("/app/modules/business-controllers/policy.js")["policyModule"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var response = policyModule.getAllPolicies();
if (response["status"] == "success") {

@ -0,0 +1,163 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Checks if provided input is valid against RegEx input.
*
* @param regExp Regular expression
* @param inputString Input string to check
* @returns {boolean} Returns true if input matches RegEx
*/
function inputIsValid(regExp, inputString) {
regExp = new RegExp(regExp);
return regExp.test(inputString);
}
/**
* Checks if an email address has the valid format or not.
*
* @param email Email address
* @returns {boolean} true if email has the valid format, otherwise false.
*/
function emailIsValid(email) {
var regExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return regExp.test(email);
}
$(document).ready(function(){
/**
* Following click function would execute
* when a user clicks on "Add User" button
* on Add User page in WSO2 Devicemgt Console.
*/
$("button#add-user-btn").click(function () {
var usernameInput = $("input#user_name");
var firstnameInput = $("input#first_name");
var lastnameInput = $("input#last_name");
var emailInput = $("input#email");
var passwordInput = $("input#password");
var passwordConfirmationInput = $("input#password_confirmation");
var username = usernameInput.val().trim();
var firstname = firstnameInput.val();
var lastname = lastnameInput.val();
var emailAddress = emailInput.val();
var password = passwordInput.val();
var passwordConfirmation = passwordConfirmationInput.val();
var errorMsgWrapper = "#user-create-error-msg";
var errorMsg = "#user-create-error-msg span";
if (!firstname) {
$(errorMsg).text("Firstname is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (!inputIsValid(firstnameInput.data("regex"), firstname)) {
$(errorMsg).text(firstnameInput.data("errormsg"));
$(errorMsgWrapper).removeClass("hidden");
} else if (!lastname) {
$(errorMsg).text("Lastname is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (!inputIsValid(lastnameInput.data("regex"), lastname)) {
$(errorMsg).text(lastnameInput.data("errormsg"));
$(errorMsgWrapper).removeClass("hidden");
} else if (!username) {
$(errorMsg).text("Username is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (!inputIsValid(usernameInput.data("regex"), username)) {
$(errorMsg).text(usernameInput.data("errormsg"));
$(errorMsgWrapper).removeClass("hidden");
} else if (!emailAddress) {
$(errorMsg).text("Email is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (!emailIsValid(emailAddress)) {
$(errorMsg).text(emailInput.data("errormsg"));
$(errorMsgWrapper).removeClass("hidden");
} else if (!password) {
$(errorMsg).text("Password is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (password.length < 6) {
$(errorMsg).text("Password is a required field. It cannot be empty.");
$(errorMsgWrapper).removeClass("hidden");
} else if (password != passwordConfirmation) {
$(errorMsg).text("Please enter the same password for confirmation.");
$(errorMsgWrapper).removeClass("hidden");
} else {
$(errorMsgWrapper).addClass("hidden");
$("#add-user-btn").prop('disabled', true);
var addUserFormData = {};
addUserFormData.username = username;
addUserFormData.firstname = firstname;
addUserFormData.lastname = lastname;
addUserFormData.emailAddress = emailAddress;
addUserFormData.password = $("input#password").val();
addUserFormData.userRoles = null;
var context = $(".form-login-box").data("context");
var addUserAPI = context + "/api/user/register";
$.ajax({
type: 'POST',
url: addUserAPI,
contentType: 'application/json',
data: JSON.stringify(addUserFormData),
success: function (data) {
$("#add-user-btn").prop('disabled', false);
if (data == 200) {
$('.wr-validation-summary strong').html(
"<i class=\"icon fw fw-ok\"></i> Successfully Submitted.");
$('.wr-validation-summary').removeClass("alert-danger");
$('.wr-validation-summary').addClass("alert-success");
} else if (data == 201) {
$('.wr-validation-summary strong').html(
"<i class=\"icon fw fw-ok\"></i> User created succssfully. You will be " +
"redirected to login page.");
$('.wr-validation-summary').removeClass("alert-danger");
$('.wr-validation-summary').addClass("alert-success");
$("#add-user-btn").prop('disabled', true);
setTimeout(function () {
window.location = context + "/login";
}, 2000);
} else if (data == 400) {
$('.wr-validation-summary strong').html(
"<i class=\"icon fw fw-error\"></i> Exception at backend.");
$('.wr-validation-summary').removeClass("alert-danger");
$('.wr-validation-summary').addClass("alert-warning");
} else if (data == 403) {
$('.wr-validation-summary strong').html("Action not permitted.");
} else if (data == 409) {
$('.wr-validation-summary strong').html(
"<i class=\"icon fw fw-info\"></i> User name already exists.");
$('.wr-validation-summary').removeClass("alert-default");
$('.wr-validation-summary').addClass("alert-success");
}
$('.wr-validation-summary').removeClass("hidden");
$('#password').val('');
$('#password_confirmation').val('');
},
error: function (err) {
$("#add-user-btn").prop('disabled', false);
$('.wr-validation-summary strong').html(
"<i class=\"icon fw fw-error\"></i> An unexpected error occurred.");
$('.wr-validation-summary').removeClass("hidden");
}
});
}
});
});

@ -0,0 +1,75 @@
{{unit "cdmf.unit.ui.title" pageTitle="Register"}}
{{#zone "content"}}
{{unit "uuf.unit.lib.form-validation"}}
<div class="container col-xs-12 col-sm-10 col-md-8 col-lg-6 col-centered wr-content wr-login col-centered sign-panel">
<p class="page-sub-title">Register</p>
<p>Create new account on WSO2 IoT (All fields are required.)</p>
<hr/>
<!-- validation -->
<div class="wr-validation-summary hidden alert alert-danger">
<strong></strong>
<button type="button" class="close" aria-label="close" data-dismiss="alert">
<span aria-hidden="true">
<i class="fw fw-cancel"></i>
</span>
</button>
</div>
<div class="form-login-box" id="registerForm" data-context="{{@app.context}}">
<div id="user-create-error-msg" class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<div class="form-group">
<label for="first_name" class="wr-input-label">First Name</label>
<input type="text" id="first_name" name="first_name" class="form-control" placeholder="First Name"
data-regex="{{usernameJSRegEx}}" data-lengthmsg="{{usernameHelpText}}"
data-errormsg="{{usernameRegExViolationErrorMsg}}"/>
</div>
<div class="form-group">
<label for="last_name" class="wr-input-label">Last Name</label>
<input type="text" id="last_name" name="last_name" class="form-control" placeholder="Last Name"
data-regex="{{usernameJSRegEx}}" data-errormsg="{{usernameRegExViolationErrorMsg}}"/>
</div>
<div class="form-group">
<label for="user_name" class="wr-input-label">Username ( {{usernameHelpText}} )</label>
<input type="text" id="user_name" name="user_name" class="form-control" placeholder="Username"
data-regex="{{usernameJSRegEx}}" data-errormsg="{{usernameRegExViolationErrorMsg}}"/>
</div>
<div class="form-group">
<label for="email" class="wr-input-label">Email</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email"
data-regex="{{emailJSRegEx}}" data-errormsg="{{emailRegExViolationErrorMsg}}"/>
</div>
<div class="form-group">
<label for="password" class="wr-input-label">Password</label>
<input type="password" id="password" name="password" class="form-control"
placeholder="Password"/>
</div>
<div class="form-group">
<label for="password_confirmation" class="wr-input-label">Confirm Password</label>
<input type="password" id="password_confirmation" name="password_confirmation"
class="form-control" placeholder="Confirm Password"/>
</div>
<div class="wr-input-control">
<button class="wr-btn" id="add-user-btn">Register</button>
<button class="wr-btn" onclick="document.location.href='{{@app.context}}/login';">
Cancel
</button>
</div>
</div>
</div>
{{/zone}}
{{#zone "bottomJs"}}
{{js "js/validate-register.js"}}
{{/zone}}

@ -0,0 +1,38 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Returns the dynamic state to be populated by add-user page.
*
* @param context Object that gets updated with the dynamic state of this page to be presented
* @returns {*} A context object that returns the dynamic state of this page to be presented
*/
function onRequest(context) {
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var page = {};
page["usernameJSRegEx"] = devicemgtProps.userValidationConfig.usernameJSRegEx;
page["usernameHelpText"] = devicemgtProps.userValidationConfig.usernameHelpMsg;
page["usernameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.usernameRegExViolationErrorMsg;
page["firstnameJSRegEx"] = devicemgtProps.userValidationConfig.firstnameJSRegEx;
page["firstnameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.firstnameRegExViolationErrorMsg;
page["lastnameJSRegEx"] = devicemgtProps.userValidationConfig.lastnameJSRegEx;
page["lastnameRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.lastnameRegExViolationErrorMsg;
page["emailJSRegEx"] = devicemgtProps.userValidationConfig.emailJSRegEx;
page["emailRegExViolationErrorMsg"] = devicemgtProps.userValidationConfig.emailRegExViolationErrorMsg;
return page;
}

@ -0,0 +1,6 @@
{
"version": "1.0.0",
"uri": "/register",
"isAnonymous": true,
"layout": "uuf.layout.sign-in"
}

@ -15,11 +15,106 @@
specific language governing permissions and limitations
under the License.
}}
{{#if control_operations}}
<div class="wr-operations" style="height: 87px; display: block;">
<style>
::-webkit-input-placeholder {
color: #B8B8B8;
}
<div class="wr-operations"></div>
::-moz-placeholder {
color: #B8B8B8;
}
:-ms-input-placeholder {
color: #B8B8B8;
}
input:-moz-placeholder {
color: #B8B8B8;
}
</style>
{{#each control_operations}}
<a href="javascript:operationSelect('{{operation}}')">
{{#if icon}}
<img src="{{@app.context}}/{{icon}}" style="width: 48px;"/>
{{else}}
<i class="fw fw-service"></i>
{{/if}}
<span>{{name}}</span>
</a>
<div class="operation" data-operation-code="{{operation}}">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-service fw-stack-1x"></i>
</span>
{{name}}
<br>
</h3>
<h4>
{{description}}
<br>
</h4>
<form action="{{@unit.params.backendApiUri}}{{params.0.uri}}" method="{{params.0.method}}" style="padding-bottom: 20px;" id="form-{{operation}}">
{{#each params.0.pathParams}}
<input type="{{type}}" id="{{name}}" placeholder="{{name}}" class="form-control" data-param-type="path" value="{{value}}" />
<br />
{{/each}}
{{#each params.0.formParams}}
<input type="{{type}}" id="{{name}}" name="{{name}}" placeholder="{{name}}" class="form-control" data-param-type="form" value="{{value}}" />
<br />
{{/each}}
{{#each params.0.queryParams}}
<input type="{{type}}" id="{{name}}" placeholder="{{name}}" class="form-control" data-param-type="query" value="{{value}}" />
<br />
{{/each}}
<button id="btnSend" type="button" onclick="submitForm('form-{{operation}}')" class="btn btn-default">&nbsp;&nbsp;&nbsp;&nbsp;Send
to Device&nbsp;&nbsp;&nbsp;&nbsp;</button>
<label id="lblSending" class="wr-input-label hidden"><i
class="fw fw-lifecycle fw-spin fw-2x"></i> Sending..</label>
<label id="lblSent" class="wr-input-label hidden"><i
class="fw fw-check fw-2x"></i> Sent</label>
</form>
</div>
</div>
</div>
</div>
{{/each}}
</div>
{{else}}
<div align="center">
<h4 style="color: #D8000C"><i class="icon fw fw-error" style="color: #D8000C"></i>
Operations Loading Failed!</h4>
</div>
{{/if}}
<div id="operation-response-template" style="display: none">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i id="status-icon" class="fw fw-error fw-stack-1x"></i>
</span>
<br>
</h3>
<h4>
<span id="title"></span>
<br>
</h4>
<span id="description"></span>
</div>
</div>
</div>
</div>
{{#zone "bottomJs"}}
<script id="operations-bar" src="{{@unit.publicUri}}/templates/operations.hbs"
type="text/x-handlebars-template"></script>
{{js "js/operation-bar.js"}}
{{/zone}}

@ -0,0 +1,55 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var log = new Log("operation.js");
var operationModule = require("/app/modules/business-controllers/operation.js")["operationModule"];
var device = context.unit.params.device;
var autoCompleteParams = context.unit.params.autoCompleteParams;
var controlOperations = operationModule.getControlOperations(device.type);
var queryParams = [];
var formParams = [];
var pathParams = [];
for (var i = 0; i < controlOperations.length; i++) {
var currentParamList = controlOperations[i]["params"];
for (var j = 0; j < currentParamList.length; j++) {
var currentParam = currentParamList[j];
currentParamList[j]["formParams"] = processParams(currentParam["formParams"], autoCompleteParams);
currentParamList[j]["queryParams"] = processParams(currentParam["queryParams"], autoCompleteParams);
currentParamList[j]["pathParams"] = processParams(currentParam["pathParams"], autoCompleteParams);
}
controlOperations[i]["params"] = currentParamList;
}
return {"control_operations": controlOperations, "device": device};
}
function processParams(paramsList, autoCompleteParams) {
for (var i = 0; i < paramsList.length; i++) {
var paramName = paramsList[i];
var paramValue = "";
var paramType = "text";
for (var k = 0; k < autoCompleteParams.length; k++) {
if (paramName == autoCompleteParams[k].name) {
paramValue = autoCompleteParams[k].value;
paramType = "hidden";
}
}
paramsList[i] = {"name": paramName, "value": paramValue, "type": paramType};
}
return paramsList;
}

@ -0,0 +1,126 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* On operation click function.
* @param selection: Selected operation
*/
function operationSelect(selection) {
$(modalPopupContent).addClass("operation-data");
$(modalPopupContent).html($(" .operation[data-operation-code=" + selection + "]").html());
$(modalPopupContent).data("operation-code", selection);
showPopup();
}
function submitForm(formId) {
var form = $("#" + formId);
var uri = form.attr("action");
var uriencodedQueryStr = "";
var uriencodedFormStr = "";
var payload = {};
form.find("input").each(function () {
var input = $(this);
if (input.data("param-type") == "path") {
uri = uri.replace("{" + input.attr("id") + "}", input.val());
} else if (input.data("param-type") == "query") {
var prefix = (uriencodedQueryStr == "") ? "?" : "&";
uriencodedQueryStr += prefix + input.attr("id") + "=" + input.val();
} else if (input.data("param-type") == "form") {
var prefix = (uriencodedFormStr == "") ? "" : "&";
uriencodedFormStr += prefix + input.attr("id") + "=" + input.val();
//payload[input.attr("id")] = input.val();
}
});
uri += uriencodedQueryStr;
var httpMethod = form.attr("method").toUpperCase();
var contentType = form.attr("enctype");
console.log(payload);
if (contentType == undefined || contentType.isEmpty()) {
contentType = "application/x-www-form-urlencoded";
payload = uriencodedFormStr;
}
//setting responses callbacks
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#operation-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var description = content.find("#description");
var successCallBack = function (response) {
var res = response;
try {
res = JSON.parse(response).messageFromServer;
} catch (err) {
//do nothing
}
title.html("Operation Triggered!");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
description.html(res);
$(modalPopupContent).html(content.html());
};
var errorCallBack = function (response) {
console.log(response);
title.html("An Error Occurred!");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
var reason = (response.responseText == "null")?response.statusText:response.responseText;
description.html(reason);
$(modalPopupContent).html(content.html());
};
//executing http request
if (httpMethod == "GET") {
invokerUtil.get(uri, successCallBack, errorCallBack, contentType);
} else if (httpMethod == "POST") {
invokerUtil.post(uri, payload, successCallBack, errorCallBack, contentType);
} else if (httpMethod == "PUT") {
invokerUtil.put(uri, payload, successCallBack, errorCallBack, contentType);
} else if (httpMethod == "DELETE") {
invokerUtil.delete(uri, successCallBack, errorCallBack, contentType);
} else {
title.html("An Error Occurred!");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
description.html("This operation requires http method: " + httpMethod + " which is not supported yet!");
$(modalPopupContent).html(content.html());
}
}
$(document).on('submit', 'form', function (e) {
e.preventDefault();
var postOperationRequest = $.ajax({
url: $(this).attr("action") + '&' + $(this).serialize(),
method: "post"
});
var btnSubmit = $('#btnSend', this);
btnSubmit.addClass('hidden');
var lblSending = $('#lblSending', this);
lblSending.removeClass('hidden');
var lblSent = $('#lblSent', this);
postOperationRequest.done(function (data) {
lblSending.addClass('hidden');
lblSent.removeClass('hidden');
setTimeout(function () {
hidePopup();
}, 3000);
});
postOperationRequest.fail(function (jqXHR, textStatus) {
lblSending.addClass('hidden');
lblSent.addClass('hidden');
});
});

@ -21,20 +21,31 @@ var invokerUtil = function () {
var publicMethods = {};
var privateMethods = {};
privateMethods.execute = function (requestMethod, requestURL, requestPayload, successCallback, errorCallback) {
privateMethods.execute = function (requestMethod, requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType) {
var restAPIRequestDetails = {};
restAPIRequestDetails["requestMethod"] = requestMethod;
restAPIRequestDetails["requestURL"] = requestURL;
restAPIRequestDetails["requestPayload"] = JSON.stringify(requestPayload);
restAPIRequestDetails["requestPayload"] = requestPayload;
var appContext = $("#app-context").data("app-context");
var contentTypeValue = "application/json";
if (contentType) {
contentTypeValue = contentType;
}
var acceptTypeValue = "application/json";
if (acceptType) {
acceptTypeValue = acceptType;
}
if(contentTypeValue == "application/json"){
restAPIRequestDetails["requestPayload"] = JSON.stringify(requestPayload);
}
var request = {
url: appContext + "/api/invoker/execute/",
type: "POST",
contentType: "application/json",
contentType: contentTypeValue,
data: JSON.stringify(restAPIRequestDetails),
accept: "application/json",
accept: acceptTypeValue,
success: successCallback,
error: function (jqXHR) {
if (jqXHR.status == 401) {
@ -50,22 +61,22 @@ var invokerUtil = function () {
$.ajax(request);
};
publicMethods.get = function (requestURL, successCallback, errorCallback) {
publicMethods.get = function (requestURL, successCallback, errorCallback, contentType, acceptType) {
var requestPayload = null;
privateMethods.execute("GET", requestURL, requestPayload, successCallback, errorCallback);
privateMethods.execute("GET", requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType);
};
publicMethods.post = function (requestURL, requestPayload, successCallback, errorCallback) {
privateMethods.execute("POST", requestURL, requestPayload, successCallback, errorCallback);
publicMethods.post = function (requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType) {
privateMethods.execute("POST", requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType);
};
publicMethods.put = function (requestURL, requestPayload, successCallback, errorCallback) {
privateMethods.execute("PUT", requestURL, requestPayload, successCallback, errorCallback);
publicMethods.put = function (requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType) {
privateMethods.execute("PUT", requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType);
};
publicMethods.delete = function (requestURL, successCallback, errorCallback) {
publicMethods.delete = function (requestURL, successCallback, errorCallback, contentType, acceptType) {
var requestPayload = null;
privateMethods.execute("DELETE", requestURL, requestPayload, successCallback, errorCallback);
privateMethods.execute("DELETE", requestURL, requestPayload, successCallback, errorCallback, contentType, acceptType);
};
return publicMethods;

@ -22,7 +22,7 @@ function onRequest(context) {
var utility = require("/app/modules/utility.js").utility;
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var types = {};
types.isAuthorized = userModule.isAuthorized("/permission/admin/device-mgt/policies/manage");

@ -15,4 +15,4 @@
specific language governing permissions and limitations
under the License.
}}
{{#zone "productName"}}CDMF BASE APP{{/zone}}
{{#zone "productName"}}WSO2 IoT{{/zone}}
Loading…
Cancel
Save