Skip to content

Commit

Permalink
Implement Stop the subscription to message notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
Sidath Weerasinghe committed Mar 16, 2017
1 parent 457659c commit b4f10ac
Show file tree
Hide file tree
Showing 10 changed files with 341 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public String saveSendSMSTransaction(String senderAddress, String addresses, Str
String status, Integer txntype, String criteria, String notificationFormat, User user,
String deliveryStatus) ;
public List<SendSMSToApplication> getMessageInbound(String regid, Integer userid);
public int saveSubscribeSMSRequest(String destinationAddress, String notifyURL, String callbackData, String criteria, String clientCorrelator, User user) throws Exception;
public int saveSubscribeSMSRequest(SubscribeSMSRequest subscribeSMSRequest) throws Exception;

public boolean removeSubscriptionToMessage(String subscriptionID) throws Exception;
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.hibernate.Transaction;

import com.wso2telco.services.dep.sandbox.dao.SMSMessagingDAO;
import org.hibernate.query.Query;

class HibernateSMSMessagingDAO extends HibernateCommonDAO implements SMSMessagingDAO{

Expand Down Expand Up @@ -125,44 +126,63 @@ public List<SendSMSToApplication> getMessageInbound(String registrationID, Integ
}

@Override
public int saveSubscribeSMSRequest(String destinationAddress, String notifyURL, String callbackData, String
criteria, String clientCorrelator, User user) throws Exception {

public int saveSubscribeSMSRequest(SubscribeSMSRequest SubscribeSMSRequest) throws Exception {

Session session = null;
Transaction transaction = null;
Integer subsid = null;

try {

session = getSession();
transaction = session.beginTransaction();

SubscribeSMSRequest subscribeSMSRequest = new SubscribeSMSRequest();
subscribeSMSRequest.setCallbackData(callbackData);
subscribeSMSRequest.setClientCorrelator(clientCorrelator);
subscribeSMSRequest.setCriteria(criteria);
subscribeSMSRequest.setDestinationAddress(destinationAddress);
subscribeSMSRequest.setNotifyURL(notifyURL);
subscribeSMSRequest.setUser(user);
subscribeSMSRequest.setDate(new Date());
subscribeSMSRequest.setNotificationFormat("JSON");
session.save(subscribeSMSRequest);
subsid = subscribeSMSRequest.getSubscribeId();

session.save(SubscribeSMSRequest);
subsid = SubscribeSMSRequest.getSubscribeId();
transaction.commit();

} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
} finally {
LOG.error("Error occurred When save subscribe SMS request",e);
throw e;

} finally {
session.close();
}

return subsid;

}

@Override
public boolean removeSubscriptionToMessage(String subscriptionID) throws Exception {

boolean isExists = false;
Session session = null;
Transaction transaction = null;

try {
session = getSession();
transaction = session.beginTransaction();
Query query= session.createQuery("delete FROM SubscribeSMSRequest WHERE subscribe_id = :id");
query.setInteger("id", Integer.parseInt(subscriptionID));
int i = query.executeUpdate();

if (i >0) {
isExists = true;
}
transaction.commit();

} catch (Exception e) {
transaction.rollback();
LOG.error("Error occurred when remove subscription to message",e);
throw e;

} finally {
session.close();
}

return isExists;
}


public boolean saveQueryDeliveryStatusTransaction(String senderAddress, String addresses, String message,
String clientCorrelator, String senderName, String notifyURL, String callbackData, Integer batchsize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@
@Path("smsmessaging")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/v1_2/sms", description = "sms")
@Api(value = "/v1_2/sms", description = " Rest Service for SMS API")
public class SmsServiceGateway {

Log LOG = LogFactory.getLog(SmsServiceGateway.class);

@POST
@Path("/v1_2/outbound/{shortCode}/requests")
@ApiOperation(value = "sms", notes = "Send SMS service in Gateway", response = Response.class)
@ApiOperation(value = "Send SMS Service", notes = "Send SMS service in Gateway", response = Response.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "sandbox", value = "Authorization token",
required = true, dataType = "string", paramType = "header")
Expand All @@ -67,18 +67,17 @@ public Response handleSendMTSMSRequest(@Context HttpServletRequest httpRequest,
returnable = handler.execute(requestDTO);
return Response.status(returnable.getHttpStatus()).entity(returnable.getResponse()).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.BAD_REQUEST).entity(returnable.getResponse()).build();
}
}


@GET
@Path("/v1_2/inbound/registrations/{registrationId}/messages")
@ApiOperation(value = "SMS Service", notes = "SMS Service", response = Response.class)
@ApiOperation(value = "Receiving SMS Service", notes = "Receiving SMS API", response = Response.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "sandbox", value = "Authorization token", required = true, dataType = "string", paramType = "header") })
public Response location(
public Response ReceivingSMS(
@ApiParam(value = "registrationId", required = true) @PathParam("registrationId") String registrationID, @ApiParam(value = "maxBatchSize", required = true) @QueryParam("maxBatchSize") int maxBatchSize,
@Context HttpServletRequest request) {

Expand Down Expand Up @@ -111,7 +110,7 @@ public Response location(

@POST
@Path("/v1_2/inbound/subscriptions")
@ApiOperation(value = "sms", notes = "SMS subscriptions service in Gateway", response = Response.class)
@ApiOperation(value = "Subscribe to Notifications of Messages Sent to Your Application Service", notes = "SMS subscriptions service in Gateway", response = Response.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "sandbox", value = "Authorization token",
required = true, dataType = "string", paramType = "header")
Expand All @@ -131,9 +130,38 @@ public Response subscribeToApplication(@Context HttpServletRequest httpRequest,
returnable = handler.execute(requestDTO);
return Response.status(returnable.getHttpStatus()).entity(returnable.getResponse()).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.BAD_REQUEST).entity(returnable.getResponse()).build();
}
}



@DELETE
@Path("/v1_2/inbound/subscriptions/{subscriptionID}")
@ApiOperation(value = "Stop the Subscription to Message Notifications", notes = "SMS subscriptions service in Gateway", response = Response.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "sandbox", value = "Authorization token",
required = true, dataType = "string", paramType = "header")
})
public Response deleteSubscribeToApplication(@ApiParam(value = "subscriptionID", required = true) @PathParam("subscriptionID") String subscriptionID,@Context HttpServletRequest httpRequest) {

StopSubscriptionMessageNotificationRequestWrapper requestDTO = new StopSubscriptionMessageNotificationRequestWrapper();
requestDTO.setHttpRequest(httpRequest);
requestDTO.setRequestType(RequestType.SMSMESSAGING);
requestDTO.setApiVersion("v1_2");
requestDTO.setSubscriptionID(subscriptionID);
RequestHandleable handler = RequestBuilderFactoryGateway.getInstance(requestDTO);
Returnable returnable = null;

try {

returnable = handler.execute(requestDTO);
return Response.status(returnable.getHttpStatus()).entity(returnable.getResponse()).build();
} catch (Exception e) {
return Response.status(Response.Status.BAD_REQUEST).entity(returnable.getResponse()).build();
}
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ protected Returnable process(ReceivingSMSRequestWrapperGateway extendedRequestDT
responseBean.setTotalNumberOfPendingMessages(smsMessageList.size()-maxBatchSize);

responseWrapper.setReceivingSMSResponseBean(responseBean);
responseWrapper.setHttpStatus(Response.Status.CREATED);
responseWrapper.setHttpStatus(Response.Status.OK);

// Save Success Response
saveResponse(registrationId, responseBean, apiServiceCalls, MessageProcessStatus.Success);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ else if (requestDTO.getRequestPath().toLowerCase().contains(SUBSCRIPTIONS)

return new SubscribeApplicationNotificationsHandler();
}

else if (requestDTO.getRequestPath().toLowerCase().contains(SUBSCRIPTIONS)
&& requestDTO.isDelete()) {
LOG.debug("LOADING SUBSCRIPTIONS SMS SERVICE");

return new StopSubscriptionMessageNotificationHandler();
}

else {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*******************************************************************************
* Copyright (c) 2015-2017, WSO2.Telco Inc. (http://www.wso2telco.com)
*
* All Rights Reserved. WSO2.Telco Inc. licences 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.
******************************************************************************/
package com.wso2telco.services.dep.sandbox.servicefactory.smsmessaging.gateway;


import com.google.gson.Gson;
import com.wso2telco.core.dbutils.exception.ServiceError;
import com.wso2telco.dep.oneapivalidation.exceptions.CustomException;
import com.wso2telco.dep.oneapivalidation.util.Validation;
import com.wso2telco.dep.oneapivalidation.util.ValidationRule;
import com.wso2telco.services.dep.sandbox.dao.DaoFactory;
import com.wso2telco.services.dep.sandbox.dao.SMSMessagingDAO;
import com.wso2telco.services.dep.sandbox.dao.model.domain.APIServiceCalls;
import com.wso2telco.services.dep.sandbox.dao.model.domain.APITypes;
import com.wso2telco.services.dep.sandbox.dao.model.domain.MessageLog;
import com.wso2telco.services.dep.sandbox.servicefactory.*;
import com.wso2telco.services.dep.sandbox.util.ServiceName;
import org.apache.commons.logging.LogFactory;

import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StopSubscriptionMessageNotificationHandler extends AbstractRequestHandler<StopSubscriptionMessageNotificationRequestWrapper> implements AddressIgnorerable {


private StopSubscriptionMessageNotificationRequestWrapper requestWrapper;
private StopSubscriptionMessageNotificationResponseWrapper responseWrapper;
private SMSMessagingDAO smsMessagingDAO;


{
LOG = LogFactory.getLog(StopSubscriptionMessageNotificationHandler.class);
smsMessagingDAO = DaoFactory.getSMSMessagingDAO();
}

@Override
protected Returnable getResponseDTO() {
return responseWrapper;
}

@Override
protected List<String> getAddress() {
return null;
}

@Override
protected boolean validate(StopSubscriptionMessageNotificationRequestWrapper wrapperDTO) throws Exception {

String subscriptionID = wrapperDTO.getSubscriptionID();

List<ValidationRule> validationRulesList = new ArrayList<>();

try {
validationRulesList.add(new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY, "subscriptionID", subscriptionID));
ValidationRule[] validationRules = new ValidationRule[validationRulesList.size()];
validationRules = validationRulesList.toArray(validationRules);
Validation.checkRequestParams(validationRules);

} catch (CustomException ex) {
LOG.error("###SMS### Error in Validations. ", ex);
responseWrapper.setRequestError(
constructRequestError(SERVICEEXCEPTION, ex.getErrcode(), ex.getErrmsg(), ex.getErrvar()[0]));
responseWrapper.setHttpStatus(Response.Status.BAD_REQUEST);
return false;
}
return true;
}


@Override
protected Returnable process(StopSubscriptionMessageNotificationRequestWrapper extendedRequestDTO) throws Exception {

String subscriptionID = extendedRequestDTO.getSubscriptionID();

APITypes apiTypes = dao.getAPIType(extendedRequestDTO.getRequestType().toString().toLowerCase());
String serviceCallPayment = ServiceName.SubscribeToApplication.toString();
APIServiceCalls apiServiceCalls = dao.getServiceCall(apiTypes.getId(), serviceCallPayment);


boolean delete = smsMessagingDAO.removeSubscriptionToMessage(subscriptionID);
if (delete) {
responseWrapper.setStatus("NO CONTENT");
responseWrapper.setHttpStatus(Response.Status.NO_CONTENT);

// Save Success Response
saveResponse(subscriptionID, apiServiceCalls, MessageProcessStatus.Success);

} else {
LOG.error("###SMS SUBSCRIPTION### NO Subscriber found");
responseWrapper.setRequestError(constructRequestError(SERVICEEXCEPTION,
ServiceError.INVALID_INPUT_VALUE, "NO Subscriber found"));
responseWrapper.setHttpStatus(Response.Status.BAD_REQUEST);

}
return responseWrapper;
}

@Override
protected void init(StopSubscriptionMessageNotificationRequestWrapper extendedRequestDTO) throws Exception {

responseWrapper = new StopSubscriptionMessageNotificationResponseWrapper();
this.requestWrapper = extendedRequestDTO;

}


private void saveResponse(String subscriptionID, APIServiceCalls apiServiceCalls, MessageProcessStatus status) throws Exception {

String jsonString = "Stop the subscription to subscriptionID: "+subscriptionID;

//setting messagelog responses
new MessageLog();
MessageLog messageLog;
messageLog = new MessageLog();
messageLog.setRequest(jsonString);
messageLog.setStatus(status.getValue());
messageLog.setType(MessageType.Response.getValue());
messageLog.setServicenameid(apiServiceCalls.getApiServiceCallId());
messageLog.setUserid(user.getId());
messageLog.setReference("subscriptionID");
messageLog.setValue(subscriptionID);
messageLog.setMessageTimestamp(new Date());

loggingDAO.saveMessageLog(messageLog);
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*******************************************************************************
* Copyright (c) 2015-2017, WSO2.Telco Inc. (http://www.wso2telco.com)
*
* All Rights Reserved. WSO2.Telco Inc. licences 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.
******************************************************************************/
package com.wso2telco.services.dep.sandbox.servicefactory.smsmessaging.gateway;


import com.wso2telco.services.dep.sandbox.dao.model.custom.RequestDTO;

public class StopSubscriptionMessageNotificationRequestWrapper extends RequestDTO {

private String subscriptionID;

public String getSubscriptionID() {
return subscriptionID;
}

public void setSubscriptionID(String subscriptionID) {
this.subscriptionID = subscriptionID;
}
}
Loading

0 comments on commit b4f10ac

Please sign in to comment.