Upload image using Javascript port - javascript

Hi I'm trying to upload image via the Java script port. Logging seems to work and it seems the server is not receiving the "file" object. Here is my code (note this works via simulator):
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
picture = (String) evt.getSource();
if (picture != null) {
String url = "...";
MultipartRequest request = new MultipartRequest();
request.setUrl(url);
try {
request.addData("file", picture, "image/png");
request.setFilename("file", "myPicture.png");
request.setPost(true);
request.addArgument("submit", "yes");
NetworkManager.getInstance().addToQueueAndWait(request);
Log.p("initVars(..) MultipartRequest error code: "
+ request.getResponseCode(), Log.DEBUG);
String data = new String(request.getResponseData());
Log.p(data, Log.DEBUG);
} catch (IOException err) {
err.printStackTrace();
}
}
}
}, Display.GALLERY_IMAGE);

If the JavaScript deployed on the same server as the upload destination?
Assuming you are in the same server try using the build hint: javascript.inject_proxy=false. This will disable the proxy servlet and create direct communication to the JavaScript port.
If you are not in the same server make sure you are using the WAR distribution with the proxy servlet within so it can redirect your upload.

Related

How to connect android studio (developing mobile apps) with phpmyadmin database in a server? [duplicate]

Android 3.3 API 18
Hello,
I am developing my first App using android. The App will have to connect to an online database to store user data.
I am looking for a cloud storage with a MySQL database included. However, can my App connect directly to this MySQL database and push and pull data from it? Or is there other things I need to do?
Many thanks for any suggestions,
Yes you can do that.
Materials you need:
WebServer
A Database Stored in the webserver
And a little bit android knowledge :)
Webservices (json ,Xml...etc) whatever you are comfortable with
1. First set the internet permissions in your manifest file
<uses-permission android:name="android.permission.INTERNET" />
2. Make a class to make an HTTPRequest from the server
(i am using json parisng to get the values)
for eg:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
3. In your MainActivity Make an object of the class JsonFunctions and pass the url as an argument from where you want to get the data
eg:
JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");
4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want
and if you have any problem you can follow this blog
he gives excellent android tutorials AndroidHive
Since the above answer i wrote was long back and now HttpClient, HttpPost,HttpEntity have been removed in Api 23. You can use the below code in the build.gradle(app-level) to still continue using org.apache.httpin your project.
android {
useLibrary 'org.apache.http.legacy'
signingConfigs {}
buildTypes {}
}
or You can use HttpURLConnection like below to get your response from server
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
or You can use 3rd party Library like Volley, Retrofit to call the webservice api and get the response and later parse it with using FasterXML-jackson, google-gson.
What you want to do is a bad idea. It would require you to embed your username and password in the app. This is a very bad idea as it might be possible to reverse engineer your APK and get the username and password to this publicly facing mysql server which may contain sensitive user data.
I would suggest making a web service to act as a proxy to the mysql server. I assume users need to be logged in, so you could use their username/password to authenticate to the web service.
You can use PHP, JSP, ASP or any other server side script to connect with mysql database and and return JSON data that you can parse it to in your android app this link how to do it
step 1 : make a web service on your server
step 2 : make your application make a call to the web service and receive result sets
Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...
you can definitely make such application, you need to make http conection to the database, by calling a php script which will in response run specific queries according to your project, and generated the result in the form of xml, or json formate , whihc can be displayed on your android application!.
for complete tutorial on how to connect android application to mysql i would recommend to check out this tutorila
It is actually very easy. But there is no way you can achieve it directly. You need to select a service side technology. You can use anything for this part. And this is what we call a RESTful API or a SOAP API. It depends on you what to select.
I have done many project with both. I would prefer REST.
So what will happen you will have some scripts in your web server, and you know the URLs. For example we need to make a user registration. And for this we have
mydomain.com/v1/userregister.php
Now from the android side you will send an HTTP request to the above URL. And the above URL will handle the User Registration and will give you a response that whether the operation succeed or not.
For a complete detailed explanation of the above concept. You can visit the following link.
**Android MySQL Tutorial to Perform CRUD Operation**
Look at this online backend.
Parse.com
They offer push notifications, social integration, data storage, and the ability to add rich custom logic to your app’s backend with Cloud Code.

How can i use socket communication between java server and javascript client?

I'm trying to connect java Server and Javascript client with socket.io. When i see the debugger at browser, it looks like the data is being received, but i'm getting this error: "Reason: CORS header 'Access-Control-Allow-Origin' missing" and i am not being able to print data at client-side.
import...
public class MeuServerSocket {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public MeuServerSocket(int port) {
// starts server and waits for a connection
try {
while(true){
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
saida.flush();
// send available data from server to client
saida.writeObject("Texto enviado 123...");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
boolean fim = false;
while (!line.equals("Over") && !fim)
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
fim = true;
System.out.println(i.toString());
}
}
System.out.println("Closing connection");
// close connection
socket.close();
saida.close();
in.close();
}
} catch (IOException i) {
System.out.println(i);
}catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String[] args) {
MeuServerSocket server = new MeuServerSocket(5000);
}
}
var socket = io('http://localhost:5000');
socket.on('connect', function () {
socket.send('hi \nOver');
socket.on('get', function (msg) {
// my msg
console.log('msg: '+msg)
})
socket.on('disconnect',()=>{
console.log('disconnected')
})
})
When i look at Firefox network, i see that the data was sent inside one of the packages...
https://imgur.com/vDAS00B
The biggest issue I'm seeing here is a misunderstanding of socket.io. Socket.io for javascript is not compatible with the Socket library in java. The naming conventions can be confusing for sure.
socket.io is a library that is related to web sockets (ws://). It implements all the basic websocket features plus some bonuses.
What you have for your java code is a TCP socket server. While websockets and socket.io are built on TCP socket, you can not connect a socket.io client to a "naked" socket server.
SOLUTION:
If your javascript is running from nodejs, you can use their net library found here. If you are running javascript from a webbrowser, than you are limited to websockets, which means you're going to change your java code to a websocket server. You can find a library for that somewhere online.
TLDR: Use ws://... instead of http://....
Details:
https is used for HTTP protocol. In such case it is correct that browser first asks your server if CORS is allowed. You have not enabled CORS. That's why it is normal that browser refuses to send CORS request.
But you say you want to use Web Sockets. Then you should use ws://, not http://. For Web Sockets there is no CORS policy and browser will send your request without CORS restrictions.

Spring 4 / ExtJs 6 File Upload - ExtJs connection refused error when file size limit exceed

I have a file upload form that's working correctly except when I send a file that is larger than the size that I've configured in Spring.
I've used the same code before on another application that was written in Spring, the difference is I was using ExtJs 4.2, now using ExtJs 6.0. As well the old app used Spring security 3, the new one 4.
The Spring side has been configured to block files that exceed 3MB.
From WebMvcConfig.java:
#Bean(name="multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver()
{
ToolkitCommonsMultipartResolver resolver = new ToolkitCommonsMultipartResolver();
resolver.setMaxUploadSize(Constants.UPLOAD_MAX_FILE_SIZE);
return resolver;
}
From ToolkitCommonsMultipartResolver:
public class ToolkitCommonsMultipartResolver extends CommonsMultipartResolver {
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
protected MultipartParsingResult parseRequest(final HttpServletRequest request) {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
List fileItems;
try {
fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
System.out.println("******* MultipartParsingResult limit exceeded");
request.setAttribute("fileSizeExceeded", ex);
fileItems = Collections.EMPTY_LIST;
}
catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
return parseFileItems(fileItems, encoding);
}
}
My custom Controller:
#PreAuthorize("hasAuthority('ACTIVITY_CREATE_UPDATE')")
#RequestMapping(value = "/activity/editActivity", method = RequestMethod.POST, consumes="multipart/form-data", produces=MediaType.TEXT_HTML_VALUE )
public #ResponseBody String editActivity(#Valid ActivityBean bean, BindingResult result, HttpServletRequest request) {
//WebMvcConfig.commonsMultipartResolver will throw exception if file size exceeds the max size
//Passed as a request attribute
Object exception = request.getAttribute("fileSizeExceeded");
if (exception != null && FileUploadBase.SizeLimitExceededException.class.equals(exception.getClass()))
{
log.info("File too large");
String msg = "The file you sent has exceeded the maximum upload size of " + (Constants.UPLOAD_MAX_FILE_SIZE / 1000000L) + " MB.";
return "{\"success\" : false, \"msg\" : \"" + msg + "\"}";
}
...other code to process request
}
}
Spring security http tag has the following code to allow frame content to be displayed from the server (X-Frame-Options). Before I added this code all the responses were blocked (save was successful or not):
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
Spring will return success: false with the message I've setup in the controller. In chrome, I see connection aborted (net::ERR_CONNECTION_ABORTED). Deep in ExtJs code I found the method onComplete:
/**
* Callback handler for the upload function. After we've submitted the form via the
* iframe this creates a bogus response object to simulate an XHR and populates its
* responseText from the now-loaded iframe's document body (or a textarea inside the
* body). We then clean up by removing the iframe.
* #private
*/
onComplete: function()
Inside onComplete() there is a call after the upload
doc = me.getDoc();
This method tries to access the content returned from the server in the iFrame is blocked. It seems as though the Spring security header isn't working in this case. There is a catch (e) that is throwing the error:
Uncaught DOMException: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.(…)
Does anyone know how to resolve this issue? I can disable the Muitipart resolver and accept the complete file, and do size validation in my custom code. It makes more sense to block the file upload first if it exceeds the size. Is this a Spring security 4 or ExtJs6 issue?

Connecting to websocket using C# (I can connect using JavaScript, but C# gives Status code 200 error)

I am new in the area of websocket.
I can connect to websocket server using JavaScript using this code:
var webSocket = new WebSocket(url);
But for my application, I need to connect to the same server using c#. The code I am using is:
ClientWebSocket webSocket = null;
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(url), CancellationToken.None);
3rd line of the code results following error:
"Server returned status code 200 when status code 101 was expected"
After little bit of survey, I realised that somehow server can't switch http protocol to websocket protocol during connection process.
Am I doing anything stupid in my C# code or there is something going wrong with the server. I don't have any access to the server, as the url I am using is a third party one .
Could you please give me any suggestion regarding the issue?
TL; DR:
Use ReceiveAsync() in loop until Close frame is received or CancellationToken is canceled. That's how you get your messages. Sending is straightworward, just SendAsync(). Do not use CloseAsync() before CloseOutputAsync() - because you want to stop your receiving loop first. Otherwise - either the CloseAsync() would hang, or if you use CancellationToken to quit ReceiveAsync() - the CloseAsync() would throw.
I learned a lot from https://mcguirev10.com/2019/08/17/how-to-close-websocket-correctly.html .
Full answer:
Use Dotnet client, here, have an example cut out from my real life code, that illustrate how the handshaking is made. The most important thing most people don't understand about how the thing operates is that there is no magic event when a message is received. You create it yourself. How?
You just perform ReceiveAsync() in a loop that ends, when a special Close frame is received. So when you want to disconnect you have to tell the server you close with CloseOutputAsync, so it would reply with a similar Close frame to your client, so it would be able to end receiving.
My code example illustrates only the most basic, outer transmission mechanism. So you send and receive raw binary messages. At this point you cannot tell the specific server response is related to the specific request you've sent. You have to match them yourself after coding / decoding messages. Use any serialization tool for that, but many crypto currency markets use Protocol Buffers from Google. The name says it all ;)
For matching any unique random data can be used. You need tokens, in C# I use Guid class for that.
Then I use request / response matching to make request work without dependency on events. The SendRequest() methods awaits until matching response arrives, or... the connection is closed. Very handy and allows to make way more readable code than in event-based approach. Of course you can still invoke events on messages received, just make sure they are not matched to any requests that require response.
Oh, and for waiting in my async method I use SemaphoreSlim. Each request puts its own semaphore in a special dictionary, when I get the response, I find the entry by the response token, release the semaphore, dispose it, remove from the dictionary. Seems complicated, but it's actually pretty simple.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace Example {
public class WsClient : IDisposable {
public int ReceiveBufferSize { get; set; } = 8192;
public async Task ConnectAsync(string url) {
if (WS != null) {
if (WS.State == WebSocketState.Open) return;
else WS.Dispose();
}
WS = new ClientWebSocket();
if (CTS != null) CTS.Dispose();
CTS = new CancellationTokenSource();
await WS.ConnectAsync(new Uri(url), CTS.Token);
await Task.Factory.StartNew(ReceiveLoop, CTS.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
public async Task DisconnectAsync() {
if (WS is null) return;
// TODO: requests cleanup code, sub-protocol dependent.
if (WS.State == WebSocketState.Open) {
CTS.CancelAfter(TimeSpan.FromSeconds(2));
await WS.CloseOutputAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);
await WS.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
WS.Dispose();
WS = null;
CTS.Dispose();
CTS = null;
}
private async Task ReceiveLoop() {
var loopToken = CTS.Token;
MemoryStream outputStream = null;
WebSocketReceiveResult receiveResult = null;
var buffer = new byte[ReceiveBufferSize];
try {
while (!loopToken.IsCancellationRequested) {
outputStream = new MemoryStream(ReceiveBufferSize);
do {
receiveResult = await WS.ReceiveAsync(buffer, CTS.Token);
if (receiveResult.MessageType != WebSocketMessageType.Close)
outputStream.Write(buffer, 0, receiveResult.Count);
}
while (!receiveResult.EndOfMessage);
if (receiveResult.MessageType == WebSocketMessageType.Close) break;
outputStream.Position = 0;
ResponseReceived(outputStream);
}
}
catch (TaskCanceledException) { }
finally {
outputStream?.Dispose();
}
}
private async Task<ResponseType> SendMessageAsync<RequestType>(RequestType message) {
// TODO: handle serializing requests and deserializing responses, handle matching responses to the requests.
}
private void ResponseReceived(Stream inputStream) {
// TODO: handle deserializing responses and matching them to the requests.
// IMPORTANT: DON'T FORGET TO DISPOSE THE inputStream!
}
public void Dispose() => DisconnectAsync().Wait();
private ClientWebSocket WS;
private CancellationTokenSource CTS;
}
}
BTW, why use other libraries than the .NET built in? I can't find any reason other than maybe poor documentation of the Microsoft's classes. Maybe - if for some really weird reason you would want to use modern WebSocket transport with an ancient .NET Framework ;)
Oh, and I haven't tested the example. It's taken from the tested code, but all inner protocol parts were removed to leave only the transport part.
Since WebsocketSharp is not .NET Core compatible I suggest using websocket-client instead.
Here's some sample code
static async Task Main(string[] args)
{
var url = new Uri("wss://echo.websocket.org");
var exitEvent = new ManualResetEvent(false);
using (var client = new WebsocketClient(url))
{
client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message: {msg}"));
await client.Start();
await client.Send("Echo");
exitEvent.WaitOne();
}
Console.ReadLine();
}
Be sure to use ManualResetEvent. Otherwise it doesn't work.
If you connect with a WebSocket client and you get an HTTP 200 as response, means that probably you are connecting to the wrong place (host, path and/or port).
Basically, you are connecting to a normal HTTP endpoint that is not understanding your WebSocket requirement, and it is just returning the "OK" response (HTTP 200). Probably the WebSocket server runs in another port or path in the same server.
Check your URL.
Not quite sure what happened to WebSocketSharp nuget package, however I noticed that now WebSocket# is showing up as most relevant result in nuget repo. It took me some time before I realized that Connect() is now returning Task, hopefully this example will be useful to someone:
using System;
using System.Threading.Tasks;
using WebSocketSharp;
namespace Example
{
class Program
{
private static void Main(string[] args)
{
using (var ws = new WebSocket(url: "ws://localhost:1337", onMessage: OnMessage, onError: OnError))
{
ws.Connect().Wait();
ws.Send("Hey, Server!").Wait();
Console.ReadKey(true);
}
}
private static Task OnError(ErrorEventArgs errorEventArgs)
{
Console.Write("Error: {0}, Exception: {1}", errorEventArgs.Message, errorEventArgs.Exception);
return Task.FromResult(0);
}
private static Task OnMessage(MessageEventArgs messageEventArgs)
{
Console.Write("Message received: {0}", messageEventArgs.Text.ReadToEnd());
return Task.FromResult(0);
}
}
}
All the libraries mentioned above are Wrappers. The .Net Frameworks class doing this is System.Net.WebSockets.ClientWebSocket
Websocket URLs should start with ws:// or wss:// where the latter is secure websocket.

How do I connect to a local Android Server from a Chromecast?

What I am trying to do is start a local server on my Android Device and from a Chromecast connect to the Android Server so that I can send image data from the android to a Chromecast.
What I've done so far is set up a ServerSocket on the Android that is binded to the 127.0.0.1 and then send the localhost information (port number) in a message to the chromecast which tells it the serversocket is ready to accept connections and instructs the Chromecast to connect to the server. But I have no idea how I should be connecting to it. I've tried using WebSockets to connect to the ServerSocket but I'm getting
WebSocket connection to 'ws://localhost:9147/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I've changed the port number, tried both "ws" and "wss" and I've tried searching for the answer but everything I've come across has been "how to connect android to a server" or "how to connect an Android server to an Android client" so I appologize if this is a repost.
What I was planning on doing is using Base64 image encoding to send a String with the image data to the chromecast and then set the image src to that. I obviously not want to do this using Cast.CastAPI.sendMessage().
To be clear, I am looking for a way to connect to an Android server using JavaScript.
The Android code runs fine, the Chromecast gets the message but when it tries to connect it fails.
Android Code:
Runnable bitmapSender = new Runnable() {
private ServerSocket serverSocket;
public static final int SERVERPORT = 9147;
#Override
public void run() {
Socket socket = null;
try {
Log.d(TAG, "Socket binding attempt");
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SERVERPORT));
String message = createJsonMessage(MessageType.socket, "wss://localhost:"+ SERVERPORT);
sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
Log.d(TAG, "Socket thread");
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
BitmapExecutorService.execute(commThread);
}catch(IOException e){
e.printStackTrace();
}
}
}
};
Javascript:
function connectToSocket(source){
//Connect to socket
window.socket = new WebSocket(source);
socket.onopen = function() {
socket.send('Hello Android');
};
window.socket.onmessage = function(event) {
console.log('Received a message from the server!', data);
var jsonObj = JSON.parse(event.data)
if(jsonObj.type == "image"){
console.log('Image sent :)');
var source = 'data:image/png;base64,'.concat(jsonObj.data)
displayEncodedImage(source);
}
};
Thanks
edit: Update
I was trying to connect through localhost. This didn't work like I thought it would. I still haven't got the image sending working but I now have the handshake. What I needed to do was send the IP Address of the phone. I did so by adding the ACCESS_WIFI_STATE permission to the manifest and obtaining the IP Address with the following code:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

Categories

Resources