I want to push notification from my server.for that i am using web push API for java , i am able to send the notification to endpoint url but on receiver side my service worker not executing push event,As I am using VAPID so no need to use gcm Id as per my understanding,here you are my service worker file.
'use strict';
const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
self.addEventListener('install', function(event){
event.waitUntil(self.skipWaiting());
console.log("activate");
});
self.addEventListener('activate', function(event){
event.waitUntil(self.clients.claim());
console.log("install");
});
self.addEventListener('push', function(event) {
console.log('Received push');
let notificationTitle = 'Hello';
const notificationOptions = {
body: 'Thanks for sending this push msg.',
icon: '/JMS/resources/images/icon.png',
badge: '/JMS/resources/images/badge.png',
tag: 'simple-push-demo-notification',
data: {
url: 'https://developers.google.com/web/fundamentals/getting-
started/push-notifications/',
},
};
if (event.data) {
const dataText = event.data.text();
notificationTitle = 'Received Payload';
notificationOptions.body = `Push data: '${dataText}'`;
}
event.waitUntil(
Promise.all([
self.registration.showNotification(
notificationTitle, notificationOptions),
])
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(
clients.openWindow('https://www.auctiontiger.net')
);
let clickResponsePromise = Promise.resolve();
if (event.notification.data && event.notification.data.url) {
clickResponsePromise = clients.openWindow(event.notification.data.url);
}
event.waitUntil(
Promise.all([
clickResponsePromise
])
);
});
here you are my main.js file from where i am able to call to my local server.
'use strict';
const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
const pushButton = document.querySelector('.js-push-btn');
let isSubscribed = false;
let swRegistration = null;
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}
if (isSubscribed) {
pushButton.textContent = 'Disable Push Messaging';
} else {
pushButton.textContent = 'Enable Push Messaging';
}
pushButton.disabled = false;
}
function updateSubscriptionOnServer(subscription) {
// TODO: Send subscription to application server
const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails =
document.querySelector('.js-subscription-details');
if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
subscriptionDetails.classList.remove('is-invisible');
} else {
subscriptionDetails.classList.add('is-invisible');
}
}
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:applicationServerKey
})
.then(function(subscription) {
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
initialiseUI();
return sendSubscriptionToServer(subscription);
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
});
}
function sendSubscriptionToServer(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
var auth = subscription.getKey ? subscription.getKey('auth') : '';
return fetch('/JMS/profile/subscription', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
endpoint: subscription.endpoint,
// Take byte[] and turn it into a base64 encoded string suitable for
// POSTing to a server over HTTP
key:key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key)))
: '',
auth:auth ? btoa(String.fromCharCode.apply(null, new
Uint8Array(auth))) : ''
})
});
}
function unsubscribeUser() {
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
return subscription.unsubscribe();
}
})
.catch(function(error) {
console.log('Error unsubscribing', error);
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
}
function initialiseUI() {
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('sw.js')
.then(function(swReg) {
console.log('Service Worker is registered', swReg.scope);
swReg.update();
swRegistration = swReg;
initialiseUI();
})
.catch(function(error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
here is the URL for webpush API that i have used for my application,
[https://github.com/web-push-libs/webpush-java][1]
finally my server side code,
#RequestMapping(value = "profile/subscription", method = RequestMethod.POST,
headers = "Content-Type=application/json")
#ResponseBody
public String post(#RequestBody String body,byte[]
payload,HttpServletResponse response)
throws GeneralSecurityException, IOException, JoseException,
ExecutionException, InterruptedException, ParseException, JSONException
{
String data="";
org.json.JSONObject ob = new org.json.JSONObject(body);
final int TTL = 255;
payload= "hello".getBytes();
com.demo.controller.PushService pushService = new
com.demo.controller.PushService();
nl.martijndwars.webpush.Notification notification =new
nl.martijndwars.webpush.Notification(ob.getString("endpoint")
,new Subscription().getUserPublicKey((ob.getString("key"))),
Base64.decode(ob.getString("auth")),
payload,TTL);
pushService.send(notification);
org.json.JSONObject ob2 = new org.json.JSONObject(body);
ob2.put("data", notification.getPayload());
JSONArray arr= new JSONArray();
arr.add(ob2);
data=arr.toJSONString();
response.setHeader("Service-Worker-Allowed", "/");
return data;
}
actually I am fetching this from client browser and on server-side sending notification on the endpoint, and i am able to send the notification but my
service worker is not able to fire push event so i am not getting notification on my browser.
{
auth:"hcQQq+1FeDuSu7V0zd5DXA=="
endpoint:"https://fcm.googleapis.com/fcm/send/
cXgp0l3svNo:APA91bG8dDfZhrc0iaSyzvuV1BvnxXz9T-
SmLCKOymKrEdwvrh0_SjzjnU3ORRKvW5QD-
Zp196T5nAGPayR7EKu_Bkb0pQrSex7Q3DZSu54Lo83AEiUE6p-2Xn-nrquCymKVFt6Z4nY8"
key:"BJv2qC3WSCsRszMi57vOBpFjnIpdJ/
uXQQFj4d0XZD9lRuZKuBgJNVFra0SFEvRlQQ88eG8RWWs7sSvO9Pbdkwk="
}
Please help me to get out of this, any help would be greatly appreciated.Thank you in advance.
The issue might be due to some firewall blocking you from receiving the push notification. This was the case with me.
Related
I am streaming the audio from microphone using javascript and sending the audio stream from frontend to backend via websocket. In my websocket handle message i can see float array recieving from front end but as soon as i write the float array to a file it does contatin any audio. here is link of generated audio file.
#Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// TODO Auto-generated method stub
byte [] bb =getByteArrayFromByteBuffer((ByteBuffer)message.getPayload());
System.out.println(Arrays.toString(bb));
FileUtils.writeByteArrayToFile(file,bb,true);
}
private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
byte[] bytesArray = new byte[byteBuffer.remaining()];
byteBuffer.get(bytesArray, 0, bytesArray.length);
return bytesArray;
}
below is javascript streaming code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<button onclick="stop()">stop</button>
<script>
const AudioContext = window.AudioContext// Safari and old versions of Chrome
var context;
var source;
var bufferDetectorNode ;
jssocket= new WebSocket("ws://localhost:8080/websocket/name?user_id="+ generateRandomInteger(0, 3));
jssocket.onopen = function(e) {
console.log("[open] Connection established");
};
jssocket.onmessage = function(event) {
console.log(`[message] Data received from server: ${event.data}`);
};
jssocket.onclose = function(event) {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
console.log('[close] Connection died');
}
};
jssocket.onerror = function(error) {
console.log(`[error] ${error.message}`);
};
try {
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia;
microphone = navigator.getUserMedia({
audio : true,
video : false
}, onMicrophoneGranted, onMicrophoneDenied);
} catch (e) {
alert(e)
}
async function onMicrophoneGranted(stream) {
console.log(stream)
context = new AudioContext();
source = context.createMediaStreamSource(stream);
await context.audioWorklet.addModule('/assets/js/buffer-detector.js');
// Create our custom node.
bufferDetectorNode= new AudioWorkletNode(context, 'buffer-detector');
bufferDetectorNode.port.onmessage = (event) => {
// Handling data from the processor.
jssocket.send(event.data)
// const byteArr = Int8Array.from(event.data)
//const original = Array.from(byteArr)
// console.log(original);
// jssocket.send( Buffer.from(byteArr, 'base64').toString('utf8'));
};
source.connect(bufferDetectorNode);
bufferDetectorNode.connect(context.destination);
//source.connect(context.destination);
}
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function onMicrophoneDenied() {
console.log('denied')
}
function stop(){
bufferDetectorNode.disconnect(context.destination)
source.disconnect(bufferDetectorNode)
}
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random() * (max - min + 1))
}
</script>
</body>
</html>
AudioWorklet
class BufferProcessor extends AudioWorkletProcessor {
bufferSize = 256
_bytesWritten = 0
// 2. Create a buffer of fixed size
_buffer = new Float32Array(this.bufferSize)
initBuffer() {
this._bytesWritten = 0
}
isBufferEmpty() {
return this._bytesWritten === 0
}
isBufferFull() {
return this._bytesWritten === this.bufferSize
}
process (inputs) {
this.append(inputs[0][0])
return true;
}
append(channelData) {
if (this.isBufferFull()) {
this.flush()
}
if (!channelData) return
for (let i = 0; i < channelData.length; i++) {
this._buffer[this._bytesWritten++] = channelData[i]
}
}
flush() {
// trim the buffer if ended prematurely
this.port.postMessage(
this._bytesWritten < this.bufferSize
? this._buffer.slice(0, this._bytesWritten)
: this._buffer
)
this.initBuffer()
}
static get parameterDescriptors() {
return [{
name: 'Buffer Detector',
}]
}
constructor() {
super();
this._socket = null;
this._isRecording = true;
this.initBuffer()
}
get socket() {
return this._socket;
}
set socket(value) {
if (value instanceof WebSocket) {
this._socket = value;
}
}
get recording() {
return this._isRecording;
}
set recording(value) {
if ('boolean' === typeof value) {
this._isRecording = value;
}
}
}
registerProcessor('buffer-detector',BufferProcessor );
I'm really new in Kotlin.
I have two application one is Client in Android emulator and one is in Windows Form Application Server (My server is Using SimpleTCP library in C#) .
Here is the Server Code:
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13;
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
messageList.Text += "Server starting...";
server.Start("192.168.1.7", 5000);
messageList.Text += "\r\n Server started...";
}
private void Server_DataReceived(object sender, SimpleTCP.Message e)
{
messageList.Invoke((MethodInvoker)delegate ()
{
messageList.Text += string.Format("\r\n Client Message: {0} \n ", e.MessageString);
});
e.ReplyLine("Hello from Server");
}
I'm communicating via localhost. I can send request and Server can get this request without problem but when i try to get response from Server unfortunately cannot receive response.
val message = input!!.readLine() is always returning null
Can you help me why i cannot do this?
Here my code
var thread: Thread? = null
var etIP: EditText? = null
var etPort: EditText? = null
var tvMessages: TextView? = null
var etMessage: EditText? = null
var btnSend: Button? = null
var SERVER_IP: String? = null
var SERVER_PORT = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
etIP = findViewById(R.id.etIP)
etPort = findViewById(R.id.etPort)
tvMessages = findViewById(R.id.tvMessages)
etMessage = findViewById(R.id.etMessage)
btnSend = findViewById(R.id.btnSend)
val btnConnect: Button = findViewById(R.id.btnConnect)
btnConnect.setOnClickListener {
tvMessages!!.text = ""
SERVER_IP = etIP!!.text.toString().trim { it <= ' ' }
SERVER_PORT = etPort!!.text.toString().trim { it <= ' ' }.toInt()
thread = Thread(Thread1())
thread!!.start()
}
btnSend!!.setOnClickListener {
val message = "Android!"+etMessage!!.text.toString().trim { it <= ' ' }
if (!message.isEmpty()) {
Thread(Thread3(message)).start()
}
}
}
private var output: PrintWriter? = null
private var input: BufferedReader? = null
internal inner class Thread1 : Runnable {
override fun run() {
val socket: Socket
try {
socket = Socket(SERVER_IP, SERVER_PORT)
output = PrintWriter(socket.getOutputStream())
input = BufferedReader(InputStreamReader(socket.getInputStream()))
runOnUiThread(Runnable { tvMessages!!.text = "Connected\n" })
Thread(Thread2()).start()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
internal inner class Thread2 : Runnable {
override fun run() {
while (true) {
try {
val message = input!!.readLine().toString()
run {
runOnUiThread(Runnable { tvMessages!!.append("server: $message\n") })
}
run {
thread = Thread(Thread1())
thread!!.start()
return
}
} catch (e: Exception) {
tvMessages!!.text = e.toString()
}
}
}
}
internal inner class Thread3(private val message: String) : Runnable {
override fun run() {
output!!.write(message)
output!!.flush()
runOnUiThread(Runnable {
tvMessages!!.append("client: $message\n")
tvMessages!!.setMovementMethod(ScrollingMovementMethod())
etMessage!!.setText("")
})
}
}
fun clearAll(view: View){
tvMessages!!.text = ""
}
i've got problem getting data from Node server, i've searching many reference from internet, but i haven't found one yet that can solve my problem.
this is my node server
var socket = require('socket.io');
var express = require('express');
var app = express();
/*
var options = {
key: fs.readFileSync('cert/file.key'),
cert: fs.readFileSync('cert/file.crt')
};
var server = require('https').createServer(options, app);
*/
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 3000;
//server.listen(port, '103.126.57.4', function () {
server.listen(port, function () {
console.log('Server listening at port %d', port);
//console.log('Server listening at port %d', port, server.address());
});
io.on('connection', function (socket) {
console.log( "New client connected !" );
//console.log(socket.handshake.headers.host);
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'new_chat_kelas', function( data ) {
io.sockets.emit( data.tabelchat, {
idleveluser: data.idleveluser,
nama: data.nama,
level: data.level,
idchat: data.idchat,
pesan: data.pesan,
file: data.file,
reply: data.reply,
created_at: data.created_at
});
});
socket.on( 'change_chat_status', function( data ) {
io.sockets.emit( 'change_status'+data.tabelchat, {
status: data.status
});
});
/*
socket.on('disconnect', function () {
console.log( "Client disconnected !" );
});
*/});
And this is my Android code
try {
//if you are using a phone device you should connect to same local network as your laptop and disable your pubic firewall as well
socket = IO.socket("http://192.168.100.13:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
refreshChat(url);
getTabelKelas();
getDiskusiChat(sharedDiskusi.getSpdiskusi());
private void getDiskusiChat(String tabelChat) {
socket.on(tabelChat, new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String jsonStr = data.toString();
Log.d("cek", "cek data : "+data);
Toast.makeText(mContext, (CharSequence) data, Toast.LENGTH_LONG).show();
try {
//extract data from fired event
String cek = String.valueOf(data.getJSONArray("idleveluser"));
// String nickname = data.getString("senderNickname");
// String message = data.getString("message");
// make instance of message
//
// Message m = new Message(nickname,message);
// Message m = new Message(nickname,message);
//
//
// //add the message to the messageList
//
// MessageList.add(m);
//
// // add the new updated list to the dapter
// chatBoxAdapter = new ChatBoxAdapter(MessageList);
//
// // notify the adapter to update the recycler view
//
// chatBoxAdapter.notifyDataSetChanged();
//
// //set the adapter for the recycler view
//
// myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
i have try to Toast and log it but did not appear.
Can anyone help me to retrieve data ?I confuse how to get data if the data in the form of an array. I'm helped if someone helps me.
Sry for my bad english brother.
This is my log
Change this code line
String cek = String.valueOf(data.getJSONArray("idleveluser"));
to
String cek = String.valueOf(data.getString("idleveluser"));
as each item in the data object is a string.
I'm working with the Bitfinex API and the version of the API is 1.
But I have a problem that can not be solved.
When I use '/v1/order/new', the server sends to the message "Key symbol was not present."
I can not find which point is the problem.
The parameter settings are as belows.
Please advise.
========== ========== ========== ==========
/**
Create Header, Param
*/
JSONObject json = new JSONObject();
json.put("request", targetURL);
json.put("nonce", Long.toString(getNonce()));
String payload = json.toString();
String payload_base64 = Base64.getEncoder().encodeToString(payload.getBytes());
String payload_sha384hmac = hmacDigest(payload_base64, apiKeySecret, ALGORITHM_HMACSHA384);
HttpTask http = new HttpTask(URL, Method.POST);
http.addHeader("X-BFX-APIKEY", apiKey);
http.addHeader("X-BFX-PAYLOAD", payload_base64);
http.addHeader("X-BFX-SIGNATURE", payload_sha384hmac);
http.setContentType("x-www-urlencoded");
http.setAcceptType("application/xml");
http.addParam("symbol", "btcusd");
http.addParam("amount", "0.01");
http.addParam("price", "0.01");
http.addParam("side", "buy");
http.addParam("type", "exchange market");
http.addParam("is_hidden", "false");
http.addParam("is_postonly", "true");
http.addParam("use_all_available", "0");
http.addParam("exchange", "bitfinex");
http.addParam("ocoorder", "false");
http.addParam("buy_price_oco", "0");
/**
Parsing Param
*/
StringBuilder sb = new StringBuilder();
Set<String> key = m_params.keySet();
int totalCount = key.size();
if (totalCount > 0) {
int index = 0;
for (Iterator<String> iterator = key.iterator(); iterator.hasNext();) {
String keyValue = (String) iterator.next();
String valueValue = (String) m_params.get(keyValue);
sb.append(String.format("%s=%s", keyValue, valueValue));
if (index < totalCount - 1) {
sb.append("&");
}
index++;
}
query = sb.toString();
}
/**
send Param
*/
if (!query.isEmpty()) {
DataOutputStream wr;
try {
wr = new DataOutputStream(m_connection.getOutputStream());
wr.writeBytes(query);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You need to put all params in payload object.
Here is my example on JAVASCRIPT:
auth_v1_request(path, params){
return new Promise((resolve, reject) => {
// console.log(this.account);
const apiKey = this.account.api_key;
const apiSecret = this.account.api_secret;
const apiPath = '/' + path;
const nonce = (Date.now() * 1000).toString();
const completeURL = `${ CONFIG.BITFINEX.API_URL }${apiPath}`;
params.nonce = nonce;
params.request = apiPath;
const payload = new Buffer(JSON.stringify(params))
.toString('base64');
const signature = crypto
.createHmac('sha384', apiSecret)
.update(payload)
.digest('hex');
const options = {
url: completeURL,
headers: {
'X-BFX-APIKEY': apiKey,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
body: JSON.stringify(params),
json: true
};
request.post(options, (error, response, res_body) => {
console.log(error);
console.log(res_body);
if(error) {
reject(error);
}
else {
let parsed;
try {
parsed = res_body;
if(parsed.message){
reject(parsed);
}
else {
resolve(parsed);
}
}
catch(err) {
reject(err);
}
}
})
});
}
I am trying to upload an Image on Java Server.the File is trnsfering from android device but saving null on server .
Here is server code
public UploadMediaServerResponse uploadFileForFunBoard(#FormDataParam("photoPath") InputStream photoInputStream,
#FormDataParam("photoPath") FormDataContentDisposition photoFileDetail,
#FormDataParam("userId") int userId, #FormDataParam("mediaType") String mediaType,
#FormDataParam("title") String title,#FormDataParam("funBoardId") int funBoardId)
{
MediaContenModel mediaContenModel = new MediaContenModel();
mediaContenModel.setFunBoardId(funBoardId);
mediaContenModel.setMediaType(mediaType);
mediaContenModel.setUserId(userId);
UploadMediaServerResponse uploadMediaServerResponse = new UploadMediaServerResponse();
boolean isMediaProcessedAndUploaded = true;
String mediaProcessingError = "";
if (photoInputStream != null && photoFileDetail != null)
{
uploadMediaServerResponse = mediaService.uploadOnServer(photoInputStream,
photoFileDetail.getFileName(), userId+"");
if (uploadMediaServerResponse != null
&& !uploadMediaServerResponse.getMediaUrl().equalsIgnoreCase("ERROR"))
{
mediaContenModel.setImageUrl(uploadMediaServerResponse.getMediaUrl());
logger.debug("ContentService --> createStroyline --> fearture Image url ::"
+ uploadMediaServerResponse.getMediaUrl());
}
else
{
isMediaProcessedAndUploaded = false;
mediaProcessingError = uploadMediaServerResponse.getMediaUrl();
logger.debug("ContentService --> createStroyline --> mediaProcessingError ::"
+ mediaProcessingError);
}
}
if (isMediaProcessedAndUploaded)
{
UploadMediaServerResponse response = funBoardService.uploadMediaContent(mediaContenModel);
uploadMediaServerResponse.setMediaUrl(response.getMediaUrl());
}
else
{
uploadMediaServerResponse.setError("Task Failed");
uploadMediaServerResponse.setStatus(ServiceAPIStatus.FAILED.getStatus());
}
return uploadMediaServerResponse;
}
here is my phonegap code
var pictureSource;
var destinationType;
function onPhotoURISuccess(imageURI)
{
console.log(imageURI);
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="photoPath";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.params = {
"userId": 1,
"funBoardId": 3,
"mediaType": 'image'
};
console.log(JSON.stringify(options));
var ft = new FileTransfer();
ft.upload(imageURI, _BaseURL+"mobile/userService/funboard/upload", win, fail, options);
}
function onPhotoDataSuccess(imageURI)
{
var imgProfile = document.getElementById('imgProfile');
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1)
{
getLocation();
}
movePic(imageURI);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function movePic(file)
{
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
function resolveOnSuccess(entry)
{
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys)
{
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory)
{
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
function successMove(entry)
{
alert(entry.fullPath);
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error)
{
alert(error.code);
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
04-14 19:33:46.010: E/FileTransfer(13550): java.io.FileNotFoundException: http:///jeeyoh/mobile/userService/funboard/upload
Thanks in Advance
Replace
options.fileKey="file";
To
options.fileKey="photoPath";