HttpRequestHandler : Sending a pdf file in response - javascript

I want server a pdf file instead of mp3 file please help
private HttpRequestHandler mRequestHandler = new HttpRequestHandler()
{
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException
{
try{
File file = new File("/mnt/sdcard/Music/song.mp3");
FileEntity body = new FileEntity(file, "audio/mpeg");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition","attachment; filename=song.mp3");
response.setEntity(body);
}catch(Exception e)
{
e.printStackTrace();
}
}
};

Change the content type to application/pdf
#Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException
{
try{
File file = new File("/my/path/file.pdf");
FileEntity body = new FileEntity(file, "application/pdf");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition","attachment; filename=file.pdf");
response.setEntity(body);
}catch(Exception e)
{
e.printStackTrace();
}
}
};
you can check mime types here

Related

Why is my controller config not allowing a cross-origin call?

I get this error message in my Browser Console, even though I think everything should be working. I´m just starting out with all of this, so I would be very gratefull if someone could help me out here.
Error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/api/file/upload/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
This is my Post-Method in the Controller:
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600, allowCredentials="true")
#PostMapping("/upload/")
public ResponseEntity<Object> uploadBild(#RequestParam("file") MultipartFile file,
#AuthenticationPrincipal User user,
HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
System.out.println("File received Upload: " + file);
String[] allowedTypes = {"image/jpeg", "image/jpg", "image/png"};
if (!Arrays.asList(allowedTypes).contains(file.getContentType())) {
Map<String, String> responseBody = new HashMap<>();
responseBody.put("error", "Invalid file type. Only jpeg and png files are allowed");
return new ResponseEntity<>(responseBody, HttpStatus.BAD_REQUEST);
}
PictureDTO pictureDTO = new PictureDTO();
pictureDTO.setTitle(file.getOriginalFilename());
Picture picture = pictureService.save(pictureDTO, user);
if (uploadService.saveFile(file, picture.getId())){
Map<String, String> response1 = new HashMap<>();
response1.put("message", "File uploaded successfully");
return new ResponseEntity<>(response1, HttpStatus.OK);
}
else {
Map<String, String> response2 = new HashMap<>();
response2.put("message", "File upload failed");
return new ResponseEntity<>(response2, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
These are my application.properties:
spring.data.mongodb.uri=mongodb://user1:pass1#localhost:27017/?authSource=db1&replicaSet=rs1
spring.data.mongodb.database=db1
com.example.demo.accessTokenExpirationMinutes=5
com.example.demo.refreshTokenExpirationDays=30
accessTokenSecret=12345
refreshTokenSecret=54321
spring.web.cors.enabled=true
spring.web.cors.allow-origin=http://localhost:4200
spring.web.cors.allow-credentials=true
This is my WebSecurityConfiguration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(accessTokenEntryPoint).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(accessTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
And this is my frontend API Call:
uploadFile(file: File) {
const formData = new FormData();
formData.append('file', file);
this.http.post('http://localhost:8080/api/file/upload/', formData,{headers: {"Content-Type":"multipart/form-data"}}).subscribe(response => {
console.log(response);
// this.watermarkImage(file, "COPYRIGHT")
});
}
I hope this is enough information. Thank you very much! Best regards!

Unable to implement websockets on non https server implementing springboot

I've been working on a project with my team for about a week and we still haven't been able to get websockets to work. We're running the whole server on our own machines for testing purposes and we're unsure if it'll be hosted on an HTTPS server in the future.
Using springboot we've been able to make all the basic web-site stuff work like login/registration and more, but websockets don't seem to work.....
Here's the code that we use:
package com.kanbanboard.websocket;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
#ServerEndpoint(
value="/events/{boardid}",
decoders = MessageDecoder.class,
encoders = MessageEncoder.class
)
public class WebSocketServer{
private Session session;
private static final Set<WebSocketServer> socketEndpoint = new CopyOnWriteArraySet<>();
private static final HashMap<String, String> users = new HashMap<>();
#OnOpen
public void onOpen(Session session, #PathParam("boardid") String boardid) throws IOException, EncodeException {
this.session = session;
socketEndpoint.add(this);
users.put(session.getId(), boardid);
Message msg = new Message();
msg.setFrom(boardid);
msg.setContent("Connected!");
broadcast(msg);
}
#OnMessage
public void onMessage(Session session, String message) throws IOException, EncodeException {
Message msg = new Message();
msg.setFrom(users.get(session.getId()));
broadcast(msg);
System.out.println("["+session.getId()+"]: "+message);
}
#OnClose
public void onClose(Session session) throws IOException, EncodeException {
socketEndpoint.remove(this);
Message message = new Message();
message.setFrom(users.get(session.getId()));
message.setContent("Disconnected!");
broadcast(message);
System.out.println("Connection has been with: "+session.getId());
}
#OnError
public void onError(Session session, Throwable throwable) {
System.out.println("Error reached!!!");
System.out.println(throwable);
}
private static void broadcast(Message message)
throws IOException, EncodeException {
socketEndpoint.forEach(endpoint -> {
synchronized (endpoint) {
try {
endpoint.session.getBasicRemote().
sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
}
The javascript we use on the client side to test the connection:
let ws = new WebSocket("ws://localhost:8080/events/1")
ws.onopen = function(ev) {
console.log("Opened connection")
ws.send("Hello World")
}
What the javascript code returns:
GETws://localhost:8080/events/1
[HTTP/1.1 404 7ms]
Firefox can’t establish a connection to the server at ws://localhost:8080/events/1. debugger eval code:1:9
Yes we've tried it on chrome too...
The thing is, when we use wss:// instead of ws:// we do get an output on intelliJ which looks like this:
java.lang.IllegalArgumentException: Invalid character found in method name [0x160x030x010x020x000x010x000x010xfc0x030x030xce0xea0x97_h0xd30xbe0xe90x080xea#0xf10xben0xdb0xf30x8cc0xd80xe30x890xfaD0xe80x1c0xb80xe80xbf0xa50x8c0xb90xc1 ]. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:419) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:271) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
Any help or recommendations greatly appreciated.
Found the solution, you're not getting it.
(Just don't use Websockets and sprinboot together, it's not worth it.)

RequestDispatcher.forward() not forwarding when servlet called via Ajax POST

I have a login page where I authenticate the user via firebase and send the request to a servlet. When I hit the submit button with correct authentications, the firebase authentication works, servlet get called but in browser I see see an error.
First of all, this is my javascript code
function toggleSignIn() {
if (firebase.auth().currentUser) {
alert('existing user');
firebase.auth().signOut();
} else {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().signInWithEmailAndPassword(email, password).then(function (firebaseUser) {
var email = firebase.auth().currentUser.email;
const options = {
method: 'POST',
url: 'LoginValidator',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `email=${email}`
}
url = 'LoginValidator'
fetch(url, options)
.then(response = > response.json())
.then(data = > console.log(data))
.catch(e = > console.error(e))
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
document.getElementById('quickstart-sign-in').disabled = false;
});
}
document.getElementById('quickstart-sign-in').disabled = true;
}
HTML
<div id="login-box" class="col-md-12">
<div class="form-group">
<input type="text" name="email" id="email" class="form-control login-input" placeholder="username">
</div>
<div class="form-group">
<input class="form-control login-input" type="password" placeholder="Password" id="password" name="password">
<i id="open" class="fa fa-eye fa-2x"></i>
<i id="closed" class="fa fa-eye-slash fa-2x"></i>
</div>
<div class="form-group">
<input type="submit" id="quickstart-sign-in" name="quickstart-sign-in"
class="form-control btn btn-info btn-md login-bt" value="Login" onclick="toggleSignIn()">
</div>
<div class="form-group text-center forgot">
Forgot username / password?
</div>
</div>
Below is my servlet
LoginValidator.java
public class LoginValidator extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String email = request.getParameter("email");
System.out.println("Printing email: "+email);
try {
System.out.println("inside try");
User user = new User();
UserRight userRight = new UserRight();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//Get user
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<User> call = endPoint.getUserByEmail(email);
user = call.execute().body();
System.out.println(user.getName());
//Get user rights
Call<UserRight> userRightCall = endPoint.getUserRightByID(user.getUserRights().getIduserRight());
userRight = userRightCall.execute().body();
System.out.println(userRight.getUserRight());
if(userRight.getUserRight().equals("admin"))
{
response.getWriter().write("{url:LoadSellPendingApprovals}");
}
else
{
response.getWriter().write("{url:index.html}");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The LoginValidator calls LoadSellPendingApprovals, below is its code
public class LoadSellPendingApprovals extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
List<ProductSellAdvertisement> categoryList = new ArrayList<ProductSellAdvertisement>();
try {
System.out.println("INSIDE LoadSellPendingApprovals");
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<List<ProductSellAdvertisement>> call = endPoint.getAllPendingApprovals();
categoryList = call.execute().body();
for (int i = 0; i < categoryList.size(); i++) {
System.out.println(categoryList.get(i).getProduct().getProductName());
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/product-sell-pending-approvals.jsp");
request.setAttribute("approvalList", categoryList);
requestDispatcher.forward(request, response);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is the error I get
SyntaxError: Unexpected token < in JSON at position 0
at (index):71
The line being pointed in my javascript code is this - .then(response => response.json())
The expected behavior is this
User enter credentials
Authenticate the credentials with firebase javascript api
If credentials are correct send them to the LoginValidator servlet where it will further check user`s authenticity.
Then the LoginValidator send the request to LoadSellPendingApprovals where it will execute the following code
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/jsp/product-sell-pending-approvals.jsp");
request.setAttribute("approvalList", categoryList);
requestDispatcher.forward(request, response);
In addition to the error I get, I never get forwarded to the JSP page as well. How can I fix this problem?
I am coming from java and mobile background, have no much clue on Javascript technology. Therefor appreciate detailed clear answers.
Your error indicates that the result "body" does not contain JSON but HTML:
Unexpected token < in JSON at position 0
JSON would look like this:
{ key: value }
HTML looks like this:
<html>....</html>
As the error states, the first < (position 0) is the "unexpected token". What ever is reading the body was expecting a {.
One reason for this might be that the request you are sending is redirected to a login page and therefore you get HTML instead of the expected JSON. Or you get an error page which you are trying to pass to your JSON parser.
Unfortunately, with this little information it is hard to tell. You should debug your code and check the response you are getting.

Getting 404 in WebSocket connection

I have a backend java code for websocket.
SessionEndpoint:
#ServerEndpoint("/session")
public class SessionEndpoint {
private static Set<SessionEndpoint> sessionEndpoints = new CopyOnWriteArraySet<>();
#OnMessage
public void onMessage(Session session, String sessionId) {
Map<String, Object> attributes = new HashMap<>();
attributes.put("sessionId", sessionId);
sessionEndpoints.forEach(endpoint -> {
synchronized (endpoint) {
try {
session.getBasicRemote().sendObject(attributes);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
});
}
}
Trying to connect to websocket from javascript, code is given below.
let webSocket = new WebSocket('ws://localhost:9999/session');
webSocket.onopen = () => webSocket.send('hello');
webSocket.onmessage = function(response) {
console.log(response);
};
I get 404 response code while connecting to websocket. How should I connect to webscoket from javascript ?

Access data after page load isn't successful

I want to access data after page load, but it doesn't work. It seems not to call the getConnection function in jsp and it doesn't call response Json. I don't know why it doesn't work. What's wrong with my code and how to fix it? Thank you very much.
MyServlet.java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
/**
* Servlet implementation class MyServlet
*/
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ArrayList<Dish> country=new ArrayList<Dish>();
country=SQLConnection.getAllDish();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Dish>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
SQLConnection.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
public class SQLConnection {
// java.sql.Connection connection;
private static Connection connection = null;
static String url, driver, username, password;
public static Connection getConnection() {
if (connection != null)
return connection;
else {
try {
Properties prop = new Properties();
InputStream inputStream = SQLConnection.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
driver = prop.getProperty("driver");
url = prop.getProperty("url");
username = prop.getProperty("user");
password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
public static ArrayList<Dish> getAllDish() {
ArrayList<Dish> arrDish = null;
try {
//Creating a statement object
Statement stmt = connection.createStatement();
//Executing the query and getting the result set
ResultSet rs = stmt.executeQuery("select * from dish");
arrDish = new ArrayList<Dish>();
//Iterating the resultset and printing the 3rd column
while (rs.next()) {
Dish item = new Dish(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDouble(4), rs.getString(5),
rs.getString(6), rs.getString(7), rs.getString(8), rs.getInt(9), rs.getInt(10), rs.getInt(11), rs.getInt(12));
arrDish.add(item);
}
//close the resultset, statement and connection.
rs.close();
stmt.close();
connection.close();
return arrDish;
} catch (SQLException e) {
e.printStackTrace();
}
return arrDish;
}
}
hello.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html>
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/style.css" />
<title><fmt:message key="title" /></title>
</head>
<body bgcolor="#FEDDFF">
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/slider.js"></script>
<script>
$(window).ready(function() {
$.get('MyServlet',function(responseJson) {
if(responseJson!=null){
$("#dishes").find("tr:gt(0)").remove();
var table1 = $("#dishes");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).int(value['dishid']);
rowNew.children().eq(1).int(value['userid']);
rowNew.children().eq(2).text(value['dishName']);
rowNew.children().eq(3).double(value['numberOfPeople']);
rowNew.children().eq(4).text(value['dishImg']);
rowNew.children().eq(5).text(value['ingredient']);
rowNew.children().eq(6).text(value['step']);
rowNew.children().eq(7).text(value['descOfDish']);
rowNew.children().eq(8).int(value['category1']);
rowNew.children().eq(9).int(value['category2']);
rowNew.children().eq(10).int(value['category3']);
rowNew.children().eq(11).int(value['rate']);
rowNew.appendTo(table1);
});
}
});
});
</script>
<div id="tabledish">
<table cellspacing="0" id="dishes">
<tr>
<th scope="col">dishid</th>
<th scope="col">userid</th>
<th scope="col">dishName</th>
<th scope="col">numberOfPeople</th>
<th scope="col">dishImg</th>
<th scope="col">ingredient</th>
<th scope="col">step</th>
<th scope="col">descOfDish</th>
<th scope="col">category1</th>
<th scope="col">category2</th>
<th scope="col">category3</th>
<th scope="col">rate</th>
</tr>
</table>
</div>
</body>
in getAllDish() of SQLConnection
Check and call the getConnection();
try{
if(connection==null)
getConnection();
Statement stmt = connection.createStatement();
...

Categories

Resources