fixed few multi tenant issues

revert-dabc3590
ayyoob 8 years ago
parent 00feadac97
commit e66311b844

@ -179,7 +179,9 @@ public class ArduinoServiceImpl implements ArduinoService {
@Produces("application/zip") @Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName) { public Response downloadSketch(@QueryParam("deviceName") String deviceName) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain();
ZipArchive zipFile = createDownloadFile(username, deviceName);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.status(Response.Status.OK); response.status(Response.Status.OK);
response.type("application/zip"); response.type("application/zip");
@ -221,7 +223,8 @@ public class ArduinoServiceImpl implements ArduinoService {
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName(); .getRealmConfiguration().getAdminUserName() + "@" + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain();;
if (apiApplicationKey == null) { if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {ArduinoConstants.DEVICE_TYPE}; String[] tags = {ArduinoConstants.DEVICE_TYPE};

@ -141,7 +141,9 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
@Produces("application/zip") @Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) { public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain();
ZipArchive zipFile = createDownloadFile(username, deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.status(Response.Status.OK); response.status(Response.Status.OK);
response.type("application/zip"); response.type("application/zip");
@ -206,7 +208,8 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
} }
if (apiApplicationKey == null) { if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName(); .getRealmConfiguration().getAdminUserName() + "@" + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {RaspberrypiConstants.DEVICE_TYPE}; String[] tags = {RaspberrypiConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(

@ -172,7 +172,9 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
public Response downloadSketch(@QueryParam("deviceName") String deviceName, public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@QueryParam("sketchType") String sketchType) { @QueryParam("sketchType") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); String user = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain();
ZipArchive zipFile = createDownloadFile(user, deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.status(Response.Status.OK); response.status(Response.Status.OK);
response.type("application/zip"); response.type("application/zip");
@ -242,7 +244,8 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
if (apiApplicationKey == null) { if (apiApplicationKey == null) {
String applicationUsername = String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName(); .getAdminUserName() + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE}; String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(

@ -142,8 +142,16 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE); registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE);
registrationProfile.setOwner(username); registrationProfile.setOwner(username);
registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE); registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE);
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX if (!mqttBrokerConnectionConfiguration.isGlobalCredentailSet()) {
+ mqttBrokerConnectionConfiguration.getAdapterName() + "_" + tenantId); registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
+ mqttBrokerConnectionConfiguration.getAdapterName() +
"_" + tenantId);
registrationProfile.setIsSaasApp(false);
} else {
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
+ mqttBrokerConnectionConfiguration.getAdapterName());
registrationProfile.setIsSaasApp(true);
}
String jsonString = registrationProfile.toJSON(); String jsonString = registrationProfile.toJSON();
StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
postMethod.setEntity(requestEntity); postMethod.setEntity(requestEntity);

@ -12,6 +12,7 @@ public class RegistrationProfile {
private String owner; private String owner;
private String grantType; private String grantType;
private String applicationType; private String applicationType;
private boolean isSaasApp;
private static final String TAG = RegistrationProfile.class.getSimpleName(); private static final String TAG = RegistrationProfile.class.getSimpleName();
@ -63,11 +64,19 @@ public class RegistrationProfile {
this.applicationType = applicationType; this.applicationType = applicationType;
} }
public String toJSON() { public boolean isSaasApp() {
return isSaasApp;
}
public void setIsSaasApp(boolean isSaasApp) {
this.isSaasApp = isSaasApp;
}
public String toJSON() {
String jsonString = String jsonString =
"{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + "\", \"tokenScope\": " + "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + "\", \"tokenScope\": " +
"\"" + tokenScope + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType + "\"" + tokenScope + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType +
"\", \"saasApp\" :true }\n"; "\", \"saasApp\" :" + isSaasApp + " }\n";
return jsonString; return jsonString;
} }
} }

@ -33,6 +33,10 @@
<url>http://wso2.org</url> <url>http://wso2.org</url>
<dependencies> <dependencies>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.analytics-common</groupId> <groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId> <artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
@ -61,6 +65,10 @@
<groupId>com.googlecode.json-simple.wso2</groupId> <groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
@ -121,7 +129,9 @@
org.apache.commons.codec.binary, org.apache.commons.codec.binary,
org.apache.http.client.entity, org.apache.http.client.entity,
org.apache.http.message, org.apache.http.message,
org.apache.commons.ssl org.apache.commons.ssl,
org.wso2.carbon.identity.jwt.client.extension.*,
org.wso2.carbon.user.api
</Import-Package> </Import-Package>
</instructions> </instructions>
</configuration> </configuration>

@ -122,7 +122,7 @@ public class MQTTEventAdapter implements OutputEventAdapter {
String clientId = eventAdapterConfiguration.getStaticProperties().get( String clientId = eventAdapterConfiguration.getStaticProperties().get(
MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID); MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID);
qos = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS); qos = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS);
mqttAdapterPublisher = new MQTTAdapterPublisher(mqttBrokerConnectionConfiguration, clientId); mqttAdapterPublisher = new MQTTAdapterPublisher(mqttBrokerConnectionConfiguration, clientId, tenantId);
} }
@Override @Override

@ -56,19 +56,20 @@ public class MQTTEventAdapterFactory extends OutputEventAdapterFactory {
//Broker Username //Broker Username
Property userName = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME); Property userName = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME);
userName.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME)); userName.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME));
userName.setRequired(true); userName.setRequired(false);
userName.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME_HINT)); userName.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME_HINT));
//Broker Password //Broker Password
Property password = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD); Property password = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD);
password.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD)); password.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD));
password.setRequired(true); password.setRequired(false);
password.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD_HINT)); password.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD_HINT));
//Broker Connection Scopes //Broker Connection Scopes
Property scopes = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES); Property scopes = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES);
scopes.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES)); scopes.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES));
scopes.setRequired(true); scopes.setRequired(false);
scopes.setDefaultValue("default");
scopes.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES_HINT)); scopes.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES_HINT));
// set clientId // set clientId

@ -22,10 +22,15 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.output.adapter.mqtt.MQTTEventAdapterFactory; import org.wso2.carbon.device.mgt.output.adapter.mqtt.MQTTEventAdapterFactory;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
/** /**
* @scr.component component.name="output.Mqtt.AdapterService.component" immediate="true" * @scr.component component.name="output.Mqtt.AdapterService.component" immediate="true"
* @scr.reference name="jwt.client.service" interface="org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService"
* cardinality="1..1"
* policy="dynamic"
* bind="setJWTClientManagerService"
* unbind="unsetJWTClientManagerService"
*/ */
public class MQTTEventAdapterServiceComponent { public class MQTTEventAdapterServiceComponent {
@ -48,4 +53,12 @@ public class MQTTEventAdapterServiceComponent {
} }
} }
protected void setJWTClientManagerService(JWTClientManagerService jwtClientManagerService) {
OutputAdapterServiceDataHolder.setJwtClientManagerService(jwtClientManagerService);
}
protected void unsetJWTClientManagerService(JWTClientManagerService jwtClientManagerService) {
OutputAdapterServiceDataHolder.setJwtClientManagerService(null);
}
} }

@ -0,0 +1,34 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.
*/
package org.wso2.carbon.device.mgt.output.adapter.mqtt.internal;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
/**
* common place to hold some OSGI service references.
*/
public final class OutputAdapterServiceDataHolder {
private static JWTClientManagerService jwtClientManagerService;
public static JWTClientManagerService getJwtClientManagerService() {
return jwtClientManagerService;
}
public static void setJwtClientManagerService(
JWTClientManagerService jwtClientManagerService) {
OutputAdapterServiceDataHolder.jwtClientManagerService = jwtClientManagerService;
}
}

@ -21,14 +21,11 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.ssl.Base64; import org.apache.commons.ssl.Base64;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttException;
@ -38,9 +35,14 @@ import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.output.adapter.mqtt.internal.OutputAdapterServiceDataHolder;
import org.wso2.carbon.event.output.adapter.core.exception.ConnectionUnavailableException; import org.wso2.carbon.event.output.adapter.core.exception.ConnectionUnavailableException;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -48,8 +50,6 @@ import java.net.URL;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
/** /**
* MQTT publisher related configuration initialization and publishing capabilties are implemented here. * MQTT publisher related configuration initialization and publishing capabilties are implemented here.
@ -60,8 +60,11 @@ public class MQTTAdapterPublisher {
private MqttClient mqttClient; private MqttClient mqttClient;
private MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration; private MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration;
String clientId; String clientId;
int tenantId;
public MQTTAdapterPublisher(MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String clientId) { public MQTTAdapterPublisher(MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, String clientId
, int tenantId) {
this.tenantId = tenantId;
if (clientId == null || clientId.trim().isEmpty()) { if (clientId == null || clientId.trim().isEmpty()) {
this.clientId = MqttClient.generateClientId(); this.clientId = MqttClient.generateClientId();
} }
@ -146,7 +149,6 @@ public class MQTTAdapterPublisher {
String password = this.mqttBrokerConnectionConfiguration.getPassword(); String password = this.mqttBrokerConnectionConfiguration.getPassword();
String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl(); String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (dcrUrlString != null && !dcrUrlString.isEmpty()) { if (dcrUrlString != null && !dcrUrlString.isEmpty()) {
try { try {
URL dcrUrl = new URL(dcrUrlString); URL dcrUrl = new URL(dcrUrlString);
@ -157,8 +159,16 @@ public class MQTTAdapterPublisher {
registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE); registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE);
registrationProfile.setOwner(username); registrationProfile.setOwner(username);
registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE); registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE);
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX if (!mqttBrokerConnectionConfiguration.isGlobalCredentailSet()) {
+ mqttBrokerConnectionConfiguration.getAdapterName() + "_" + tenantId); registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
+ mqttBrokerConnectionConfiguration.getAdapterName() +
"_" + tenantId);
registrationProfile.setIsSaasApp(false);
} else {
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
+ mqttBrokerConnectionConfiguration.getAdapterName());
registrationProfile.setIsSaasApp(true);
}
String jsonString = registrationProfile.toJSON(); String jsonString = registrationProfile.toJSON();
StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
postMethod.setEntity(requestEntity); postMethod.setEntity(requestEntity);
@ -186,40 +196,34 @@ public class MQTTAdapterPublisher {
throw new OutputEventAdapterRuntimeException("Invalid dcrUrl : " + dcrUrlString); throw new OutputEventAdapterRuntimeException("Invalid dcrUrl : " + dcrUrlString);
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) { } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) {
throw new OutputEventAdapterRuntimeException("Failed to create an https connection.", e); throw new OutputEventAdapterRuntimeException("Failed to create an https connection.", e);
} catch (JWTClientException | UserStoreException e) {
log.error("Failed to create an oauth token with jwt grant type.", e);
} }
} }
throw new OutputEventAdapterRuntimeException("Invalid configuration for mqtt publisher"); throw new OutputEventAdapterRuntimeException("Invalid configuration for mqtt publisher");
} }
private String getToken(String clientId, String clientSecret) private String getToken(String clientId, String clientSecret)
throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, ParseException { throws UserStoreException, JWTClientException {
URL tokenEndpoint = new URL(mqttBrokerConnectionConfiguration.getTokenUrl()); PrivilegedCarbonContext.startTenantFlow();
HttpClient httpClient = MQTTUtil.getHttpClient(tokenEndpoint.getProtocol()); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
HttpPost postMethod = new HttpPost(tokenEndpoint.toString()); try {
String scopes = mqttBrokerConnectionConfiguration.getScopes();
List<NameValuePair> nameValuePairs = new ArrayList<>(); String username = mqttBrokerConnectionConfiguration.getUsername();
nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.GRANT_TYPE_PARAM_NAME, if (mqttBrokerConnectionConfiguration.isGlobalCredentailSet()) {
MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE)); username = PrivilegedCarbonContext.getThreadLocalCarbonContext()
nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_USERNAME, .getUserRealm().getRealmConfiguration().getAdminUserName() + "@" + PrivilegedCarbonContext
mqttBrokerConnectionConfiguration.getUsername())); .getThreadLocalCarbonContext().getTenantDomain(true);
nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_PASSWORD, }
mqttBrokerConnectionConfiguration.getPassword()));
String scopes = mqttBrokerConnectionConfiguration.getScopes();
if (scopes != null && !scopes.isEmpty()) {
nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_SCOPES, scopes));
}
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); JWTClientManagerService jwtClientManagerService =
postMethod.addHeader("Authorization", "Basic " + getBase64Encode(clientId, clientSecret)); OutputAdapterServiceDataHolder.getJwtClientManagerService();
postMethod.addHeader("Content-Type", "application/x-www-form-urlencoded"); AccessTokenInfo accessTokenInfo = jwtClientManagerService.getJWTClient().getAccessToken(
HttpResponse httpResponse = httpClient.execute(postMethod); clientId, clientSecret, username, scopes);
String response = MQTTUtil.getResponseString(httpResponse); return accessTokenInfo.getAccessToken();
if (log.isDebugEnabled()) { } finally {
log.debug(response); PrivilegedCarbonContext.endTenantFlow();
} }
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
return (String) jsonObject.get(MQTTEventAdapterConstants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME);
} }
private String getBase64Encode(String key, String value) { private String getBase64Encode(String key, String value) {

@ -33,6 +33,8 @@ public class MQTTBrokerConnectionConfiguration {
private String tokenUrl; private String tokenUrl;
private boolean cleanSession = true; private boolean cleanSession = true;
private int keepAlive; private int keepAlive;
private boolean globalCredentailSet;
public String getTokenUrl() { public String getTokenUrl() {
return tokenUrl; return tokenUrl;
} }
@ -69,11 +71,20 @@ public class MQTTBrokerConnectionConfiguration {
return adapterName; return adapterName;
} }
public boolean isGlobalCredentailSet() {
return globalCredentailSet;
}
public MQTTBrokerConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration, public MQTTBrokerConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration,
Map<String, String> globalProperties) { Map<String, String> globalProperties) {
adapterName = eventAdapterConfiguration.getName(); adapterName = eventAdapterConfiguration.getName();
this.username = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME); this.username = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME);
this.password = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD); this.password = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD);
if ((username == null || username.isEmpty()) && (password == null || password.isEmpty())) {
username = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME);
password = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD);
globalCredentailSet = true;
}
String url = eventAdapterConfiguration .getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_URL); String url = eventAdapterConfiguration .getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_URL);
if (url == null || url.isEmpty()) { if (url == null || url.isEmpty()) {
url = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_URL); url = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_URL);

@ -58,7 +58,7 @@ public final class MQTTEventAdapterConstants {
public static final String DEFAULT_CALLBACK = ""; public static final String DEFAULT_CALLBACK = "";
public static final String DEFAULT_PASSWORD = ""; public static final String DEFAULT_PASSWORD = "";
public static final String GRANT_TYPE = "password"; public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
public static final String TOKEN_SCOPE = "production"; public static final String TOKEN_SCOPE = "production";
public static final String APPLICATION_NAME_PREFIX = "OutputAdapter_"; public static final String APPLICATION_NAME_PREFIX = "OutputAdapter_";
public static final String CLIENT_ID = "clientId"; public static final String CLIENT_ID = "clientId";

@ -12,6 +12,7 @@ public class RegistrationProfile {
private String owner; private String owner;
private String grantType; private String grantType;
private String applicationType; private String applicationType;
private boolean isSaasApp;
private static final String TAG = RegistrationProfile.class.getSimpleName(); private static final String TAG = RegistrationProfile.class.getSimpleName();
@ -63,11 +64,19 @@ public class RegistrationProfile {
this.applicationType = applicationType; this.applicationType = applicationType;
} }
public String toJSON() { public boolean isSaasApp() {
return isSaasApp;
}
public void setIsSaasApp(boolean isSaasApp) {
this.isSaasApp = isSaasApp;
}
public String toJSON() {
String jsonString = String jsonString =
"{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + "\", \"tokenScope\": " + "{\"callbackUrl\": \"" + callbackUrl + "\",\"clientName\": \"" + clientName + "\", \"tokenScope\": " +
"\"" + tokenScope + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType + "\"" + tokenScope + "\", \"owner\": \"" + owner + "\"," + "\"grantType\": \"" + grantType +
"\", \"saasApp\" :false }\n"; "\", \"saasApp\" : " + isSaasApp + " }\n";
return jsonString; return jsonString;
} }
} }

@ -110,6 +110,28 @@
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>unpack-analytics</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.analytics</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution> <execution>
<id>unpack-geo</id> <id>unpack-geo</id>
<phase>package</phase> <phase>package</phase>

@ -57,10 +57,7 @@
<!--if file based properties is set to false then the configuration will be picked from platform configuration--> <!--if file based properties is set to false then the configuration will be picked from platform configuration-->
<ConfigProperties> <ConfigProperties>
<Property Name="mqttAdapterName">androidsense.mqtt.adapter</Property> <Property Name="mqttAdapterName">androidsense.mqtt.adapter</Property>
<Property Name="username">admin</Property>
<Property Name="password">admin</Property>
<Property Name="qos">0</Property> <Property Name="qos">0</Property>
<Property Name="scopes"/>
<Property Name="clearSession">true</Property> <Property Name="clearSession">true</Property>
</ConfigProperties> </ConfigProperties>
</PushNotificationProvider> </PushNotificationProvider>

@ -113,6 +113,28 @@
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>unpack-analytics</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.analytics</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution> <execution>
<id>copy-jaxrs-war</id> <id>copy-jaxrs-war</id>
<phase>package</phase> <phase>package</phase>

@ -133,6 +133,28 @@
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>unpack-analytics</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.analytics</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions> </executions>
</plugin> </plugin>

@ -39,10 +39,7 @@
<!--if file based properties is set to false then the configuration will be picked from platform configuration--> <!--if file based properties is set to false then the configuration will be picked from platform configuration-->
<ConfigProperties> <ConfigProperties>
<Property Name="mqttAdapterName">raspberrypi.mqtt.adapter</Property> <Property Name="mqttAdapterName">raspberrypi.mqtt.adapter</Property>
<Property Name="username">admin</Property>
<Property Name="password">admin</Property>
<Property Name="qos">0</Property> <Property Name="qos">0</Property>
<Property Name="scopes"/>
<Property Name="clearSession">true</Property> <Property Name="clearSession">true</Property>
</ConfigProperties> </ConfigProperties>
</PushNotificationProvider> </PushNotificationProvider>

@ -162,6 +162,28 @@
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>unpack-analytics</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.analytics</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions> </executions>
</plugin> </plugin>

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<DeviceManagementConfiguration>
<EventListenerConfiguration>
<!--MQTT Config-->
<EventListenerProvider>MQTT</EventListenerProvider>
<Properties>
<Property Name="mqttAdapterName">virtualfirealarm.mqtt.adapter</Property>
<Property Name="username">admin</Property>
<Property Name="password">admin</Property>
<Property Name="qos">0</Property>
<Property Name="scopes"/>
<Property Name="clearSession">true</Property>
</Properties>
<!--XMPP Config-->
<!--PushNotificationProvider>XMPP</PushNotificationProvider>
<Properties>
<Property Name="xmpp.adapter.name">virtualfirealarm.xmpp.adapter</Property>
<Property Name="host">localhost</Property>
<Property Name="port">5222</Property>
<Property Name="username">admin</Property>
<Property Name="password">admin</Property>
<Property Name="jid">admin@localhost</Property>
<Property Name="server.name">localhost</Property>
</Properties-->
</EventListenerConfiguration>
</DeviceManagementConfiguration>

@ -31,7 +31,7 @@
</Features> </Features>
<ProvisioningConfig> <ProvisioningConfig>
<SharedWithAllTenants>false</SharedWithAllTenants> <SharedWithAllTenants>true</SharedWithAllTenants>
</ProvisioningConfig> </ProvisioningConfig>
<PushNotificationProvider type="MQTT"> <PushNotificationProvider type="MQTT">
@ -39,10 +39,7 @@
<!--if file based properties is set to false then the configuration will be picked from platform configuration--> <!--if file based properties is set to false then the configuration will be picked from platform configuration-->
<ConfigProperties> <ConfigProperties>
<Property Name="mqttAdapterName">virtualfirealarm.mqtt.adapter</Property> <Property Name="mqttAdapterName">virtualfirealarm.mqtt.adapter</Property>
<Property Name="username">admin</Property>
<Property Name="password">admin</Property>
<Property Name="qos">0</Property> <Property Name="qos">0</Property>
<Property Name="scopes"/>
<Property Name="clearSession">true</Property> <Property Name="clearSession">true</Property>
</ConfigProperties> </ConfigProperties>
</PushNotificationProvider> </PushNotificationProvider>

@ -20,7 +20,6 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/device-types/);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/devicetypes/);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/devicetypes/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/devicetypes/,target:${installFolder}/../../deployment/server/devicetypes/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/devicetypes/,target:${installFolder}/../../deployment/server/devicetypes/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/etc/device-mgt-plugins/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/carbonapps/,target:${installFolder}/../../resources/devicetypes/virtual_firealarm/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/carbonapps/,target:${installFolder}/../../resources/devicetypes/virtual_firealarm/,overwrite:true);\

Loading…
Cancel
Save