I have made a servlet program to insert image into an Oracle database. The program is as follows.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InsertImage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url=request.getParameter("image");
File image=new File(url);
FileInputStream fis;
PrintWriter pw=response.getWriter();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String str = "jdbc:oracle:thin:#localhost:1521:XE";
Connection con = DriverManager.getConnection(str,"system","root");
PreparedStatement pstmt=con.prepareStatement("insert into insertimage(image) values(?)");
fis = new FileInputStream(image);
pstmt.setBinaryStream(1, (InputStream)fis, (int)(image.length()));
int size=pstmt.executeUpdate();
if(size>0)
{
pw.println("<html>Image Uploaded Successfully.</html>");
}
else
{
pw.println("<html>Image could not be uploaded.</html>");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
And the HTML page, from where the input is coming is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form action="InsertImage" name="form1">
INSERT IMAGE
<input type="file" name="image"></input>
<input type="submit" name="upload"></input>
</form>
</body>
</html>
When I try to run this code from the HTML page, whatever picture input I give, it always throws FileNotFoundException. I can't understand why I am getting this. The stacktrace is:
java.io.FileNotFoundException: Counter-Strike-Servers.jpg (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at InsertImage.doGet(InsertImage.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
I tried to print the URL in the servlet and got only shocked.jpg and not the full filepath. Maybe the full filepath is not coming and that is the cause of not finding the file error. So how can I send the full filepath?
While uploading a file from JSP/HTML, you must have the form method set to POST with encType set to multipart/form-data. (HTTP specification)
<form action="InsertImage" method="post" encType="multipart/form-data" name="form1">
Implement the doPost method to get the same file. You may want to take a look at Apache Commons FileUpload to upload files and Stack Overflow post How to upload files to server using JSP/Servlet? for further details.
I tried one way to upload the file without using the Apache Common FileUpload and it's working.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form action="InsertImage" name="form1" method="post" enctype="multipart/form-data">
INSERT IMAGE
<input type="file" name="image"></input>
<input type="submit" name="upload"></input>
</form>
</body>
</html>
</body>
</html>
Servlet doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url=request.getParameter("image");
InputStream is = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
PrintWriter pw=response.getWriter();
pw.println("Reading file");
while ((line = reader.readLine()) != null) {
pw.println(line);
}
pw.flush();
}
Now you have to parse the file contents as per your needs. Refer blog post Upload and store files. However, I would strongly suggest using Apache Commons FileUpload for the same.
It looks like a local error in the sense that it really can't find the file specified by url. I would suggest debugging by printing out the url String and creating a dummy class to feed the doGet method a handmade request/response to make sure whether the problem is in the program itself or in some unexpected passing/formating of the request (you might want to comment out some parts of the method for this, e.g. the connection and statement part).
EDIT: Example of the dummy class (or method, in this case):
private void testDoGet() {
// I would suggest commenting out all the Connection and PreparedStatement
// parts of the doGet method so you don't have to establish the connection.
// - this is just to test if you can get to the image on your machine.
HttpServletRequest request;
//insert into request the image parameter with the string to the requested image
HttpServletResponse response //TODO initialize with some class implementing it
doGet(request, response);
// if you want to, set a breakpoint somewhere here to check
// what's in the classes now
}
Related
`
package Xcel;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class NewTest {
#Test
public void f() throws EncryptedDocumentException, InvalidFormatException, IOException
{
System.setProperty("webdriver.chrome.driver", "E:\\New Folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://127.0.0.1/login.do");
String un = NewTest.afterMethod(1, 0);
driver.findElement(By.name("username")).sendKeys(un);
String ur = NewTest.afterMethod(1, 1);
driver.findElement(By.name("pwd")).sendKeys(ur);
driver.findElement(By.xpath("//input[#type='submit']")).click();
}
public static String afterMethod(int r, int c) throwsEncryptedDocumentException, InvalidFormatException, IOException
{
FileInputStream fis = new FileInputStream("E:\\Test\\Book1.xlsx");
Workbook Wb = WorkbookFactory.create(fis);
String s1 = Wb.getSheet("Test1").getRow(r).getCell(c).getStringCellValue();
return s1;
}
}
`I Have Gave All The Test Script Correctly . But Still Am Getting an Error . The Error is
java.io.FileNotFoundException: ?E:\Test\Book1.xlsx (The filename, directory name, or volume label syntax is incorrect. [Error screen shot]
and Finally HTML Code is,
<input type="text" name="username" value="" style="width: 213px"> - Username
<input type="password" name="pwd" value="" style="width: 213px">- Password
<input type="submit" valign="absmiddle" value=" Login now ">- Login Now Button
The exception you are getting : Java.io.FileNotFoundException: ?E:\Test\Book1.xlsx (The filename, directory name, or volume label syntax is incorrect. has nothing to do with selenium , it is because your binding language in your case it is JAVA.
Suggestion 1:
Use try catch block :
try
{
FileInputStream fis = new FileInputStream("E:\\Test\\Book1.xlsx");
}
catch(Exception e)
{
System.out.println("File error !!!");
}
Suggestion 2:
It takes more care of adjusting directory separator characters in the path between targetPath and filename:
File targetFile = new File(targetPath, filename);
Suggestion 3 :
Most of the people have encountered this issue because of access permission. Just make sure your code is able to read/write the xlsx file.
I have got some of the reference , may be they will help you better :
Java file exception SO
Java file exception github
I'm trying to make a Spring MVC app with Spring boot, Spring Security and Thymeleaf.
The problem is - when i'm requesting a page with it's html and css, i'm not getting the correct MIME type for my css file, thus why Chrome cannot load it with status "canceled" and the message "Refused to apply style from 'http://localhost:8080/login' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled."
I'm linking the css file correctly:
" "
The css file is contained in:
resources -> static -> css - > style.css
I've allowed all resouces from the resources folder in the Security config file:
package org.isp.configuration;
import org.isp.services.api.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(this.userService);
authProvider.setPasswordEncoder(getBCryptPasswordEncoder());
return authProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
String[] permitted = new String[]{
"/", "/home","/register","/about","/png/**",
"/css/**","/icons/**","/img/**","/js/**","/layer/**"
};
http
.authorizeRequests()
.antMatchers(permitted).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.defaultSuccessUrl("/dashboard")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/unauthorized")
.and()
.csrf().disable();
}
#Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
This is my html page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" >
<head>
<title>Index</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
**<link rel="stylesheet" href="../static/css/style.css" type="text/css">**
</head>
<body>
<div th:include="~{fragments/navbar :: navbar}"></div>
<div class="container">
<h3>Home</h3>
<p>This is the home page of the project!</p>
</div>
<div th:include="~{fragments/footer :: footer}" class="footer"></div>
</body>
</html>
Any ideas how can i fix the incorrect MIME type? Is there any configuration im missing?
In my case, I have to permit requests for static files to get it to work.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Overide
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/js/**", "/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
I've just been struggling with the same issue, and I finally realized that it was a red herring - the real problem was 404, and the MIME type error came from Spring's handling of it. As explained in the Spring Boot docs, its built-in error handling automatically redirects to /error and outputs the error details as JSON. When I checked my logs, I saw a 404 in my webserver access log and the following in my application log:
DEBUG DispatcherServlet:869 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /error
DEBUG RequestMappingHandlerMapping:317 - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
DEBUG HttpEntityMethodProcessor:234 - Written [{timestamp=Fri Apr 06 14:06:54 PDT 2018, status=404, error=Not Found, message=No message available, path=/css/style.css}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#5ef96137]
So, your real problem is that Spring is not finding your static resources. You'll want to make sure the resources folder is in your classpath, or explicitly set the locations using the spring.resources.static-locations property.
In my case, I have used additional filter. So all kind of request will go through that filter. even css and js file used to go through that.
At this point, for some request in the ratio of 1/7 or 1/10, I get mime type issue, for css file the server returns with the type of application/javascript or application/json and ect.
Then I used #WebFilter and allows only api request to go through that filter.
#WebFilter(urlPatterns = "/api/*")
Now the css and js files not allowed in that additional filter. and then I did't find issue with mime type.
In my point of view, when we have too many filters the backend fails to handle frequent request for resources (js, css, img ...), So it returns with wrong MIME type.
Hope, this would help someone, who face this kind of issue
A client had the case today (24 nov 2021) when Spring Security was redirecting most of the requested urls to "/login" equivalent functional endpoint. No assets were loaded, and the same message you get about mimetype was in their Google Chrome console logs.
Diagnostic was done with entering the assets with wrong mimetype and see the loading of the "/login" endpoint.
It was resolved with adding some Spring Security mapping rules in their SecurityConfig.class of their Spring Boot Application, so the webapp is running well now.
Sample program...
import java.io.IOException;
import org.docx4j.Docx4jProperties;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.contenttype.ContentType;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.model.structure.PageSizePaper;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.AlternativeFormatInputPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.CTAltChunk;
public class HtmlToDoc {
public static void main(String[] args) throws Docx4JException {
String html="", s="", filepath="E://HtmlToDoc//";
try {
String html = "<html><head><title>Import me</title></head><body><p>Hello World! Sample Program</p><img src="E:/HtmlToDoc/LOGO.JPEG"/></body></html>";
Docx4jProperties.getProperties().setProperty("docx4j.PageSize", "B4JIS");
String papersize= Docx4jProperties.getProperties().getProperty("docx4j.PageSize", "B4JIS");
String landscapeString = Docx4jProperties.getProperties().getProperty("docx4j.PageOrientationLandscape", "true");
boolean landscape= Boolean.parseBoolean(landscapeString);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(PageSizePaper.valueOf(papersize), landscape);
AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html"));
afiPart.setBinaryData(html.getBytes());
//afiPart.setBinaryData(fileContent);
afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = wordMLPackage.getMainDocumentPart().addTargetPart(afiPart);
// .. the bit in document body
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId() );
wordMLPackage.getMainDocumentPart().addObject(ac);
// .. content type
wordMLPackage.getContentTypeManager().addDefaultContentType("html", "text/html");
wordMLPackage.save(new java.io.File("E://HtmlToDoc//" + "test.docx"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is working correctly in my local machine. but i moved this code to server in my word document image is not embedded but i gave correct image path [The same image path is working fine when i am converting HTML to PDF in server]. what could be the reason image is missing while running in server[linux machine and IBM websphere App Server and ApacheWeb server]. Even though all my paths(word document, image, html document) are same.
Your code relies on Word to convert the altChunk to HTML, so, if you are opening the Word document on your local machine, its not going to be able to see an image at E:/HtmlToDoc/LOGO.JPEG on the server.
You could possibly use a URL, or a data URI.
Alternatively, use docx4j-ImportXHTML, which will do the conversion without leaving anything to Word.
I am facing the issue with IE browser.It is loading the icons for first time load. but if i refresh the page the icons are not visible. Can you please tell me how to fix this from server side? This is related to Font-awesome disappears after refresh for all ie browsers ie11,ie10,ie9 . but it does nt have the complete solution
We had this same problem because we were storing the FA CSS file locally. The font #import's would fail on refreshes, probably because it does a different HTTP call than the one for the local file. We reverted to their CDN and it fixed the problem. If you downloaded the FA files and aren't pulling them in through a CDN, then change your <link> tag in your <head> to:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
Once we did that FontAwesome was being served up on every refresh without problem.
In my case i was using java and the only thing that works was this cache filter that i made.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebFilter("*")
public class CacheFilter implements Filter {
/**
* #constructor CacheFilter
* #date 28/09/2015
*/
public CacheFilter() {
//construtor
}
/* (non-Javadoc)
* #see javax.servlet.Filter#destroy()
*/
#Override
public void destroy() {
//metodo vazio
}
/* (non-Javadoc)
* #see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpServletRequest httpRequest = (HttpServletRequest) request;
String page = httpRequest.getRequestURI();
if (!page.contains("fontawesome-webfont") || !page.endsWith(".eot")){
httpResponse.setHeader("Expires", "-1");
httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
httpResponse.setHeader("Pragma", "no-cache");
}else if(page.contains("fontawesome-webfont") && page.endsWith(".eot")){
httpResponse.setHeader("Expires", "-1");
httpResponse.setHeader("Cache-Control", "public");
httpResponse.setHeader("Pragma", "cache");
}
chain.doFilter(request, response);
}
/* (non-Javadoc)
* #see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
#Override
public void init(FilterConfig fConfig) throws ServletException {
//metodo vazio
}
}
I did the same thing as https://stackoverflow.com/a/37196841/1982385 except that I did it on the reverse proxy (HAProxy) instead of from the servlet itself.
backend app
server server1 10.10.14.4:9090 check
acl is_woff capture.req.uri -m sub .woff
acl is_ttf capture.req.uri -m sub .ttf
acl is_eot capture.req.uri -m sub .eot
http-response set-header Cache-Control public if is_eot or is_woff or is_ttf
http-response set-header Expires -1 if is_eot or is_woff or is_ttf
http-response set-header Pragma cache if is_eot or is_woff or is_ttf
Suggestion provided by CV Harris is working fine. But, we didn't want to use files from CDN.
For us, icons issue occurred after upgrading Spring Security to 4.2.3. So, as given in Spring security configuration, added following in spring configuration.
defaults-disable="true"
Now icons are displayed in IE11.
I know... old question... but still relevant. I had the same issue... using a CDN worked, but not hosting the FA css myself.
Turns out it was related to caching as others have suggested. I had turned caching off for everything in the BeginRequest method below (for some reason which now escapes me... troubleshooting something else probably), but it seems that FA really wants to be cached... /shrug.
protected void Application_BeginRequest()
{
Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
Commenting this out fixed FA icons on refreshes, though I now have the task of making it a little more fine grained...
I am exporting my List to CSV file through Servlet. Everything is working fine. but i want to set default/ dynamic width for cell/column?
Here is my coding. Your swift reply will be helpful..
Thanks in advance.
package com.uson.stat.action;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ExportAction extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/CSV");
res.setHeader("Cache-Control", "public");
res.setHeader("Pragma", "public");
res.setHeader("Content-Disposition", "attachment; filename= \"test.csv"+ "\"");
String content = "Test Article"+","+"Viewed on 01-02-2010"+","+"Guest";
System.out.println("content >>>>>>" + content);
res.getOutputStream().print(content);
}
}
output will be:
Test Article Viewed on 01-01-2010 Guest
But output is displaying like this:
Test ArtiViewed on Guest
It is displaying fine in each cell. But I need to increase the size manually in Excel. file. How can i set the cell width dynamically/default size?
How to resolve this?
Gnaniyar Zubair
"How can i set the cell width dynamically/default size?"
You can't.
CSV is just the data. Nothing more. No color, no font, no width. Nothing.