we have a message campaign where we send over 100k messages (SMS) a day. So we are a client of SMSC server. We have no influence on SMSC server code. Before some time, we had around 80-90 message per second, now frequency dropped to 15 messages per second, according to tcpdumps.
I have few information regarding this, so I will try to explain best as I can.
So we are using Spring Boot 2.7 and open source jsmpp (3.0.0) library for sending SMS messages (PDU commands) to SMSC.
While reading about protocol (page 40), I noticed that there is a way to send messages asynchronously by providing a seqence_number. The code example is here. But I am not sure if that is going to help...
The code:
#Component
public class ClientConfig {
#Autowired
private MessageReceiverListener msgListener;
#Autowired
private SessionStateListener sessionListener;
private SMPPSession session;
public String charset = "ISO-10646-UCS-2";
public long idleReceiveTimeout = 65000;
public long checkBindingTimeout = 12000;
public long timeout = 7000;
public int enquireLinkTimeout = 15000;
public String hostIp = "someIpAddress";
public int port = 5000;
public String final systemId = "someSystemId";
public String final password = "password";
public BindType bindType = BindType.BIND_TRX; //transceiver
public String systemType = null;
public String addressRange = null;
public TypeOfNumber addrTon = TypeOfNumber.UNKNOWN;
public NumberingPlanIndicator addrNpi = NumberingPlanIndicator.UNKNOWN;
protected synchronized void tryToConnectToSmsc() throws Exception {
try {
// Connect to host
BindParameter bp = new BindParameter(bindType, systemId, password, systemType, addrTon, addrNpi, addressRange);
session = new SMPPSession();
session.setEnquireLinkTimer(enquireLinkTimer);
session.connectAndBind(host, port, bp, timeout);
session.setMessageReceiverListener(msgListener);
session.addSessionStateListener(sessionListener);
}
// Main connection failed.
catch (Exception e) {
//log and re-attempt connection logic here
}
}
}
The listeners:
#Component
public class MySessionListenerImpl implements SessionStateListener {
#Override
public void onStateChange(SessionState newState, SessionState oldState, Session source) {
//TODO
}
}
#Service
public class SmsListenerImpl implements MessageReceiverListener {
#Override
public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException {
//TODO
}
#Override
public void onAcceptAlertNotification(AlertNotification alertNotification) {}
#Override
public DataSmResult onAcceptDataSm(DataSm dataSm, Session session) throws ProcessRequestException {
return null;
}
}
Message sending service:
#Service
public class MessageSendingServiceImpl extends ClientConfig implements MessageSendingService{
private final ESMClass esmClass = new ESMClass();
private final byte protocolId = (byte) 0;
private final byte priorityFlag = (byte) 1;
private final TimeFormatter formatter = new AbsoluteTimeFormatter();
private final byte defaultMsgId = (byte) 0;
public SmsAdapterServiceImpl() {
super();
}
#PostConstruct
public synchronized void init() throws Exception {
super.tryToConnectToSmsc();
}
#Override
public String send(DomainObject obj){ //DomainObject -> contains fields: id, to, from, text, delivery, validity;
String serviceType = null;
//source
TypeOfNumber sourceTON = TypeOfNumber.NATIONAL; //there is some logic here which determines if it is INTERNATIOANL, ALPHANUMERIC etc...
NumberPlaningIndicator sourceNpi = NumberPlaningIndicator.ISDN; //constant...
String sourcePhone = obj.getFrom();
//destination
TypeOfNumber destinationTON = TypeOfNumber.NATIONAL; //there is some logic here which determines if it is INTERNATIOANL, ALPHANUMERIC etc...
NumberPlaningIndicator destinationNpi = NumberPlaningIndicator.ISDN; //constant...
String destinationPhone = obj.getTo();
String scheduledDeliveryTime = null;
if (obj.getDelivery() != null) scheduledDeliveryTime = formatter.format(obj.getDelivery());
String validityPeriodTime = null;
if (obj.getValidity() != null) validityPeriodTime = formatter.format(obj.getValidity());
Map<Short, OptionalParameter> optionalParameters = new HashMap<>();
String text = obj.getText();
if ( text.length() > 89 ) { //set text as payload instead of message text
OctetString os = new OctetString(OptionalParameter.Tag.MESSAGE_PAYLOAD.code(), text, "ISO-10646-UCS-2"); //"ISO-10646-UCS-2" - encoding
optionalParameters.put(os.tag, os);
text = "";
}
String msgId =
session.submitShortMessage( serviceType ,
sourceTON ,
sourceNpi ,
sourcePhone ,
destinationTON ,
destinationNpi ,
destinationPhone ,
esmClass ,
protocolId ,
priorityFlag ,
scheduledDeliveryTime ,
validityPeriodTime ,
new RegisteredDelivery() ,
ReplaceIfPresentFlag.DEFAULT.value() ,
new GeneralDataCoding(Alphabet.ALPHA_UCS2) ,
defaultMsgId ,
text.getBytes("ISO-10646-UCS-2") ,
optionalParameters.values().toArray(new OptionalParameter[0]));
return msgId;
}
}
Client code which invokes the service (it is actually a scheduler job):
#Autowired private MessageSendingService messageSendingService;
#Scheduled(cron)
public void execute() {
List<DomainObject> messages = repository.findMessages(pageable, config.getBatch()); //up to several thousand
start(messages);
ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(getSchedulerConfiguration().getPoolSize(), new NamedThreadFactory("Factory"));
List<DomainObject> domainObjects = Collections.synchronizedList(messages);
List<List<DomainObject>> domainObjectsPartitioned = partition(domainObjects.size(), config.getPoolSize()); //pool size is 4
for (List<DomainObject> list: domainObjectsPartitioned ) {
executorService.execute(new Runnable() {
#Override
public void run() {
try {
start(list);
} catch (Exception e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
}
}
private void start(List<DomainObject> list){
for (DomainObject> obj : list) {
String mid = messageSendingService.send(obj);
//do smtg with id...
}
}
i have 3rd party smpp connection.
so i created java smpp client and its working fine.
how i can create smpp server connect to 3rd party smpp connection and need to send sms via that created smpp server. my problem is i doesn't know how to connect smpp server to smsc/smpp 3rd party connection
please help to me connect this smpp server to smpp 3rd party server for send sms..
public class SMPPServerSimulator extends ServerResponseDeliveryAdapter implements Runnable, ServerMessageReceiverListener {
private static final Logger log = LoggerFactory.getLogger(SMPPServerSimulator.class);
private static final String QUERYSM_NOT_IMPLEMENTED = "query_sm not implemented";
private static final String CANCELSM_NOT_IMPLEMENTED = "cancel_sm not implemented";
private static final String DATASM_NOT_IMPLEMENTED = "data_sm not implemented";
private static final String REPLACESM_NOT_IMPLEMENTED = "replace_sm not implemented";
private static final String BROADCASTSM_NOT_IMPLEMENTED = "broadcast_sm not implemented";
private static final String CANCELBROADCASTSM_NOT_IMPLEMENTED = "cancel_broadcast_sm not implemented";
private static final String QUERYBROADCASTSM_NOT_IMPLEMENTED = "query_broadcast_sm not implemented";
private static final Integer DEFAULT_PORT = 2775;
private static final String DEFAULT_SYSID = "twtest";
private static final String DEFAULT_PASSWORD = "test123";
private static final String SMSC_SYSTEMID = "sys";
private final ExecutorService execService = Executors.newFixedThreadPool(5);
private final ExecutorService execServiceDelReceipt = Executors.newFixedThreadPool(100);
private final MessageIDGenerator messageIDGenerator = new RandomMessageIDGenerator();
private final boolean useSsl;
private final int port;
private final String systemId;
private final String password;
public SMPPServerSimulator(boolean useSsl, int port, String systemId, String password) {
this.useSsl = useSsl;
this.port = port;
this.systemId = systemId;
this.password = password;
}
#Override
public void run() {
boolean running = true;
/*
* for SSL use the SSLServerSocketConnectionFactory() or DefaultSSLServerSocketConnectionFactory()
*/
try (SMPPServerSessionListener sessionListener = useSsl ?
new SMPPServerSessionListener(port, new KeyStoreSSLServerSocketConnectionFactory())
: new SMPPServerSessionListener(port)) {
/*
* for SSL use the SSLServerSocketConnectionFactory() or DefaultSSLServerSocketConnectionFactory()
*/
log.info("Listening on port {}{}", port, useSsl ? " (SSL)" : "");
while (running) {
System.out.println("running");
SMPPServerSession serverSession = sessionListener.accept();
log.info("Accepted connection with session {}", serverSession.getSessionId());
serverSession.setMessageReceiverListener(this);
serverSession.setResponseDeliveryListener(this);
Future<Boolean> bindResult = execService.submit(new WaitBindTask(serverSession, 30000, systemId, password));
try {
boolean bound = bindResult.get();
System.out.println(bound+" sss");
if (bound) {
// Could start deliver_sm to ESME
log.info("The session is now in state {}", serverSession.getSessionState());
serverSession.deliverShortMessage("CMT",
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.ISDN, "94712320529",
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.ISDN, "TWTEST",
new ESMClass(0), (byte) 0x00, (byte) 0x00, new RegisteredDelivery(), DataCodings.ZERO,
"Hello Worldxxxxxxxxxxx".getBytes());
}
} catch (InterruptedException e){
log.info("Interrupted WaitBind task: {}", e.getMessage());
Thread.currentThread().interrupt();
running = false;
} catch (ExecutionException e){
log.info("Exception on execute WaitBind task: {}", e.getMessage());
running = false;
} catch (NegativeResponseException | ResponseTimeoutException | PDUException | InvalidResponseException e){
log.info("Could not send deliver_sm: {}", e.getMessage());
}
}
} catch (IOException e) {
log.error("IO error occurred", e);
}
}
#Override
public QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException {
log.info("QuerySm not implemented");
throw new ProcessRequestException(QUERYSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RINVCMDID);
}
#Override
public SubmitSmResult onAcceptSubmitSm(SubmitSm submitSm,
SMPPServerSession source) throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.info("Receiving submit_sm '{}', and return message id {}", new String(submitSm.getShortMessage()), messageId);
if (SMSCDeliveryReceipt.FAILURE.containedIn(submitSm.getRegisteredDelivery()) || SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitSm.getRegisteredDelivery())) {
execServiceDelReceipt.execute(new DeliveryReceiptTask(source, submitSm, messageId));
}
/*
* SMPP 5.0 allows the following optional parameters (SMPP 5.0 paragraph 4.2.5):
* additional_status_info_text, delivery_failure_reason, dpf_result, network_error_code
* Add the congestionState for SMPP 5.0 connections.
*/
if (source.getInterfaceVersion().value() >= InterfaceVersion.IF_50.value()) {
final int congestionRatio = source.getCongestionRatio();
OptionalParameter.Congestion_state congestionState = new OptionalParameter.Congestion_state((byte) congestionRatio);
return new SubmitSmResult(messageId, new OptionalParameter[]{ congestionState });
}
return new SubmitSmResult(messageId, new OptionalParameter[0]);
}
#Override
public void onSubmitSmRespSent(SubmitSmResult submitSmResult,
SMPPServerSession source) {
log.debug("submit_sm_resp with message_id {} has been sent", submitSmResult.getMessageId());
}
#Override
public SubmitMultiResult onAcceptSubmitMulti(SubmitMulti submitMulti, SMPPServerSession source)
throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.debug("Receiving submit_multi_sm '{}', and return message id {}",
new String(submitMulti.getShortMessage()), messageId);
if (SMSCDeliveryReceipt.FAILURE.containedIn(submitMulti.getRegisteredDelivery())
|| SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitMulti.getRegisteredDelivery())) {
execServiceDelReceipt.execute(new DeliveryReceiptTask(source, submitMulti, messageId));
}
/*
* SMPP 5.0 allows the following optional parameters (SMPP 5.0 paragraph 4.2.5):
* additional_status_info_text, delivery_failure_reason, dpf_result, network_error_code
* Add the congestionState for SMPP 5.0 connections.
*/
if (source.getInterfaceVersion().value() >= InterfaceVersion.IF_50.value()) {
final int congestionRatio = source.getCongestionRatio();
OptionalParameter.Congestion_state congestionState = new OptionalParameter.Congestion_state((byte) congestionRatio);
return new SubmitMultiResult(messageId.getValue(), new UnsuccessDelivery[0], new OptionalParameter[]{ congestionState });
}
return new SubmitMultiResult(messageId.getValue(), new UnsuccessDelivery[0], new OptionalParameter[0]);
}
#Override
public DataSmResult onAcceptDataSm(DataSm dataSm, Session source)
throws ProcessRequestException {
log.info("Accepting data_sm, but not implemented");
throw new ProcessRequestException(DATASM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RSYSERR);
}
#Override
public void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting cancel_sm, but not implemented");
throw new ProcessRequestException(CANCELSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RCANCELFAIL);
}
#Override
public void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting replace_sm, but not implemented");
throw new ProcessRequestException(REPLACESM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RREPLACEFAIL);
}
#Override
public BroadcastSmResult onAcceptBroadcastSm(final BroadcastSm broadcastSm, final SMPPServerSession source)
throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.debug("Receiving broadcast_sm '{}', and return message id {}",
new String(broadcastSm.getOptionalParameter(OptionalParameter.Tag.MESSAGE_PAYLOAD).serialize()), messageId);
return new BroadcastSmResult(messageId, new OptionalParameter[0]);
}
#Override
public void onAcceptCancelBroadcastSm(final CancelBroadcastSm cancelBroadcastSm, final SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting cancel_broadcast_sm, but not implemented");
throw new ProcessRequestException(CANCELBROADCASTSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RBCASTCANCELFAIL);
}
#Override
public QueryBroadcastSmResult onAcceptQueryBroadcastSm(final QueryBroadcastSm queryBroadcastSm,
final SMPPServerSession source) throws ProcessRequestException {
log.info("Accepting query_broadcast_sm, but not implemented");
throw new ProcessRequestException(QUERYBROADCASTSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RBCASTQUERYFAIL);
}
private static class WaitBindTask implements Callable<Boolean> {
private final SMPPServerSession serverSession;
private final long timeout;
private final String systemId;
private final String password;
public WaitBindTask(SMPPServerSession serverSession, long timeout, String systemId, String password) {
this.serverSession = serverSession;
this.timeout = timeout;
this.systemId = systemId;
this.password = password;
}
#Override
public Boolean call() {
try {
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
BindRequest bindRequest = serverSession.waitForBind(timeout);
try {
if (BindType.BIND_TRX.equals(bindRequest.getBindType())) {
if (systemId.equals(bindRequest.getSystemId())) {
if (password.equals(bindRequest.getPassword())) {
log.info("Accepting bind for session {}, interface version {}", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
serverSession.setInterfaceVersion(InterfaceVersion.IF_50.min(bindRequest.getInterfaceVersion()));
// The systemId identifies the SMSC to the ESME.
bindRequest.accept(SMSC_SYSTEMID, InterfaceVersion.IF_50);
return true;
} else {
log.info("Rejecting bind for session {}, interface version {}, invalid password", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RINVPASWD);
}
} else {
log.info("Rejecting bind for session {}, interface version {}, invalid system id", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RINVSYSID);
}
} else {
log.info("Rejecting bind for session {}, interface version {}, only accept transceiver", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RBINDFAIL);
}
} catch (PDUStringException e) {
log.error("Invalid system id: " + SMSC_SYSTEMID, e);
bindRequest.reject(SMPPConstant.STAT_ESME_RSYSERR);
}
} catch (IllegalStateException e) {
log.error("System error", e);
} catch (TimeoutException e) {
log.warn("Wait for bind has reach timeout", e);
} catch (IOException e) {
log.error("Failed accepting bind request for session {}", serverSession.getSessionId());
}
return false;
}
}
private static class DeliveryReceiptTask implements Runnable {
private final SMPPServerSession session;
private final MessageId messageId;
private final TypeOfNumber sourceAddrTon;
private final NumberingPlanIndicator sourceAddrNpi;
private final String sourceAddress;
private final TypeOfNumber destAddrTon;
private final NumberingPlanIndicator destAddrNpi;
private final String destAddress;
private final int totalSubmitted;
private final int totalDelivered;
private final byte[] shortMessage;
public DeliveryReceiptTask(SMPPServerSession session,
SubmitSm submitSm, MessageId messageId) {
this.session = session;
this.messageId = messageId;
// reversing destination to source
sourceAddrTon = TypeOfNumber.valueOf(submitSm.getDestAddrTon());
sourceAddrNpi = NumberingPlanIndicator.valueOf(submitSm.getDestAddrNpi());
sourceAddress = submitSm.getDestAddress();
// reversing source to destination
destAddrTon = TypeOfNumber.valueOf(submitSm.getSourceAddrTon());
destAddrNpi = NumberingPlanIndicator.valueOf(submitSm.getSourceAddrNpi());
destAddress = submitSm.getSourceAddr();
totalSubmitted = totalDelivered = 1;
shortMessage = submitSm.getShortMessage();
}
public DeliveryReceiptTask(SMPPServerSession session,
SubmitMulti submitMulti, MessageId messageId) {
this.session = session;
this.messageId = messageId;
// set to unknown and null, since it was submit_multi
sourceAddrTon = TypeOfNumber.UNKNOWN;
sourceAddrNpi = NumberingPlanIndicator.UNKNOWN;
sourceAddress = null;
// reversing source to destination
destAddrTon = TypeOfNumber.valueOf(submitMulti.getSourceAddrTon());
destAddrNpi = NumberingPlanIndicator.valueOf(submitMulti.getSourceAddrNpi());
destAddress = submitMulti.getSourceAddr();
// distribution list assumed only contains single address
totalSubmitted = totalDelivered = submitMulti.getDestAddresses().length;
shortMessage = submitMulti.getShortMessage();
}
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("Interrupted", e);
//re-interrupt the current thread
Thread.currentThread().interrupt();
}
SessionState state = session.getSessionState();
if (!state.isReceivable()) {
log.debug("Not sending delivery receipt for message id {} since session state is {}", messageId, state);
return;
}
String stringValue = Integer.valueOf(messageId.getValue(), 16).toString();
try {
DeliveryReceipt delRec = new DeliveryReceipt(stringValue, totalSubmitted, totalDelivered, new Date(), new Date(), DeliveryReceiptState.DELIVRD, "000", new String(shortMessage));
session.deliverShortMessage(
"mc",
sourceAddrTon, sourceAddrNpi, sourceAddress,
destAddrTon, destAddrNpi, destAddress,
new ESMClass(MessageMode.DEFAULT, MessageType.SMSC_DEL_RECEIPT, GSMSpecificFeature.DEFAULT),
(byte)0,
(byte)0,
new RegisteredDelivery(0),
DataCodings.ZERO,
delRec.toString().getBytes());
log.debug("Sending delivery receipt for message id {}: {}", messageId, stringValue);
} catch (Exception e) {
log.error("Failed sending delivery_receipt for message id " + messageId + ":" + stringValue, e);
}
}
}
public static void main(String[] args) {
// System.setProperty("javax.net.debug", "ssl");
/*
* To use SSL, add -Djsmpp.simulator.ssl=true
* To debug SSL, add -Djavax.net.debug=ssl
*/
String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID);
String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD);
int port;
try {
port = Integer.parseInt(System.getProperty("jsmpp.simulator.port", DEFAULT_PORT.toString()));
} catch (NumberFormatException e) {
port = DEFAULT_PORT;
}
boolean useSsl = Boolean.parseBoolean(System.getProperty("jsmpp.simulator.ssl", "false"));
SMPPServerSimulator smppServerSim = new SMPPServerSimulator(useSsl, port, systemId, password);
smppServerSim.run();
}
}
I have the method:
public HTTPResult get(String url) throws Exception{
try {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return new HTTPResult(response.getBody(), response.getStatusCode().value());
}
catch (ResourceAccessException e) {
String responseBody = e.getCause().getMessage();
JSONObject obj = new JSONObject(responseBody);
return new HTTPResult(obj.getString("responseBody"), Integer.parseInt(obj.getString("statusCode")));
}
}
I want to do unit testing for it and i am not sure how to proceed:
public class MockHttpServerTest {
private static final int PORT = 51234;
private static final String baseUrl = "http://localhost:" + PORT;
private MockHttpServer server;
private SimpleHttpResponseProvider responseProvider;
private HttpClient client;
#Before
public void setUp() throws Exception {
responseProvider = new SimpleHttpResponseProvider();
server = new MockHttpServer(PORT, responseProvider);
server.start();
client = new DefaultHttpClient();
}
I am getting RED for MockHttpServer & SimpleHttpResponseProvider which should be part of org.apache.wink.client.*; which i am importing. so why do i have red ones? is there some simple way to unit test it?
HTTPResult return me response code and message.
So I have problem with testing my application. I am trying to do REST/HTTP test. Here is my code:
#Path("/ftpaction")
public class JerseyFileUpload {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response postMsg(#HeaderParam("FTP-Host") String Host, #HeaderParam("FTP-Port") String Port,
#HeaderParam("FTP-User") String User, #HeaderParam("FTP-Password") String Password,
#HeaderParam("FTP-Path") String Path, #FormDataParam("file") InputStream inputStream) {
try {
InformationHandler informationHandler = new InformationHandler(Path, Host, Port, User, Password);
CountriesStructure worker = new CountriesStructure();
worker.prepareCountriesStructure(inputStream, true, informationHandler);
} catch (UsernameOrPasswordException e) {
return Response.status(401).entity("Status 401.").build();
} catch (SocketException e) {
return Response.status(404).entity("Status 404.").build();
} catch (IOException e) {
return Response.status(400).entity("Status 400.").build();
} catch (JAXBException e) {
return Response.status(500).entity("Status 500.").build();
} catch (Exception e) {
return Response.status(500).entity("Status 500.").build();
}
return Response.status(200).entity("Success!").build();
}
}
And my test:
#RunWith(HttpJUnitRunner.class)
public class TestMain extends TestCase {
#Rule
public Destination destination = new Destination(this, "http://localhost:8080");
#Context
private Response response;
#HttpTest(method = Method.POST, path = "/JerseyWebApp/ftpaction/upload", content = "{}", file = "/CountriesList.txt", type = MediaType.MULTIPART_FORM_DATA, headers = {
#Header(name = "FTP-Host", value = "localhost"), #Header(name = "FTP-Port", value = "21"),
#Header(name = "FTP-User", value = "ftptest"), #Header(name = "FTP-Password", value = "test"),
#Header(name = "FTP-Path", value = "/test123"), #Header(name = "Accept-Encoding", value = "multipart/form-data")})
public void checkPost() {
System.out.println(response.getBody());
}
}
I have problem with reading file by test. I don't know what I have to do, because I am using file as "FormDataParam". Somebody have any idea how can I upload file to test as FormDataParam? Because like now it doesn't see my file and just return "Status 400".
I'm calling SAOP Webservice via a main method and it works fine.. But when i invoke the same method via a browser called method it give me the following error.
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL:
------------Working Code as Follows---------------------------
public class WSConnectionUtil {
private static final WSConnectionUtil INSTANCE = new WSConnectionUtil();
public SynchronizationServiceWSImpl getSyncServicePort(){
SynchronizationServiceWSImplService service = new SynchronizationServiceWSImplService();
SynchronizationServiceWSImpl servicePort = service.getSynchronizationServiceWSImplPort();
((BindingProvider) servicePort).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,getInstance().getSyncUrl());
return servicePort;
}
public static WSConnectionUtil getInstance() {
return INSTANCE;
}
private String getSyncUrl(){
String url = "http://10.2.241.33/synchronize?wsdl";
return url;
}
}
public void syncAll(){
System.out.println("===========syncAll======"+new Date());
SynchronizationRequest request = new SynchronizationRequest();
WSConnectionUtil wsCon = WSConnectionUtil.getInstance();
request.setPosCode("TNCB");
SynchronizationResponse response = wsCon.getSyncServicePort().synchronize(request);
List<String> types = response.getUpdateTypes();
System.out.println("===========types======"+types.size());
}
----------Error Code---------------------
/**
*
* service for login execution
* - user : Contains user id & password
* #param user
* #return
*
*/
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody ModelMap login(#ModelAttribute ("User")User user ){
String username = user.getName();
String password = user.getPassword();
ModelMap model = new ModelMap();
Boolean status = loginService.login(username, password);
if(status == true){
model.put("status", true);
}
return model;
}
public boolean login(String loginUser,String password){
Steward steward = new Steward();
steward.setStewardId(Integer.parseInt(loginUser));
//List<Steward> stewardsList = stewardDao.getStewardsByCriteria(steward);
//if(stewardsList!=null && stewardsList.size()>0){
// steward = stewardsList.get(0);
//}else{
// LOG.error("Cannot Find a Steward for Login : "+loginUser);
// return false;
//}
TouchPosApplication.getApplication().setUser("SYSTEM");
TouchPosApplication.getApplication().setOutletCode("A");
TouchPosApplication.getApplication().setLoginUserId(loginUser);
// final SynchronizationServiceImpl impl = new SynchronizationServiceImpl();
// impl.syncAll();
new Thread(new Runnable() {
private static final long serialVersionUID = -4094418102152819603L;
#Override
public void run() {
while (true) {
long i =0;
try {
i = 1000 * 60 * 1;
Thread.sleep(i);
} catch (InterruptedException e) {
System.out.println("===InterruptedException==========="+e);
}
SyncUtil.synchronizeAutomatic(true);
}
}
}).start();
LOG.info("::::: Successfuly Logged In :"+loginUser);
return true;
}