I am developing a code for xcel generation and download using apache poi. LocalHost server and app server is jboss. When i run the code on localhost, a temp folder is generated in jboss's deployment folder and in that the xcel is generated and then downloaded through frontend. I am using java spring angularjs and html. This runs fine on localhost but after deploying on app server the xcel is not downloaded and it gives 500:internal server error.
angularjs controller code:
$scope.generateExcel=function(sDate,eDate,doc,search)
{
console.log("hello");
var sDate = document.getElementById('sD').value
var eDate = document.getElementById('eD').value
$scope.obj.sDate = sDate;
$scope.obj.eDate = eDate;
$scope.obj.iou = doc;
$scope.obj.du = search;
console.log($scope.obj);
$http.post('abc/generateExcel',$scope.obj).then(function()
{
//console.log(path);
$window.location.href="/ProjectName/file_name.xls";
})
.error(function()
{
console.log("Error!!");
});
};
java code:
//Method
public HttpServletResponse generateExcel ( HttpServletRequest request , HttpServletResponse response, String sD, String eD, String doc, String search)
{
//EXCEL GENERATION HERE
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=filename.xls");
//Path Specification
String path = request.getRealPath("/file_name.xls");
//System.out.println("Here...");
System.out.println(path);
FileOutputStream fileOut2 = new FileOutputStream(path);
workbook.write(fileOut2);
/*returning response*/
}
It's difficult to answer this unless one knows what's the error you are getting on the server side. Put your server code in a try-catch block. Rerun the code, and check the server logs. Paste them here.
try{
String path = request.getRealPath("/file_name.xls");
//System.out.println("Here...");
System.out.println(path);
FileOutputStream fileOut2 = new FileOutputStream(path);
workbook.write(fileOut2);
} catch(Exception e){
e.printStackTrace(); // this should print some error in server logs
}
Related
I have an akka http service. I simply return the api documentation for a get request. The documentation is in html file.
It all works fine when run within the IDE. When I package it as a jar I get error 'resource not found'. I am not sure why it can not read the html file when hosted in a jar and works fine when in IDE.
Here is the code for the route.
private Route topLevelRoute() {
return pathEndOrSingleSlash(() -> getFromResource("asciidoc/html/api.html"));
}
The files are located in resource path.
I have got this working now.
I am doing this.
private Route topLevelRoute() {
try {
InputStreamReader inputStreamReader = new InputStreamReader(getClass().getResourceAsStream("/asciidoc/html/api.html"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//Get the stream input into string builder
reader.lines().forEach(s -> strBuild.append(s));
inputStreamReader.close();
bufferedReader.close();
//pass the string builder as string with contenttype set to html
complete(HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, strBuild.toString()))
} catch (Exception ex) {
//Catch any exception here
}
}
I need your help, I'm in trouble.
I have to do one report on my project. I did it and it works good. I send request from browser and my java code generate report via jasper add response and chrome show it.
Our system engineer deploy project on last day. My report file(.pdf) couldn't load. We don't understand why? Chrome says "Failed load pdf file", Firefox and IE show bytecodes on notepad. We look to log file but no error, no exception.
Here is my java report code:
#Path("print")
#GET
#UnitOfWork
#Produces("application/pdf")
public Response print(#Context HttpServletResponse response,
#QueryParam("mbsFileOid") String mbsFileOid,
#QueryParam("followAfterDate") Date followAfterDate,
#QueryParam("fileOid") long fileOid,
#Context UriInfo allUri) throws IOException{
OutputStream stream = response.getOutputStream();
List<Commitment> commitments = commitmentDao.findAllCommitmensByFileOid(""+fileOid);
List<CommitmentsReportValue> commitmentsReportValues = new ArrayList<>();
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
for (Commitment commitment : commitments) {
CommitmentsReportValue commitmentsReportValue = new CommitmentsReportValue();
commitmentsReportValue.setAmount(commitment.getAmount().toString());
commitmentsReportValue.setSortId(""+commitment.getSortId());
commitmentsReportValue.setCommitmentDate(sdf.format(commitment.getCommitmentDate()));
commitmentsReportValues.add(commitmentsReportValue);
if(commitment.getCommitmentStatus() == Commitment.CommitmentStatus.NotPaid)
commitmentsReportValue.setStatus("Ödenmedi");
else
commitmentsReportValue.setStatus("Ödendi");
}
CoverCalculationDTO coverCoverCalculationDTO = mbsFileDao.getCoverCalculation(mbsFileOid,followAfterDate);
coverCoverCalculationDTO.setFollowTotalInterest(""+coverCoverCalculationDTO.getFollowAfterTotalInterest());
coverCoverCalculationDTO.setTotalBalance(""+coverCoverCalculationDTO.getLastTotalBalance());
MbsFile mbsFile = mbsFileDao.findById(mbsFileOid);
try {
buildAggregateReport(mbsFile,coverCoverCalculationDTO,commitmentsReportValues).toPdf(stream);
} catch (DRException e) {
LOGGER.info(e.getMessage());
}
response.addHeader("Content-Disposition", "inline; filename=\"rapor.pdf\"");
stream.flush();
stream.close();
return Response.ok().build();
And here is the screen shot from my local server:
And here is the ss from deployment on chrome:
And here is ss from deployment on firefox:
It sounds to me ridiculous. It works perfect on my local computer but didn't work on deployment and no errors no execptions.
Could you help me please?
I have saved a file into mongoDB using gridFS like so.
Mongo mongo = new Mongo("XXXXX", XXXX);
DB db = mongo.getDB("XXX");
GridFS fs = new GridFS(XXX);
File install = new File("C:\\Users\\Nabeel\\Desktop\\docs.txt");
GridFSInputFile inFile = fs.createFile(install);
inFile.save();
Now I want download that file using spring MVC. I don't seep to able to find example on how i can get the file back as gridFS has converted the file into binary.
An example code would be nice as i am new to all this.
Thanks you in advance
You can do something like this for serving file :
public void downloadFile(String videoId , HttpServletResponse response ) {
InputStream is = null;
ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoDBConfiguration.class);
GridFsOperations gridOperations = (GridFsOperations) ctx.getBean("YourBeanName");
List<GridFSDBFile> result = gridOperations.find(new Query().addCriteria(Criteria.where("_id").is(videoId)));
for (GridFSDBFile file : result) {
try {
/* send file */
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
}
Send file example here: How do I return a video with Spring MVC so that it can be navigated using the html5 <video> tag?
This link about video serving but it can give you an idea. Use method 2 in the link and GridFSDBFile's getInputStream() method.
I was planning to unit test my Servlet through ServletUnit and ran across some problems :
- As a starting point, we are supposed to create a ServletRunner object. One of the constructors expects File object with web.xml file. I provide the full path of my web.xml file but somehow it ignores the path provided and searches at the top level folder. The code-snippet and error message is below:
Code Snippet
ServletRunner sr = new ServletRunner(new File("* C:/eclipse-workspaces/pocs/lms-csd/src/main/webapp/WEB-INF/web.xml*"));
ServletUnitClient sc = sr.newClient();
WebRequest request = new PostMethodWebRequest("path to be specified" ); request.setParameter( "userId", "test" );
request.setParameter( "password", "csd" );
WebResponse response = sc.getResponse(request);
String text = response.getText();
Assert.assertTrue(text.contains("Welcome to Leave Management System"));
stack trace
com.meterware.httpunit.HttpInternalErrorException:
Error on HTTP request: 500 org.apache.jasper.JasperException: java.io.FileNotFoundException: * C:\eclipse-workspaces\pocs\lms-csd\WEB-INF\web.xml*
(The system cannot find the path specified)
[http://localhost/login] - Why does the system keep on looking at the folder structure to be .../WEB-INF/web.xml.
Mine is a maven project and I would not like to change the structure of the project to adapt this way. How can I make ServletRunner class to read from a specified folder ? - In the Servlet code,
I use the following code :
String result = null if (someCondition) result = "/welcome.jsp"; } else { logger.warn("Password Validation failed"); request.setAttribute("failedlogin", new Boolean(true)); result = "/index.jsp"; } } RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(result); requestDispatcher.forward(request, response);
Again ServletUnit expects welcome.jsp to be at root foler, though jsp files are present at .../src/main/webapp/ folder. Again how can ServletUnit be told about the target folder location ?
Many thanks in advance.
Best Regards
M.SuriNaidu
This is the sort of thing I do. This is a facsimile of the base class of my servlet tests. In this case I pass the relative path of the web.xml file as it exists in my source tree. I run these tests from ant and eclipse.
abstract public class ServletTestCase {
protected ServletRunner m_runner;
protected ServletUnitClient m_client;
protected String m_userAgent = "something/1.0";
#Override
protected void setUp() throws Exception {
super.setUp();
initHttpUnit();
}
#Override
protected void tearDown() throws Exception {
shutdownHttpUnit();
super.tearDown();
}
protected void initHttpUnit() throws IOException, SAXException {
shutdownHttpUnit();
// We are expecting UTF-8 character handling in URLs, make it the default
HttpUnitOptions.setDefaultCharacterSet("UTF-8");
// Find the servlet's web.xml file and use it to init servletunit
File file = new File("tests/web.xml"));
m_runner = new ServletRunner(file);
m_client = m_runner.newClient();
m_client.getClientProperties().setUserAgent(m_userAgent);
}
protected void shutdownHttpUnit() {
if (m_runner != null) {
m_runner.shutDown();
}
m_client = null;
m_runner = null;
}
}
I am trying to access a file via a URI using the FTP protocol. For obvious security reasons I had to make some changes but this is where the problems seem to be coming from.
My URI is as follows:
ftp://user:pasword#host.net/u/Bigpathname/XYZ/ABC/BigPathname/bigpathname/xyz/abc/MY_LOG.LOG
And I see this exception:
sun.net.ftp.FtpProtocolException: CWD Bigpathname:501 A qualifier in "Bigpathname" is more than 8 characters
This is really confusing as I can access the file from a Windows 7 command line with the CD command just fine. Both one directory at a time and as a full path.
I found one article mentioning that MVS file names must be 8 or fewer characters but this does not explain how I can get to these same files from my command line! They do exist there is data there that I can download manual but I can not get there via a URI in Java.
PS I use .toURL().openStream() to get files on my local machine just fine, it only fails when I try to get them from my server.
EDIT October 1st
I am able to access files on the MVS host using FileZilla and the basic FTP client from the Windows 7 command line - but I still cannot get them from a URI/URL. I downloaded a very basic Java built FTP client and tried accessing the same file in my program from there and the path works but because my file name has a dot in it "MY_LOG.LOG" I am getting File does not exist 501 Invalid data set name "MY_LOG.LOG". Use MVS Dsname conventions. I am utterly perplexed by this...
EDIT Ocotober 1st afternoon :)
OK I finally got it to work with a FTP client in my Java code - but I still want to use the URL class as I have logs on both local and remote machines. Is there a way to encode a URL string so that it can retrieve a file from a remote machine with the FTP protocol? I am not sure how it works in the Java URL class but in the FTP client I had to use the CWD and then the RETR command.
If I can do this then I have one solution for getting all my logs, otherwise I will have to detect if it is a file or ftp URL and then behave differently. Not the end of the world but not what I want...
The code that tries to get the file with just a URL is as follows: (sysc is a valid host)
void testFTP()
{
String ftp = "ftp://user:pword#sysc/u/Xxxxxxxxxx/ICS/YT7/XxxxxXxxxxxxx/xxxxxxxxx/logs/xxxxxxxx/XX_YT.LOG";
try
{
URI uri = new URI(ftp);
URL ftpFile = uri.toURL();
BufferedReader in = new BufferedReader(new InputStreamReader(ftpFile.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
In this case I think the problem is also Server Related, It all works fine for me with Filezilla Server except when the filename length(including directories) exceeds 255 chars but if you want to use the URL class with another FTP you must override or implement your own URLStreamHandlerFactory.
URL.setURLStreamHandlerFactory(...);
I haven't found any for my favorite java FTP Client witch is Apache one so I have developed one but may need a few touch ups.
package net.custom.streamhandler.apacheftp;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ApacheURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
//this will only override the chosen protocol
if ( protocol.equalsIgnoreCase("ftp") )
return new CustomHandler();
else
return null;
}
}
class CustomHandler extends URLStreamHandler {
protected URLConnection openConnection(URL url)
throws IOException {
return new CustomURLConnection(url);
}
}
class CustomURLConnection extends URLConnection {
int reply;
FTPClient ftp = new FTPClient();
InputStream in;
static int defaultPort = 21;
static String defaultPath = "/";
CustomURLConnection ( URL url)
throws IOException {
super( url );
}
synchronized public void connect() throws IOException {
try {
int port;
if ((port = url.getPort()) == -1 )
port = defaultPort;
ftp.connect(url.getHost(), port);
String login = "anonymous";
String password = "";
if(url.getAuthority().indexOf(':')>-1 &&
url.getAuthority().indexOf('#')>-1){
String []auxArray = url.getAuthority().replaceAll("#", ":").split(":");
login = auxArray[0];
password = auxArray[1];
}
ftp.login(login, password);
reply = ftp.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Apache Success");
} else {
System.out.println("Connection Apache Failed");
ftp.disconnect();
}
in = ftp.retrieveFileStream(url.getFile());
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
connected = true;
}
synchronized public InputStream getInputStream()
throws IOException {
if (!connected)
connect();
return ( in );
}
}
*Keep in mind that you can implement new ways to handle different protocols for the java.net.URL this way.
Your code...
...
{
String ftp = "ftp://user:pword#sysc/u/Xxxxxxxxxx/ICS/YT7/XxxxxXxxxxxxx/xxxxxxxxx/logs/xxxxxxxx/XX_YT.LOG";
try
{
URL.setURLStreamHandlerFactory(new ApacheURLStreamHandlerFactory());
...
G'Bye
**(To err is human, to forgive is divine)
Try using the short name for the path. Something like /U/BIGPAT~1/XYZ/ABC/BIGPAT~1/BIGPAT~1/XYZ/ABC/MY_LOG.LOG
You can find the short name for any directory longer than 8 characters with dir /x.
FTP clients are notoriously difficult to write given the variation of (and bugs in) server implementations.
I'm betting that MVS is not completely supported by sun.net.ftp.FtpClient, which is the class used under the hood when you call URL.openStream on an FTP URL.
The Apache Commons Net library should support MVS, but it sounds like you already found a working client.
Have you considered using an RMI for transporting the files that way you can give a direct path to the file as a parameter without the use of ftp then have the file sent back in a byte array.