Converting Byte[] to Image - javascript

I want to convert byt[] to image in client side. I have tried the below code but it isn't working. I receive the data1 value but not able to convert it to image.
Client Side :
function getPic(name) {
$.post("/Chat/ProfliePic", {
name : name+".png"
}, function(data1, status) {
alert(data1);
$("#profImg").attr("src","data:image/png;base64," + data1);
});
}
Server Side :
package servlets;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ProfliePic")
public class ProfliePic extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProfliePic() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
File f = new File("/Users/shilu/MyProject/Chat/Photo/" + name);
byte[] data = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new java.io.FileInputStream(f));
in.readFully(data);
in.close();
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
out.write(data);
out.flush();
out.close();
}
Please tell me where I went wrong...

Related

Cross Origin requests at server side

Hi I am facing issue in cross origin requests at server side when trying to open file which is retrieved from database using java.I am unaware of this cross orgin requests.When file is clicked then it is giving error as
jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/JR00432239/Desktop/trial/src/temp/filetest1.docx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Can anyone please help me to resolve this issue.
Here is my java code:
package fileretrieve;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import dbConnection.Dbconn;
#MultipartConfig
public class FileRetrieve extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String onelevel=request.getParameter("onelevel");
Connection conn = null; // connection to the database
String message = null;
Statement st = null;// message will be sent back to client
try {
// connects to the database
conn = Dbconn.getConnection();
st = conn.createStatement();
PreparedStatement ps=conn.prepareStatement("select data from files1 where board=?");
ps.setString(1,onelevel);
//out.print("<table width=25% border=1>");
// out.print("<center><h1>Result:</h1></center>");
ResultSet rs=ps.executeQuery();
/* Printing column names */
ResultSetMetaData rsmd=rs.getMetaData();
int count=0;
while(rs.next())
{
count=count+1;
FileOutputStream fos = new FileOutputStream("C:\\Users\\JR00432239\\Desktop\\trial\\src\\temp\\filetest"+count+".docx");
fos.write(rs.getBytes(1));
fos.close();
// out.print("<tr>");
// out.print("<td>"+rsmd.getColumnName(1)+"</td>");
// out.print("<td>"+count+"</td></tr>");
// getServletContext().getRequestDispatcher("/home.html").forward(request, response);
System.out.println("writing...");
response.getWriter().write("{\"name\":\""+count+"\",\"path\":\"C:/Users/JR00432239/Desktop/trial/src/temp/filetest"+count+".docx\"}");
}
// out.print("</table>");
//
}catch (Exception e2)
{
e2.printStackTrace();
}
finally{
// request.setAttribute("data", data);
// RequestDispatcher rd =request.getRequestDispatcher("userview.jsp");
//
out.close();
}
// forwards to the message page
// getServletContext().getRequestDispatcher("/home.html").forward(request, response);
}
}
Here is my html code:
Submit
Here is my javascript page:
$("#retrieve").click(function(){
$.ajax({
url : 'FileRetrieve',
method:"POST",
data : {
onelevel : $('#onelevel').val()
},
crossDomain: true,
success : function(responseText) {
var data=JSON.parse(responseText)
$("#files_data").html('')
$("#files_data").html('<table><tr><td><button onclick="getFile()">'+data.name+'</button></td></tr></table>')
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
If you're using chrome, as a simple solution try a chrome extention like Allow-Control-Allow-Origin:*
https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog
if not fixed,
run chrome using command line with the flag
path/to/chrome.exe --allow-file-access-from-files
or just switch to firefox and check whether the issue is still there
this would be a quick-fix only in the development
EDIT
As far as I know, best thing you can do is make the files available in http server and access them using http protocol.

How to call function in Cordova Plugin

I wrote a simple cordova plugin which displays an alert.
JS file: alert.js
module.exports = {
alert: function(title, message, buttonLabel, successCallback) {
cordova.exec(successCallback,
null, // No failure callback
"Alert",
"alert",
[title, message, buttonLabel]);
}
};
Java File: Alert.java
package com.acme.plugin.alert;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Alert extends CordovaPlugin {
protected void pluginInitialize() {
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (action.equals("alert")) {
alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
return true;
}
return false;
}
private synchronized void alert(final String title,
final String message,
final String buttonLabel,
final CallbackContext callbackContext) {
new AlertDialog.Builder(cordova.getActivity())
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setNeutralButton(buttonLabel, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
})
.create()
.show();
}
}
How do I call the alert function of alert.js from another js? And what parameter should i pass to map to successCallback??
according to cordova git for creating plugin see github page you can do it like this
Add the following code to wherever you need to call the plugin functionality:
‍‍‍cordova.plugins.<PluginName>.<method>();
where <PluginName> is your plugin name and <method> is your method.

android app crashes on client start

I'm trying to make an app that connects to my tcp server on my pc to send text but every time I start the thread, my app crashes. please help. I just started using android studio so im not that familiar with it.
Here's my code:
package com.example.alex.hahanice;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Handler UIHandler;
Thread Thread1 = null;
public static final int SERVERPORT = 6000;
public static final String SERVERIP = "192.168.1.76";
#Override
protected void onCreate(Bundle savedInstanceState) {
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
View view;
runOnUiThread(new Runnable() {
public void run() {
Thread1.start();
}
});
}
class Thread1 implements Runnable
{
public void run() {
Socket socket = null;
try
{
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
socket = new Socket(serverAddr, SERVERPORT);
Thread2 commThread = new Thread2(socket);
new Thread(commThread).start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class Thread2 implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public Thread2(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void run()
{
while(!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
if(read != null)
{
//UIHandler.post(new updateUIThread(read));
}
else
{
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Here's what the debugger says when I click on the button to start the thread to connect to my pc
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.hahanice, PID: 3772
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4659)
at android.view.View$PerformClick.run(View.java:19462)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4659) 
at android.view.View$PerformClick.run(View.java:19462) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5692) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.IllegalThreadStateException: Thread already started
at java.lang.Thread.checkNotStarted(Thread.java:871)
at java.lang.Thread.start(Thread.java:1025)
at com.example.alex.hahanice.MainActivity$1.run(MainActivity.java:50)
at android.app.Activity.runOnUiThread(Activity.java:5001)
at com.example.alex.hahanice.MainActivity.onClick(MainActivity.java:48)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4659) 
at android.view.View$PerformClick.run(View.java:19462) 
at android.os.Handler.handleCallback(Handler.java:733) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5692) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) 
at dalvik.system.NativeStart.main(Native Method) 
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
You are starting Thread at onCreate()
this.Thread1 = new Thread(new Thread1());
this.Thread1.start();
Then again starting the same thread at onClick()
Your problem is on this line:
Thread Thread1 = null;
You are setting the thread to a null value and that's where it says the error is coming from. Try assigning it a different value and see if that changes anything.

I am trying to play video using jquery but anchor tag not working while im trying to display video names?

package controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.sun.corba.se.spi.orbutil.fsm.Action;
import bean.Video;
import dao.Dao;
import daoimpl.daoImpl;
public class DisplayVideo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Dao dao=new daoImpl();
String action=request.getParameter("action");
if(action.equals("display")){
ArrayList<Video>al=dao.getAllVideo();
//PrintWriter pw=response.getWriter();
Gson gson=new Gson();
String json = gson.toJson(al);
System.out.println(json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
This is my servlet where im getting data in json format.
<html>
<head>
<script type="text/javascript" src='js/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
alert("on document ready");
$('#video').click(function(event) {
alert("on click");
$.post("Controller?action=display",
function (data) {
alert("key"+data);
var json = data;
alert("value"+json);
$.each(json, function(key,value) {
alert("key1"+value);
var v ="<a href=${pageContext.request.contextPath}/videos/"+value.videoUrl+"target='blank'>"+value.videoUrl+"</a>";
$(v).appendTo($content);
});
});
});
});
</script>
</head>
<body>
<div id='content'>
<button id="video">Play</button>
</div>
</body></html>
This my sucess.jsp file from here control goes to servlet and get data in json format from database i have only save video name c.mp4,java.mp4 and cpp.mp4 in database also i have create a folder named videos in my webcontent folder in my project and save videos in that folder also.Response getting properly but after printing alert inside each their is nothing print on screen.my requirment is print that all names of video and onclick of link play video in iframe or in popup window.please help me i didnt know the tags which are used.Thanks in Advance.

Use a json script from java, possible?

I am trying to create a java program that retrieves a METARs from the stations like this:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class metar{
public static void main(String[] args) throws IOException {
URL aURLGlobal=null;
Document doc;
String fichier ="stations.txt";
try {
InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
// need http protocol
String ligne;
while ((ligne=br.readLine())!=null){
URL aURL = new URL( "https://www.aviationweather.gov/adds/metars/?station_ids="+ligne+"&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&submitmet=Submit");
// System.out.println("******************city num"+aURL.toString()+"**************************");
doc = Jsoup.connect(aURL.toString()).get();
String element= doc.select("FONT").first().ownText();
System.out.println(element);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
stations.txt :
LSGG
LFMD
LFMN
LFQB
LFMK
LFCR
LFML
LFMI
LFMY
LFRK
result :
LSGG 201620Z 22018KT 7000 -RA FEW014 SCT025 OVC045 13/10 Q1010 TEMPO 4000 RA BR
LFMD 201600Z AUTO 23017G28KT 200V280 CAVOK 18/10 Q1008
LFMN 201600Z 07015KT CAVOK 17/12 Q1007 TEMPO WS ALL RWY
LFQB 201600Z AUTO 32006KT 9999 -RA BKN004/// BKN035/// BKN042/// ///TCU 08/08 Q1005
LFMK 201600Z AUTO 28015KT 240V300 CAVOK 20/03 Q1018
LFCR 201600Z AUTO 25015KT 9999 OVC018 13/10 Q1018
LFML 201530Z 25017KT CAVOK 17/10 Q1016 NOSIG
LFMI 201600Z AUTO 29014KT CAVOK 17/09 Q1016
LFMY 201600Z AUTO 28012KT 250V310 CAVOK 17/09 Q1016
LFRK 201600Z AUTO 29012KT 9999 BKN036 OVC044 09/08 Q1009
I am now looking to parse a json file METARs,
I found a metar.js script to parse any metar
http://epeli.github.io/metar.js/
My question is (I do not know too in json): did i can use it to parse all of my METARs and copied in one json file, that is to say call the file parser.js from java.
someone can help me please..
Edit :
THANKS A LOT FOR YOUR IDEA
CODE:
package tests;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class test {
public static void main(String[] args) throws IOException, ScriptException, NoSuchMethodException {
URL aURLGlobal=null;
Document doc;
String fichier ="stations.txt";
try {
InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
// need http protocol
String ligne;
while ((ligne=br.readLine())!=null){
URL aURL = new URL( "https://www.aviationweather.gov/adds/metars/?station_ids="+ligne+"&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&submitmet=Submit");
// System.out.println("******************city num"+aURL.toString()+"**************************");
doc = Jsoup.connect(aURL.toString()).get();
String element= doc.select("FONT").first().ownText();
System.out.println(element);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:\\metar.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("parseMETAR", element);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
error :
LSGG 201620Z 22018KT 7000 -RA FEW014 SCT025 OVC045 13/10 Q1010 TEMPO 4000 RA BR
Exception in thread "main" java.lang.NoSuchMethodException: No such function parse
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:197)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:381)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:187)
at tests.test.main(test.java:52)
as I told you, json is a black box for me, it is the parse function to be used in metar.js, and I put my metar parameter recevid from the previous step,
Thanks for your help

Categories

Resources