How to send FCM message from Appengine server on cloud code works local server - google-app-engine

How to do it in cloud AppEngine without billing.
I am able to get Token from Javascript but sending messages to the server for notification. Create JSON object for downstream data/notification. On the server saying billing for the socket.
private void localappengine(HttpServletResponse response, String ENDPOINT_URL) throws IOException {
HttpClient client = new DefaultHttpClient();
Log.info("after client");
HttpPost post = new HttpPost(ENDPOINT_URL);
String deviceToken="cthG-hesotM:APA91bGg_tLg7TqvpY4aAvzHpyBK2mTTOT2KgO94tDFcLGPakcS9vmXkYEIe4Vh0Mo5ka1COfaXarUEJGWyqDdmVi_kujUfKDtE4C30eZwkPQATXnFrDPJxHxd8iouwsWuRcAk-ZYe_4";
PrintWriter out=response.getWriter();
response.getWriter().println("Hello from myservlet " );
// Create JSON object for downstream data/notification
JSONObject mainNotificationJsonObj = new JSONObject();
JSONObject outerBaseJsonObj = new JSONObject();
try {
// Notification payload has 'title' and 'body' key
mainNotificationJsonObj.put("title", "testing message");
mainNotificationJsonObj.put("body", "Hello I sent it");
// This will be used in case of both 'notification' or 'data' payload
outerBaseJsonObj.put("to", deviceToken);
// Set priority of notification. For instant chat setting
// high will
// wake device from idle state - HIGH BATTERY DRAIN
//outerBaseJsonObj.put(PRIORITY_KEY, PRIORITY_HIGH);
// Specify required payload key here either 'data' or
// 'notification'. We can even use both payloads in single
// message
outerBaseJsonObj.put("notification", mainNotificationJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
Log.info("before entity");
// Setup http entity with json data and 'Content-Type' header
StringEntity requestEntity = new StringEntity(outerBaseJsonObj.toString());
//(outerBaseJsonObj.toString(), APPLICATION_JSON);
String FIREBASE_SERVER_KEY= "key=AAAA6nN2BxI:APA91bHYotXML0siwL0Pm0LK5iXQ9Ik1kQtdB1ALbJrm5kseUk2zS5gJs6AMHVsX86exEE-JFsIF962YNY1yRyl3yFxGCyMBAH4OKwTn8Ff6vcd6vJMVXutNlP99X8AtOsW8_JIBkyEl";
// Setup required Authorization header
post.setHeader("Authorization", FIREBASE_SERVER_KEY);
post.setHeader("Content-Type", String.valueOf(APPLICATION_JSON));
Log.info("after header");
// Pass setup entity to post request here
post.setEntity(requestEntity);
// Execute apache http client post response
HttpResponse fcmResponse = client.execute(post);
Log.info("after client execute");
// Get status code from FCM server to debug error and success
System.out.println("RESPONSE_CODE" + fcmResponse.getStatusLine().getStatusCode());
// Get response entity from FCM server and read throw lines
BufferedReader rd = new BufferedReader(new InputStreamReader(fcmResponse.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
if (response != null) {
// Print out the response to webpage
PrintWriter out1;
out1 = response.getWriter();
out1.println(result);
System.out.println("This is Result - " + result);
}
}

Related

Changing apache camel message type to InOut

From what I understand, an InOut message is one where a response can be received from the destination.
However, I have not been able to find any example of how to convert a message to InOut type, and how to access the response from the destination
For example, given a route like:
from("direct:start").to("smtps://smtp.gmail.com:465?username=user#gmail.com&password=usrpw&to=address#gmail.com")
How to convert the message routed to smtps component into InOut type?
Can I expect a response from the smtp component, e.g. indicating that the message was sent successfully?
how to access this response?
By default, each ".to(uri)" are in InOut. The body in the next step will be replaced by the response of the InOut destination. For example, in HTTP component, if you have the following route :
from(direct:start)
.to(http://...)
.log(INFO, "${body}")
The response to the http call will be logged.
If you don't find good informations in the document, I highly recommend you to check the code of the related producer to know what's returned or can be used.
https://github.com/apache/camel
For example, for SMTP, I haven't found the doc saying what's happening to the body, but the code is pretty much clear :
public void process(final Exchange exchange) {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
ClassLoader applicationClassLoader = getEndpoint().getCamelContext().getApplicationContextClassLoader();
if (applicationClassLoader != null) {
Thread.currentThread().setContextClassLoader(applicationClassLoader);
}
MimeMessage mimeMessage;
final Object body = exchange.getIn().getBody();
if (body instanceof MimeMessage) {
// Body is directly a MimeMessage
mimeMessage = (MimeMessage) body;
} else {
// Create a message with exchange data
mimeMessage = new MimeMessage(sender.getSession());
getEndpoint().getBinding().populateMailMessage(getEndpoint(), mimeMessage, exchange);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Sending MimeMessage: {}", MailUtils.dumpMessage(mimeMessage));
}
sender.send(mimeMessage);
// set the message ID for further processing
exchange.getIn().setHeader(MailConstants.MAIL_MESSAGE_ID, mimeMessage.getMessageID());
} catch (MessagingException e) {
exchange.setException(e);
} catch (IOException e) {
exchange.setException(e);
} finally {
Thread.currentThread().setContextClassLoader(tccl);
}
}
Your exchange will have an header with the MAIL_ID ("CamelMailMessageId"), and in case of any messaging exception, the exception will be propagated. The body seems to be left untouched, even if it's InOut.

Codename one application is not able to connect with server using https request

We have created codename one application which using https request.
I have not made any changes in code.
Earlier the request could be sent using https but now their is a problem and i am unable to connect to the server using https request but i am able to connect same https url using postman.
The connection code snippet is following please refer it
new APIHandler().PropertiesLoad();
ConnectionRequest req = new ConnectionRequest() {
protected void handleErrorResponseCode(int code, String message) {
if (code != 200) {
// do something
}
}
};
req.setUrl(properties.getProperty("https_url"));
req.setPost(true);
req.setTimeout(Constant.TIMEOUT);
req.addArgument("FirstName", fName;
req.addArgument("SecondName", sName);
req.addArgument("BirthDate", bDate);
req.addArgument("Password", pWord);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
if (data == null) {
}
result = new String(data);
} catch (Exception e) {
//get nullpointer exception because result get null
result = "";
}
return result;

Windows IoT TcpClient

I want to send a command to my Sonos speaker. With my Windows application that is easy. I just use the TcpClient example provided on Microsoft website (shown below).
public void Connect(String server, String message)
{
try
{
TcpClient client = new TcpClient(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Now, how would I go about doing this with Windows 10 IoT on a Raspberry Pi 3?
With UWP, you may need to reference the "System.Net.Sockets" Nuget package in order to use TcpClient. You probably end up with something like below snippet,
async void FunctionName()
{
try
{
using (var client = new TcpClient())
{
await client.ConnectAsync(server, 1400);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
//Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
//Console.WriteLine("Received: {0}", responseData);
}
}
catch (ArgumentNullException e)
{
//Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
// Console.WriteLine("SocketException: {0}", e);
}
//Console.WriteLine("\n Press Enter to continue...");
//Console.Read();
}
Note that you need to declare the Internet client capability in your project manifest file.
PS: There's also an alternative an alternative called StreamSocket.
Refer to an complete code sample from Microsoft github repository.
Also, if you're new to UWP programming, you should get yourself familar with the async/await pattern.

Apache Camel - protocol buffer endpoint

I am trying to create a camel endpoint that listens on a tcp port to receive a message encoded using protocol buffers. [https://code.google.com/p/protobuf/]
I am trying to use netty to open the tcp port but I cannot get it to work.
My camel route builder is:
from("netty:tcp://localhost:9000?sync=false").to("direct:start");
from("direct:start").unmarshal(format)
.to("log:protocolbuffers?level=DEBUG")
.to("mock:result");
I have tried the textline code, but this just causes the error com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either than the input has been truncated or that an embedded message misreported its own length.
I think I need to use a byte array codec rather than a String, but I can't see a way to do it. I think I could write a custom endpoint to do it, but I'd rather not. Any pointers would be much appreciated.
I sent the message to the camel endpoint using the code below:
public static void main(String[] args) {
try {
TestProtos.Person me = TestProtos.Person.newBuilder().setId(2).setName("Alan").build();
//set up socket
SocketChannel serverSocket;
serverSocket = SocketChannel.open();
serverSocket.socket()
.setReuseAddress(true);
serverSocket.connect(new InetSocketAddress("127.0.0.1", 9000));
serverSocket.configureBlocking(true);
//create BAOS for protobuf
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//mClientDetails is a protobuf message object, dump it to the BAOS
me.writeDelimitedTo(baos);
//copy the message to a bytebuffer
ByteBuffer socketBuffer = ByteBuffer.wrap(baos.toByteArray());
//keep sending until the buffer is empty
while (socketBuffer.hasRemaining()) {
serverSocket.write(socketBuffer);
}
serverSocket.close();
} catch (Exception e) {
System.out.println("error....");
}
}
}
I also ran a test using a file endpoint which worked as expected. I created the file
with:
#Test
public void fileTest() throws Exception {
TestProtos.Person me = TestProtos.Person.newBuilder().setId(2).setName("Chris").build();
File file = new File("/tmp/test.txt");
FileOutputStream out = new FileOutputStream(file);
me.writeTo(out);
out.close();
};

Silverlight - Exception when trying to POST to webservice

I'm using the "Post" method so I can send a custom object. But I keep getting the following exception on the request.BeginGetResponse():
{System.Net.ProtocolViolationException: Operation is not valid due to the current state of the object.
at System.Net.Browser.BrowserHttpWebRequest.BeginGetResponseImplementation()}
public void Send()
{
HttpWebRequest client = WebRequest.Create(new Uri(BaseUrl)) as HttpWebRequest;
client.Method = "POST";
client.ContentLength = MaxSerializationSize;
client.BeginGetRequestStream(new AsyncCallback(RequestProceed), client);
}
private void RequestProceed(IAsyncResult asuncResult)
{
HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;
StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyCustomClass));
ser.WriteObject(ms, MyCustomClassObject);
postDataWriter.Write(ms);
postDataWriter.Close();
request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);
}
private void ResponceProceed(IAsyncResult asuncResult)
{
var request = (HttpWebRequest) asuncResult.AsyncState;
using (var resp = (HttpWebResponse) request.EndGetResponse(asuncResult))
{
using (var stream = resp.GetResponseStream())
{
}
}
}
I have tried so many ways to get this to work. Hoping someone can tell me where i'm going wrong. Thanks.
You need to close the request stream. You are just closing the StreamWriter and not the underlying request stream. While you are at it eliminate the superflous MemoryStream and have the DataContractJsonSerializer write directly to the Request stream.
HttpWebRequest request = (HttpWebRequest) asuncResult.AsyncState;
using (Stream outStream = request.EndGetRequestStream(asyncResult));
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MyCustomClass));
ser.WriteObject(outStream, MyCustomClassObject);
outStream.Flush();
outStream.Close();
}
request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);
Also get rid of this line:-
client.ContentLength = MaxSerializationSize;
Without also turning off AllowWriteStreamBuffering (which is only possible on the ClientHTTP implementation anyway) there is no need to set the ContentLength, that is done for you.

Resources