How to post an image to server in android - http-post

How do I upload an image to the Server? Both MultiPArtEntity and MultiPartEntityBuilder classes are deprecated in API level 23. Can we do this using HTTPUrlConnection or volley?

I suggest that you use OkHttp. More details about it you can find at the following:
OkHttp - An HTTP & SPDY client for Android and Java applications
Please refer to my basic sample code that uploads a PNG file from drawable folder to remote web service. Hope this helps!
...
mTextView = (TextView) findViewById(R.id.textView);
mHandler = new Handler(Looper.getMainLooper());
...
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
final byte[] bitmapdata = stream.toByteArray();
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"ic_launcher.png\""),
RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
.build();
final Request request = new Request.Builder()
.url("http://myserver/api/files")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Request request, final IOException e) {
Log.e(LOG_TAG, e.toString());
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
mTextView.setText(e.toString());
}
});
}
#Override
public void onResponse(Response response) throws IOException {
final String message = response.toString();
Log.i(LOG_TAG, message);
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
mTextView.setText(message);
}
});
}
});
}

Hello totally above answer is correct and accepted but here is the another solution the easiest way ever for posting image to the server:-
Using rest api from andoid spring framework in your android project just create new custom interface as below :-
#Rest(rootUrl ="BASE_URL", converters = {ByteArrayHttpMessageConverter.class,
FormHttpMessageConverter.class, StringHttpMessageConverter.class})
public interface CustomRest extends RestClientErrorHandling {
#Post("YourPostfixforUrl")
String _postImage(MultiValueMap<String, Object> multiValueMap);
}
Create your own RestErrorHandler using below code:-
#EBean
public class CustomRestErrorHandler implements RestErrorHandler
{
#Override
public void onRestClientExceptionThrown(NestedRuntimeException e)
{
Log.e("NestedRuntimeException ", "NestedRuntimeException :- " + e.toString());
}
}
On Your activity call bellow code :-
#AfterInject
public void afterInject() {
MultiValueMap<String, Object> ObjectMultiValueMap = new LinkedMultiValueMap<>();
ObjectMultiValueMap.add("yourImageKey", new FileSystemResource(new File("yourFilePath")));
doInBackground(myrest, ObjectMultiValueMap);
}
#Background
public void doInBackground(Myrest myrest, MultiValueMap<String, Object> multiValueMap) {
myrest.setRestErrorHandler(myErrorHandler);
}
Your Gradle will look like below:-
def AAVersion = '3.3.2'
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'}
NOTE:- Your activity Must be #Eactivity
--> I Guess androidannotation+rest is the best time saver and sincerely optimizing the code snippets!
Thanks

Related

How to decompress gzipped content in spring reactive?

While migrating my spring server from servlets to reactive I had to change all the filters in the code to WebFilter. One of the filters was decompressing gzipped content, but I couldn't do the same with the new WebFilter.
With servlets I wrapped the inputstream with a GzipInputStream. What is the best practice to do it with spring reactive?
Solution:
#Component
public class GzipFilter implements WebFilter {
private static final Logger LOG = LoggerFactory.getLogger(GzipFilter.class);
public static final String CONTENT_ENCODING = "content-encoding";
public static final String GZIP = "gzip";
public static final String UTF_8 = "UTF-8";
#Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (!isGzip(request)) {
return chain.filter(exchange);
}
else {
ServerHttpRequest mutatedRequest = new ServerHttpRequestWrapper(request);
ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
return chain.filter(mutatedExchange);
}
}
private boolean isGzip(ServerHttpRequest serverHttpRequest) {
String encoding = serverHttpRequest.getHeaders().getFirst(CONTENT_ENCODING);
return encoding != null && encoding.contains(GZIP);
}
private static class ServerHttpRequestWrapper implements ServerHttpRequest {
private ServerHttpRequest request;
public ServerHttpRequestWrapper(ServerHttpRequest request) {
this.request = request;
}
private static byte[] getDeflatedBytes(GZIPInputStream gzipInputStream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(gzipInputStream, writer, UTF_8);
return writer.toString().getBytes();
}
#Override
public String getId() {
return request.getId();
}
#Override
public RequestPath getPath() {
return request.getPath();
}
#Override
public MultiValueMap<String, String> getQueryParams() {
return request.getQueryParams();
}
#Override
public MultiValueMap<String, HttpCookie> getCookies() {
return request.getCookies();
}
#Override
public String getMethodValue() {
return request.getMethodValue();
}
#Override
public URI getURI() {
return request.getURI();
}
#Override
public Flux<DataBuffer> getBody() {
Mono<DataBuffer> mono = request.getBody()
.map(dataBuffer -> dataBuffer.asInputStream(true))
.reduce(SequenceInputStream::new)
.map(inputStream -> {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
byte[] targetArray = getDeflatedBytes(gzipInputStream);
return new DefaultDataBufferFactory().wrap(targetArray);
}
catch (IOException e) {
throw new IllegalGzipRequest(String.format("failed to decompress gzip content. Path: %s", request.getPath()));
}
});
return mono.flux();
}
#Override
public HttpHeaders getHeaders() {
return request.getHeaders();
}
}
}
love #Yuval's solution!
My original idea was to convert Flux to a local file, and then decompress the local file.
But getting a file downloaded in Spring Reactive is too challenging. I googled a lot, and most of them are blocking way to get file, (e.g. Spring WebClient: How to stream large byte[] to file? and How to correctly read Flux<DataBuffer> and convert it to a single inputStream , none of them works...) which makes no sense and will throw error when calling block() in a reactive flow.
#Yuval saved my day! It works well for me!

Endpoint "/api-docs" doesn't work with custom GsonHttpMessageConverter

I migrated from Springfox Swagger to Springdoc OpenApi. I have added few lines in my configuration about springdoc:
springdoc:
pathsToMatch: /api/**
api-docs:
path: /api-docs
swagger-ui:
path: /swagger-ui.html
In configuration class MainConfig.kt I have following code:
val customGson: Gson = GsonBuilder()
.registerTypeAdapter(LocalDateTime::class.java, DateSerializer())
.registerTypeAdapter(ZonedDateTime::class.java, ZonedDateSerializer())
.addSerializationExclusionStrategy(AnnotationExclusionStrategy())
.enableComplexMapKeySerialization()
.setPrettyPrinting()
.create()
override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
converters.add(GsonHttpMessageConverter(customGson))
}
When I go to http://localhost:8013/swagger-ui.html (in configuration I have server.port: 8013) the page is not redirect to swagger-ui/index.html?url=/api-docs&validatorUrl=. But this is not my main problem :). When I go to swagger-ui/index.html?url=/api-docs&validatorUrl= I got page with this information:
Unable to render this definition
The provided definition does not specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).
But when I go to http://localhost:8013/api-docs I have this result:
"{\"openapi\":\"3.0.1\",\"info\":{(...)}}"
I tried using default config and I commented configureMessageConverters() method and result of \api-docs now looks like normal JSON:
// 20191218134933
// http://localhost:8013/api-docs
{
"openapi": "3.0.1",
"info": {(...)}
}
I remember when I was using Springfox there was something wrong with serialization and my customGson had additional line: .registerTypeAdapter(Json::class.java, JsonSerializer<Json> { src, _, _ -> JsonParser.parseString(src.value()) })
I was wondering that I should have special JsonSerializer. After debugging my first thought was leading to OpenApi class in io.swagger.v3.oas.models package. I added this code: .registerTypeAdapter(OpenAPI::class.java, JsonSerializer<OpenAPI> { _, _, _ -> JsonParser.parseString("") }) to customGson and nothing changed... So, I was digging deeper...
After when I ran my Swagger tests:
#EnableAutoConfiguration
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureMockMvc
#ExtendWith(SpringExtension::class)
#ActiveProfiles("test")
class SwaggerIntegrationTest(#Autowired private val mockMvc: MockMvc) {
#Test
fun `should display Swagger UI page`() {
val result = mockMvc.perform(MockMvcRequestBuilders.get("/swagger-ui/index.html"))
.andExpect(status().isOk)
.andReturn()
assertTrue(result.response.contentAsString.contains("Swagger UI"))
}
#Disabled("Redirect doesn't work. Check it later")
#Test
fun `should display Swagger UI page with redirect`() {
mockMvc.perform(MockMvcRequestBuilders.get("/swagger-ui.html"))
.andExpect(status().isOk)
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
}
#Test
fun `should get api docs`() {
mockMvc.perform(MockMvcRequestBuilders.get("/api-docs"))
.andExpect(status().isOk)
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.jsonPath("\$.openapi").exists())
}
}
I saw in console this:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /api-docs
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = org.springdoc.api.OpenApiResource
Method = org.springdoc.api.OpenApiResource#openapiJson(HttpServletRequest, String)
Next I check openapiJson in OpenApiResource and...
#Operation(hidden = true)
#GetMapping(value = API_DOCS_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public String openapiJson(HttpServletRequest request, #Value(API_DOCS_URL) String apiDocsUrl)
throws JsonProcessingException {
calculateServerUrl(request, apiDocsUrl);
OpenAPI openAPI = this.getOpenApi();
return Json.mapper().writeValueAsString(openAPI);
}
OK, Jackson... I have disabled Jackson by #EnableAutoConfiguration(exclude = [(JacksonAutoConfiguration::class)]) because I (and my colleagues) prefer GSON, but it doesn't explain why serialization go wrong after adding custom GsonHttpMessageConverter. I have no idea what I made bad. This openapiJson() is endpoint and maybe it mess something... I don't know. I haven't any idea. Did you have a similar problem? Can you give some advice or hint?
PS. Sorry for my bad English :).
I had the same issue with a project written in Java, and I've just solved that by defining a filter to format my springdoc-openapi json documentation using Gson. I guess you can easily port this workaround to Kotlin.
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
ByteResponseWrapper byteResponseWrapper = new ByteResponseWrapper((HttpServletResponse) response);
ByteRequestWrapper byteRequestWrapper = new ByteRequestWrapper((HttpServletRequest) request);
chain.doFilter(byteRequestWrapper, byteResponseWrapper);
String jsonResponse = new String(byteResponseWrapper.getBytes(), response.getCharacterEncoding());
response.getOutputStream().write((new com.google.gson.JsonParser().parse(jsonResponse).getAsString())
.getBytes(response.getCharacterEncoding()));
}
#Override
public void destroy() {
}
static class ByteResponseWrapper extends HttpServletResponseWrapper {
private PrintWriter writer;
private ByteOutputStream output;
public byte[] getBytes() {
writer.flush();
return output.getBytes();
}
public ByteResponseWrapper(HttpServletResponse response) {
super(response);
output = new ByteOutputStream();
writer = new PrintWriter(output);
}
#Override
public PrintWriter getWriter() {
return writer;
}
#Override
public ServletOutputStream getOutputStream() {
return output;
}
}
static class ByteRequestWrapper extends HttpServletRequestWrapper {
byte[] requestBytes = null;
private ByteInputStream byteInputStream;
public ByteRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream inputStream = request.getInputStream();
byte[] buffer = new byte[4096];
int read = 0;
while ((read = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, read);
}
replaceRequestPayload(baos.toByteArray());
}
#Override
public BufferedReader getReader() {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
#Override
public ServletInputStream getInputStream() {
return byteInputStream;
}
public void replaceRequestPayload(byte[] newPayload) {
requestBytes = newPayload;
byteInputStream = new ByteInputStream(new ByteArrayInputStream(requestBytes));
}
}
static class ByteOutputStream extends ServletOutputStream {
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
#Override
public void write(int b) {
bos.write(b);
}
public byte[] getBytes() {
return bos.toByteArray();
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setWriteListener(WriteListener writeListener) {
}
}
static class ByteInputStream extends ServletInputStream {
private InputStream inputStream;
public ByteInputStream(final InputStream inputStream) {
this.inputStream = inputStream;
}
#Override
public int read() throws IOException {
return inputStream.read();
}
#Override
public boolean isFinished() {
return false;
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
}
}
You will also have to register your filter only for your documentation url pattern.
#Bean
public FilterRegistrationBean<DocsFormatterFilter> loggingFilter() {
FilterRegistrationBean<DocsFormatterFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new DocsFormatterFilter());
registrationBean.addUrlPatterns("/v3/api-docs");
return registrationBean;
}

How do I resolve an "Unknown Host Exception" when using Volley to interact with BigCommerce's Orders API endpoint?

As far as I know, I am implementing Volley correctly, and I know for a fact that the API endpoint URL along with all the HTTP headers are 100% correct. Yet, when I try to GET the JSON from the endpoint, an Unknown Host Exception is thrown.
I used the BigCommerce Orders API reference and made multiple test queries, and it worked there, but there appears to be some kind of disconnect when ran on the emulator on Android studio. Is it possible that my business' WiFi and/or the emulator itself is causing this problem?
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(com.android.volley.Request.Method.GET,
URL, null, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseOrders(response);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley", error.getMessage());
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("accept", "application/json");
params.put("content-type", "application/json");
params.put("x-auth-token", "myToken");
params.put("x-auth-client", "myClientID");
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
requestQueue.add(jsonObjectRequest);

Spring-Integration-DSL & Soap Service Soap header is not getting invoked

I am trying to call a soap service with spring integration DSL, have some custom header that needs to be added.
Constructed marshellingoutboundgateway. Trying to override DefaultSoapHeaderMapper but none of the overridden methods are getting called.
Trying to construct some thing like this.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<ObjectType34 >
</ObjectType34>
</soapenv:Header>
<soapenv:Body>
<ObjectType12 >
</ObjectType12>
</soapenv:Body>
</soapenv:Envelope>
There is a sample in : https://github.com/spring-projects/spring-integration/blob/master/src/reference/asciidoc/ws.adoc
looks like only available in 5.0
posted detail code.
Any insights will be helpful.
#Configuration
#SpringBootApplication
#IntegrationComponentScan
#EnableIntegration
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
Info Info = ctx.getBean(Info.class);
//Constructing request Payload
ObjectType12 getInfoType = new ObjectFactory().ObjectType12();
JAXBElement<GetInfoType> getInfoTypeJAXBElement = new ObjectFactory().createGetInfo(getInfoType);
JAXBElement<GetInfoResponseType> getInfoResponseType = Info.getInfo(getInfoTypeJAXBElement);
System.out.println(getInfoResponseType.getName());
ctx.close();
}
#MessagingGateway
public interface Info {
#Gateway(requestChannel = "convert.input")
JAXBElement<GetInfoResponseType> getInfo(JAXBElement<GetInfoType> InfoType);
}
#Bean
public IntegrationFlow convert() {
StringResult result = new StringResult();
return flow -> flow
.wireTap(f -> f.<JAXBElement, String>transform(ele -> {
jaxb2Marshaller().marshal(ele, result);
return result.toString();
}).log())
.handle(endpoint());
}
#Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("org.abc", "com.abc");
return marshaller;
}
#Bean
public MarshallingWebServiceOutboundGateway endpoint() {
MarshallingWebServiceOutboundGateway gateway = new MarshallingWebServiceOutboundGateway("https://example.com/v1", jaxb2Marshaller(), jaxb2Marshaller());
gateway.setHeaderMapper(new DefaultSoapHeaderMapper() {
#Override
protected void populateUserDefinedHeader(String headerName, Object headerValue, SoapMessage target) {
super.populateUserDefinedHeader("Content-Type", "application/soap+xml", target);
}
#Override
protected void populateStandardHeaders(Map<String, Object> headers, SoapMessage target) {
headers.put(WebServiceHeaders.SOAP_ACTION,
"http://www.example.com/SOAUI/ServiceHeader/V4");
super.populateStandardHeaders(headers, target);
}
#Override
public void fromHeadersToRequest(MessageHeaders headers, SoapMessage target) {
SaajSoapMessage targetMessage = (SaajSoapMessage) target;
SoapHeader header = targetMessage.getEnvelope().getHeader();
//Constructing SOAP Header
JAXBElement<ObjectType34> trackingHdrTypeJAXBElement = ObjectFactory().createHdr(ObjectType34);
jaxb2Marshaller().marshal(trackingHdrTypeJAXBElement, header.getResult());
System.out.println(header.getResult());
}
#Override
public void setRequestHeaderNames(String... requestHeaderNames) {
super.setRequestHeaderNames("*");
}
});
gateway.setMessageFactory(new SaajSoapMessageFactory() {
#Override
public void setSoapVersion(SoapVersion version) {
super.setSoapVersion(SoapVersion.SOAP_11);
}
});
return gateway;
}
}
UPDATE: Modified the code
#Bean
public DefaultSoapHeaderMapper headerMapper11() {
return new DefaultSoapHeaderMapper() {
#Override
public void fromHeadersToRequest(MessageHeaders headers, SoapMessage target) {
SaajSoapMessage targetMessage = (SaajSoapMessage) target;
SoapHeader header = targetMessage.getEnvelope().getHeader();
//Constructing SOAP Header
JAXBElement<ObjectType34> trackingHdrTypeJAXBElement = ObjectFactory().createHdr(ObjectType34);
jaxb2Marshaller().marshal(trackingHdrTypeJAXBElement, header.getResult());
super.fromHeadersToRequest(headers, target);
}
};
}
and set the header using the method call:
gateway.setHeaderMapper(headerMapper11());
Now the overridden method is getting called and having the header as well.
Code is working as expected now.

Too many connection for Spring Boot Application and Apache storm

I am using spring boot application for websocket and in my storm project i am calling the spring boot application everytime to publish real time sensor data i,e per 5 minutes it is establishing 5000 connection so how to avoid this problem?
Is there any way to do connection pooling for spring boot connection in the Apache storm project?
String boot application controller class:
private static Logger logger=Logger.getLogger(GreetingController.class);
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
//logger.info("+++++++Sending Greetinge+++++++" + message);
//Thread.sleep(3000); // simulated delay
return new Greeting("Hello greetings, " + message.getName() + "!");
}
#MessageMapping("/orignal")
#SendTo("/topic/orignal")
public Map<String, Object> orignal(Map<String, Object> orignal) throws Exception {
// logger.info("+++++++Sending orignale+++++++" + orignal);
//System.out.println("Sending orignal");
//Thread.sleep(3000); // simulated delay
return orignal;
}
#MessageMapping("/tupple")
#SendTo("/topic/tupple")
public Map<String, Object> tupple(Map<String, Object> tupple) throws Exception {
logger.info("+++++++Sending tupple+++++++" + tupple);
//System.out.println("Sending tupple");
//Thread.sleep(3000); // simulated delay
//String company_name=(String) tupple.get("company_name");
/*Map<String, Object> companyMap=new HashMap<String, Object>();
companyMap.put("success", true);
companyMap.put("message", "company created successfully");*/
return tupple;
}
#MessageMapping("/websocket")
#SendTo("/topic/websocket")
public Map<String, Object> websocket(Map<String, Object> websocket) throws Exception {
logger.info("+++++++Sending websocket+++++++" + websocket);
//System.out.println("Sending websocket");
//Thread.sleep(3000); // simulated delay
return websocket;
}
In storm project making connection to spring boot application:
private final static WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
public ListenableFuture<StompSession> connect(String endpoint) {
Transport webSocketTransport = new WebSocketTransport(new StandardWebSocketClient());
List<Transport> transports = Collections.singletonList(webSocketTransport);
SockJsClient sockJsClient = new SockJsClient(transports);
sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());
WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
/*String url = "ws://{host}:{port}/"+endpoint;
return stompClient.connect(url, headers, new MyHandler(), "10.0.0.6", 8080);*/
String url = "ws://*************/IoTWebSocketServer-1.2.5.RELEASE/"+endpoint;
return stompClient.connect(url, headers, new MyHandler());
}
public void subscribeGreetings(String topic,StompSession stompSession) throws ExecutionException, InterruptedException {
stompSession.subscribe(topic, new StompFrameHandler() {
public Type getPayloadType(StompHeaders stompHeaders) {
return byte[].class;
}
public void handleFrame(StompHeaders stompHeaders, Object o) {
}
});
}
public void sendHello(StompSession stompSession,String message) {
String jsonHello = "{ \"name\" : \""+message+"\" }";
stompSession.send("/app/hello", jsonHello.getBytes());
}
private class MyHandler extends StompSessionHandlerAdapter {
public void afterConnected(StompSession stompSession, StompHeaders stompHeaders) {
}
}
public static void main(String[] args) throws Exception {
HelloClient helloClient = new HelloClient();
String endPoint = "hello";
ListenableFuture<StompSession> f = helloClient.connect(endPoint);
StompSession stompSession = f.get();
String topic= "/topic/greetings";
helloClient.subscribeGreetings(topic,stompSession);
String message = "hieeeeeeeeeeeeeeee message";
helloClient.sendHello(stompSession,message);
HelloClient helloClienttupple = new HelloClient();
String endPointtupple = "tupple";
ListenableFuture<StompSession> ftupple = helloClient.connect(endPointtupple);
StompSession stompSessiontupple = ftupple.get();
String topictupple= "/topic/tupple";
helloClient.subscribeGreetings(topictupple,stompSessiontupple);
String messagetupple = "hieeeeeeeeeeeeeeee tupple";
helloClienttupple.sendHello(stompSessiontupple,messagetupple);
JSONObject companyMap = new JSONObject();
companyMap.put("name", "Mahabali");
companyMap.put("num", new Integer(100));
companyMap.put("balance", new Double(1000.21));
companyMap.put("is_vip", new Boolean(true));
System.out.println(companyMap.toString());
stompSessiontupple.send("/app/tupple", companyMap.toString().getBytes());
//Thread.sleep(60000);
}
This the connection establishing code:
t
ry{
logger.info("++++Websocket Gateway packet++++" + topicId);
JSONObject jsonObject=new JSONObject();
JSONObject jsonObject1=new JSONObject();
JSONArray array=new JSONArray();
jsonObject.put("MAC_IMEI", topicId);
jsonObject.put("TIME", eventTime);
jsonObject.put("DEVICE", "GATEWAY");
jsonObject.put("GATEWAY", nJsonArray);
array.put(jsonObject);
jsonObject1.put("GATEWAY", array);
HelloClient helloClientwebsocket = new HelloClient();
String endPointwebsocket = "websocket";
ListenableFuture<StompSession> fwebsocket = helloClientwebsocket.connect(endPointwebsocket);
StompSession stompSessionwebsocket = fwebsocket.get();
String topicwebsocket= "/topic/websocket";
helloClientwebsocket.subscribeGreetings(topicwebsocket,stompSessionwebsocket);
stompSessionwebsocket.send("/app/websocket", jsonObject.toString().getBytes());
}
catch(Exception e)
{
logger.info("Gateway exception");
logger.error("++++Exception caught during sending the sensor details in the new websocket server++++"+e);
}

Resources