URLConnection to filename question

Not sure if this is the right forum for this but I hope so.
I have a program which I created that takes a http address and then downloads the file from that address.
The program looks at the entered URL and downloads its content into a temp file with an arbitrarily name.
Then, a JFileChooser opens, which is supposed to, by default, suggest the name of the file which was just downloaded.
This works in MOST situations, but my problem is that if I have a url which redirects, for example, if i pasted the link to a download on a site like for example filehippo.com was what i tested with....
I gave it the URL: http://www.filehippo.com/download/file/4aac52cca0ce60fd95312eebf41deffc096823c22c2cbf043f4b6dfd323a4b3a/ which is just a trial version of "CC cleaner" or something, but instead of suggesting the name as like install cccleaner.exe or whatever it is supposed to be it is suggesting the name "null" because there is no filename included in that url.
My question is how can i get the filename which a URLConnection is pointing to / redirecting to 100% so that this will always be correct?
Thanks
Robert
Edited by: rnoack on Jan 27, 2009 11:32 PM

Check this out
try {
            // TODO code application logic here
            URL u=new URL("http://www.filehippo.com/download/file/4aac52cca0ce60fd95312eebf41deffc096823c22c2cbf043f4b6dfd323a4b3a/");
            HttpURLConnection con=(HttpURLConnection) u.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            OutputStream out = con.getOutputStream();
            InputStream in = con.getInputStream();
            if(con.getFollowRedirects())
                System.out.println(con.getURL());
        } catch (UnknownHostException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
Output: http://fs7.filehippo.com/9006/ac2f91079423421eb40b9a8ca428da4d/ccsetup216.exe

Similar Messages

  • Library filename question

    library filenames:
    I imported a large folder of photos to the library that had the proper filenames from the camera.  When they appeared in the library, every photo has the same filename:  DSCN0023.  Additionally, all of the other photos in all of the other albums in the library show that same name.  What gives?

    What happens when you right-click an image and select <Show in Explorer / Finder>.
    Does it take you to the correct image, i.e. is the correct image highlighted?
    And what is the filename of the image that is displayed in Explorer / Finder ? Does it show the proper (correct) filename?
    BTW: Are you on a Mac or Windows?

  • Filename question

    i am designing a Student class which implements the Student interface, the Student interface is:
    * A simple interface to allow access to student
    * properties from a class data file.
    public interface Student {
    //some methods
    which i named Student.java
    then i want to have a class like:
    public class Student implements Student{
    //some methods
    and now the filename for this class must be Student.java. but there already exist a Student.java. any suggestion will be appreciated. thanks.

    then i want to have a class like:
    public class Student implements Student{
    //some methods
    and now the filename for this class must be
    Student.java. but there already exist a Student.java.
    any suggestion will be appreciated. thanks.My suggestion would be to stop wanting to have that class. Call it something else.

  • FileReference#download() and filename question

    On the server side I set a HTTP header as
    Content-Disposition: attachment; filename=myfilename.txt
    Is it possible to get this information in Flex client? The FileReference#download() function gives a possibility for a name to set on the file browser, but I can't figure out how to get it from the server. By default, the function uses the remote URL.
    Any ideas?
    Thanks.

    Lawcats please see Install and update apps - https://helpx.adobe.com/creative-cloud/help/install-apps.html for information on how to install the Adobe Creative applications included with your membership.

  • PSCC - Filename question

    Hi Guys,
    Using Photoshop CC, does anyone know what the asterisk means inside the tab name? This is on the inside of the bracket, outside it would mean not saved. I'm using 16 bit files throughout and the ProPhoto RGB Workspace. Files are transferred in and out of Lightroom 5.2 as my front-end .
    e.g. Nikon D700-4162-ME.tif @ 21.9% (RGB/16*)
    Thanks,
    Lyndon

    That's an interesting question.  I've just learned something:
    http://www.earthboundlight.com/phototips/photoshop-pound-sign-asterik-title-bar.html

  • Adobe droplet question, involving Place command and filenames

    Suppose I have two files called, (a) "background.tif" and (b) "Image001.tif".
    Background.tif is a simple black layer, sized to 1500 x 1000 px.  Image001.tif may be cropped to any size.
    I want to do the following in a droplet:
        1. Place (File/Place) "Image001.tif" in "background.tif", knowing it'll be centered and resized as needed automatically.
        2. Save the new file for the web as "Image001.jpg",
        3. close both files without saving (I only need the resulting JPG).
    My goal - I have several hundred files that all need web-ready JPGs created with a standard size black background, so that they'll fit a web gallery that can only handle a fixed set of dimensions.
    Questions:
    1. Is this even possible via automation?
    2. If so, how do I ensure that the JPG that gets created has the same name as the source image file; i.e. "image001.jpg", and then "image002.jpg", etc.?
    3. is there a better way to create the end result, rather than using the place command; i.e. doing this with the original image file instead (thus solving the filenaming question)?
    Running PS CS6 on Win7/64.
    Many thanks!
    Jerry

    Hi csuebele,
    The only requirement is that the final result is 1500 x 1000 px.  The black is used to fill in the sides/tops as necessary.  Since this is to be automated, I need each new file to have a unique name of course (otherwise succeeding files will overwrite their predecessor).
    For example, say I have a file called image001.tif that is cropped to 2400w x 3000h px. I need this to fit a container that's 1500 x 1000 px, with black filling this out.
    Manually I would
    1. Open a black TIFF that's already 1500x1000.
    2. Place the 2400x3000 px image in the black tiff.
    3.  PS then resizes and centers the image to fit, while preserving the aspect ratio. 
    4. Thus the image is now sized to be 800w x 1000h px , with black filling the sides equally; i.e. 750 px of black on either side.
    5. I then save that "new" version of the black file for the web, and then close w/o saving.
    6. End result is a 1500x1000 file called image001.JPG.
    Please see attached for 2 examples:
    Example of a portrait image:
    Example of a landscape image:

  • URLConnection from MDB

    I am working on an application where the MDB (configurable value) will pick up message from IBM MQ, process these messages and post them out to a URI and handle the response back and put them to MQ. I am trying to use HttpClient instead of URLConnection. My question is,
    1) What is the best practice to open this (rather say these) external connection (s) and post message to them?
    2) How to do the house keeping (managing resources)
    3) Is it good to use SessionBean (Stateful, Stateless?)
    Any ideas appreciated

    1) What is the best practice to open this (rather say these) external connection (s) and post message to them?
    The biggest problem you'll have is figuring out how (and if) to handle errors. Since HTTP POSTS aren't transactional you can get the situation where the POST succeeds, but your server dies before the JMS session is commited. Since the JMS session didn't commit, the message will still be on the queue and be picked up next time your MDB starts, leading to a duplicate post. One way to resovle this is if the message contains a unique id, the recipient can discard duplicates.
    An alternative scenario where there is something wrong with the message. In this situation you need to agree with the recipient whether they will handle the error or whether the MDB should.
    There's no best practice for this sort of thing, as it depends on how valuable the message is, whether duplicates matter, whether bad messages can be fixed, or need to be corrected at source etc.
    2) How to do the house keeping (managing resources)
    Do you mean TCP/IP connections? I haven't done much work with HttpClient but it looks as though you can share connections using the HttpConnectionManager.
    3) Is it good to use SessionBean (Stateful, Stateless?)
    I would delegate the http work to another class, but don't see any benefit in making it a session bean.

  • How to make file download in JSP ?

    Friends,
    i am using following code :
    // LISTING FILES IN DIR
            out.println("<br>");
            File dir = new File(dirName);
            String[] children = dir.list();
                 if (children == null)
            // Either dir does not exist or is not a directory
                 else
                    %>
                    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="68%" id="AutoNumber1">
                    <tr>
                        <td width="50%" align="center"><font face="Verdana">File</font></td>
                        <td width="50%" align="center"><font face="Verdana">Action</font></td>
                          </tr>   
                        <%
                        for (int i=0; i<children.length; i++)
                        // Get filename of file or directory
                        String filename = children;
    //out.println(filename);
    %>
    <tr>
    <td width="50%">
    <p align="center"><font face="Verdana"><%=filename %></font></td>
    <td width="50%">
    <p align="center"><font face="Verdana"><a href="<%= children[i %">">View</a></font></td>
    </tr>
    <%
    out.println("<br>");
    %>
    SInce i am not able to download file from link.
    link shows path correct but why its not working ??
    HELP ME.
    *i don't want to show real path( physical location of file) on file donwload link.*
    Example :
    *it will not allow to show like following :*
    *C:\project\webUpload\build\web\fuploads\file2.jpg*
    *it may allow like :*
    *\webUpload\fuploads\file2.jpg*
    Thanks</a>

    My friend you are getting it all wrong here...
    Here we would be taking help of a dedicated servlet to locate and download a file(which would be the output the respective concent of depeding of the fineName or fileId you send in).
    Please find some time and try to consider the below case...
    Say i have a Servlet which takes a Request of detailed filePath and would give output as file itself....
    and you prompt you give a link to that servlet from you JSP to download that file...
    Checkout the below Code snippets to get some idea
    DownloadPrompting.JSP:
    ==================
    <a href="FileServlet?fileName=C:\fileuploaded\image1.jpg" title="C:\fileuploaded\image1.jpg">Click Here to download Image1 JPEG File</a>
    <c:forEach var="fileName" items="${sessionScope.fileNames}">
       <a href="FileServlet?fileName=<c:uri value="${fileName}"/>" title="<c:out value="${fileName}"/>">Click Here to download</a>
    </c:forEach>
    -------------------------------------------------------------------------FileServlet.java
    ===========
    package com;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLConnection
    public class FileServlet extends HttpServlet{
      private void processAction(HttpServletRequest request,HttpServletResponse response) throws Exception{
           // getting fileName which user is requesting for
           String fileName = request.getParameter("fileName").replace('\\','/');
           boolean exists = new File(fileName).exists();
           // Checking whether the file Exists or not      
           if(exists){
            FileInputStream input = null;
            BufferedOutputStream output = null; 
            int contentLength = 0;
            try{
                // Getting the Mime-Type
                String contentType = URLConnection.guessContentTypeFromName(fileName); 
                if(contentType == null)        
                   contentType = "application/octet-stream";
                input = new FileInputStream(fileName);
                contentLength = input.available();
                // Enables us to specify of what kind of content we are trying to download.
                response.setContentType(contentType);
                // Specifes How much amountof data we straming & trying to download
                response.setContentLength(contentLength);
                // Adding Content Disposition header so that it cud enable us to get OPEN/SAVE  after clicking on the link 
                response.setHeader("Content-Disposition","attachment;filename="+fileName+"\");
                // Initializing File Streaming Response via a Servlet
                output = new BufferedOutputStream(response.getOutputStream());
                // Placing each byte on to the stream after reading it from the file
                while ( contentLength-- > 0 ) {
                   output.write(input.read());
                 // Flushing the stream.         
                 output.flush();
              }catch(IOException e) {
                     System.err.println("Exception Occured:"+e.getMessage());
                 System.err.println("Exception Localized Message:"+e.getLocalizedMessage());
              } finally {
                   // Closing the INPUT stream 
                   if (input != null) {
                       try {
                          input.close();
                      } catch (IOException ie) {
                          System.err.println("Exception Occured:"+e.getMessage());
                             System.err.println("Exception Localized Message:"+e.getLocalizedMessage());                      
                   // Closing the OUTPUT stream 
                   if (output != null) {
                       try {
                          output.close();
                      } catch (IOException ie) {
                          System.err.println("Exception Occured:"+e.getMessage());
                             System.err.println("Exception Localized Message:"+e.getLocalizedMessage());                      
           }else{
             response.sendRedirect("/errorPage.html");
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws Exception{       
            processAction(request,response); 
      public void doGet(HttpServletRequest request,HttpServletResponse response) throws Exception{
            processAction(request,response); 
    }And if you are thinking of hiding filepath & all...
    Here is a hint for you...
    Try to maintain a properties file which has a key value pairs of that something like.
    112345678=C:\\uploadfile\\image1.jpg
    122142637=C:\\uploadfile\\image2.jpg
    or create a Database table which which an autogenerated primany key with some Id and holds the complete filePath.
    and in this case you would access the file something like the one below from your jsp
    <a href="FileServlet?fileId=112345678" title="112345678">Click Here to download Image1 JPEG File</a>
    <c:forEach var="fileId" items="${sessionScope.fileNames}">
       <a href="FileServlet?fileId=<c:uri value="${fileId}"/>" title="<c:out value="${fileId}"/>">Click Here to download</a>
    </c:forEach>
    -------------------------------------------------------------------------and in the fileServlet you might have to change the below part to
    // getting fileName which user is requesting for
           String fileName = request.getParameter("fileName").replace('\\','/');to something like
    // getting fileName which user is requesting for
           String fileId = request.getParameter("fileId");
       /*Querying the database or reading the Properties file to findout the correspoding filePath associated with the fileId something like*/
        String fileName = ResourceDelegate.getInstance().getFile("fileId").replace('\\','/');
    NOTE:* The idea is similar to what my fellow poster is trying to explain you in all his posts.
    Hope that might help :)
    REGARDS,
    RaHuL

  • Create OutputFile in jsp and write this file to response

    Hello
    Please can you help me
    I need to dynamically create a file in jsp and send this file to user
    Please help

    Don't forget to set the contentLength. Some clients/applications will refuse to run/open the file otherwise.
    At the bottom of this article you can find several reuseable downloadFile() utility methods: http://balusc.xs4all.nl/srv/dev-jep-pdf.html
    I'll copypaste them here:
    package net.balusc.util;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLConnection;
    import javax.servlet.http.HttpServletResponse;
    public class HttpServletUtil {
         * Send the given file as a byte array to the servlet response. If attachment
         * is set to true, then show a "Save as" dialogue, else show the file inline
         * in the browser or let the operating system open it in the right application.
         * @param response The HttpServletResponse to be used.
         * @param bytes The file contents in a byte array.
         * @param fileName The file name.
         * @param attachment Download as attachment?
        public static void downloadFile(HttpServletResponse response, byte[] bytes, String fileName, boolean attachment) throws IOException {
            // Wrap the byte array in a ByteArrayInputStream and pass it through another method.
            downloadFile(response, new ByteArrayInputStream(bytes), fileName, attachment);
         * Send the given file as a File object to the servlet response. If attachment
         * is set to true, then show a "Save as" dialogue, else show the file inline
         * in the browser or let the operating system open it in the right application.
         * @param response The HttpServletResponse to be used.
         * @param file The file as a File object.
         * @param attachment Download as attachment?
        public static void downloadFile(HttpServletResponse response, File file, boolean attachment) throws IOException {
            // Prepare stream.
            BufferedInputStream input = null;
            try {
                // Wrap the file in a BufferedInputStream and pass it through another method.
                input = new BufferedInputStream(new FileInputStream(file));
                downloadFile(response, input, file.getName(), attachment);
            } catch (IOException e) {
                throw e;
            } finally {
                // Gently close stream.
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
         * Send the given file as an InputStream to the servlet response. If attachment
         * is set to true, then show a "Save as" dialogue, else show the file inline
         * in the browser or let the operating system open it in the right application.
         * @param response The HttpServletResponse to be used.
         * @param input The file contents in an InputStream.
         * @param fileName The file name.
         * @param attachment Download as attachment?
        public static void downloadFile(HttpServletResponse response, InputStream input, String fileName, boolean attachment) throws IOException {
            // Prepare stream.
            BufferedOutputStream output = null;
            try {
                // Prepare.
                int contentLength = input.available();
                String contentType = URLConnection.guessContentTypeFromName(fileName);
                String disposition = attachment ? "attachment" : "inline";
                // Init servlet response.
                response.setContentLength(contentLength);
                response.setContentType(contentType);
                response.setHeader("Content-disposition", disposition + "; filename=\"" + fileName + "\"");
                output = new BufferedOutputStream(response.getOutputStream());
                // Write file contents to response.
                while (contentLength-- > 0) {
                    output.write(input.read());
                // Finalize task.
                output.flush();
            } catch (IOException e) {
                throw e;
            } finally {
                // Gently close stream.
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
    }

  • Parse XML AppleScript

    I have found some tutorials online which have got me to the stage I am at with my applescript below, however I am now stuck.
    I would be grateful if anyone could help me.
    I have this XML in a document below.
    <?xml version="1.0" encoding="UTF-8"?>
    <Question Parameters>
    <Question>Which of these two colours do you like most?</Question>
    <Response1>Red</Response1>
    <Response2>Blue</Response2>
    <Filename>Choose A Colour</Filename>
    </Question Parameters>
    I have the action below in Automator which runs a script. My functionality is to open the text file and move the xml text as a string in a variable. Then move the value of an xml element name "Response1" into a new variable.
    on run {input, parameters}
    tell application "TextEdit" to get text of document 1 as string
    set myXMLSource to result as Unicode text
    tell application "System Events"
    set myResponseText to value of XML element named "Response1" of myXMLSource
    end tell
    end run
    All I keep getting is an error asking me to "Check the actionʼs properties and try running the workflow again.", but my script looks exactly like the tutorials I have been reading.
    Any suggestions?
    Message was edited by: dwigg

    Hi,
    I'd suggest that you sort out the AppleScript itself, in Script Editor, before trying to run it in Automator. The Automator error is a generic "This AppleScript doesn't work, I'm giving up now"-type message.
    I know very little about XML, and the System Events XML suite is not well documented beyond what can be found in SE's AppleScript dictionary.
    However, I think you have two problems. First, you're not telling System Events that you want it to deal with XML data. Second, once that bit's fixed, I don't think that <Question Parameters> is a valid XML tag (it's got a space in it.)
    Save the following into a text-only file:
    <xml>
    <Question_parameters>
    <Question>Which of these two colours do you like most?
    </Question>
    <Response1>Red</Response1>
    <Response2>Blue</Response2>
    <Filename>Choose A Colour</Filename>
    </Question_parameters>
    </xml>
    What you've got there is three levels of xml data, and you have to do some digging through the elements to get the information you require (and you have to know the structure of your data file).
    Try this Applescript:
    set the_file to ((choose file without invisibles) as string) -- navigate to and choose the file you just saved
    tell application "System Events"
    set xml_data to contents of XML file the_file
    tell xml_data to set level_1 to XML element 1 -- the "xml" level
    tell xml_data to set level_2 to XML element 1 of level_1 --the "Question_parameters" level
    tell xml_data to set level_3 to XML elements of level_2 -- level 3 is the level you're after
    tell xml_data to set data_count to count level_3
    display dialog data_count -- level 3 has four xml elements
    set value_1 to value of item 2 of level_3 -- value of Response1
    set value_2 to value of item 3 of level_3 -- value of Response2
    set the_question to value of item 1 of level_3
    display dialog "Response 1 is " & value_1 & return & "Response 2 is " & value_2 with title the_question
    end tell
    Look in Script Editor's Event Log to see what's going on.
    Hope this helps a bit. Can you provide a link to your tutorials?
    H
    Message was edited by: HD

  • FileServlet serving from FTP

    Hello!
    I'm trying to create a bean that opens a PDF file from another FTP server. I have it open from a local path, but can't get it to open from a FTP host. Your help is appreciated.
    Thanks in advance!
    -Tony
    package aiView;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLConnection;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import sun.net.ftp.FtpClient;
    public class FileServlet extends HttpServlet {
        private FtpClient m_client;
        private String host = "";
        private String user = "";
        private String password = "";
        private String sDir = "";
        public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
                m_client = new FtpClient(host);
                m_client.login(user, password);
                m_client.cd(sDir);
                m_client.binary();
            // Define base path somehow. You can define it as init-param of the servlet.
            String filePath = "/files";
            //Not working
            //String filePath = m_client.cd(sDir);
            // String filePath = getServletContext().getRealPath("/WEB-INF/files");
            // Get file name from request.
            String fileName = request.getParameter("name")+".pdf";
            // Check if file name is supplied to the request.
            if (fileName != null) {
                // Strip "../" and "..\" (avoid directory sniffing by hackers!).
                fileName = fileName.replaceAll("\\.+(\\\\|/)", "");
            } else {
                // Do your thing if the file name is not supplied to the request.
                // Throw an exception, or show default/warning page, or just ignore it.
                fileName = "filenotfound.pdf";
                response.sendRedirect("FileNotFoundError.jsp");
                return;
            // Prepare file object.
            File file = new File(filePath, fileName);
            // Check if file actually exists in filesystem.
            if (!file.exists()) {
                // Do your thing if the file appears to be non-existing.
                // Throw an exception, or show default/warning page, or just ignore it.
                //fileName = "filenotfound.pdf";
                response.sendRedirect("FileNotFoundError.jsp");
                return;
            // Get content type by filename.
            String contentType = URLConnection.guessContentTypeFromName(fileName);
            // If content type is unknown, then set the default value.
            // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
            if (contentType == null) {
                contentType = "application/pdf";
            // Prepare streams.
            BufferedInputStream input = null;
            BufferedOutputStream output = null;
            try {
                // Open file file.
                input = new BufferedInputStream(new FileInputStream(file));
                int contentLength = input.available();
                // Init servlet response.
                response.reset();
                response.setContentLength(contentLength);
                response.setContentType(contentType);
                response.setHeader(
                        "Content-disposition", "attachment; filename=\"" + fileName + "\"");
                output = new BufferedOutputStream(response.getOutputStream());
                // Write file contents to response.
                while (contentLength-- > 0) {
                    output.write(input.read());
                // Finalize task.
                output.flush();
            } catch (IOException e) {
                // Something went wrong?
                e.printStackTrace();
            } finally {
                // Gently close streams.
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
    }Edited by: ynotlim333 on Oct 19, 2007 1:17 AM
    Edited by: ynotlim333 on Oct 19, 2007 1:19 AM

    Well,Alright here is an example which i would try to implement.
    Say,there is a table in dataBase which has below schema
    TABLE fileTable{
        fileId --- PK -- Auto Generated;
        fileNameWithPath - varchar2(200);
        createdDate -- DATE;
    }and their is a DTO Mapped to that table called FileDTOBean
    public class FileDTOBean implements serializable{
       private String fileId = "";
       private String fileNameWithPath ="";
       private Date createdDate = null;
        /** Setters & getters for respective properties */
    }Assuming that their is a DAO called FileServiceDAO which has method called getFileDTO(String fileId) which return an instance of FileDTOBean for a given fileId.
    by executing a query like
    "select fileId,fileNameWithPath,createdDate from fileTable where fileId = ?"and you would be using a dedicated Business Object for the same purpose.
    FileServiceDelegateImpl.java:
    =====================
    package com.webapp.commons.delegate.impl;
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryUsage;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URL;
    import java.net.URLConnection;
    import org.apache.commons.net.ftp.FTPClient;
      * @Author : RaHuL ShArMa
      * @Version : v1.0
    /**The Delegate class could be used as a Bsuiness Object which provides services to give access to different stored in Database/local system/remote mapped network drive/FTP registered by specfic fileId from database*/
    public class FileServiceDelegateImpl implements FileServiceDelegate{
              private static FileServiceDelegate fsd = null;
              private static FileServiceDAO fd = null;
              protected FileServiceDelegateImpl(){ 
                   this.fd = FileServiceDAO.getCurrentInstance();
              public static synchronize FileServiceDelegate getCurrentInstance(){
                    if(fsd == null)
                      fsd = new FileServiceDelegateImpl();
                    return fsd;
              public void exportFTPFile(HttpServletResponse reponse,String ftpUri,String userName,String password,String fileId,boolean content)throws Exception{
                      InputStream fis = null;                 
                      BufferedInputStream input = null;
                      BufferedOutputStream output = null;       
                      int contentLength = 0;
                      FileDTOBean fdto = this.fd.getFileDto(fileId);
                      FTPClient ftpClient = null;
                      try{
                          String fileName = fdto.getFileName();
                          ftpClient = new FTPClient();
                          ftpClient.connect(ftpUri);
                          ftpClient.login(ftpUri);
                          fis =  ftpClient.retrieveFileStream(fileName);
                            // Getting the Mime-Type
                           String contentType = URLConnection.guessContentTypeFromStream(fis);          
                           if(contentType == null)
                                contentType = "application/octet-stream";
                            fis = new FileInputStream(fdto.getFileNameWidPath());
                            contentLength = fis.available(); 
                            // Trying to get the Generic Buffer Size w.r.t other factors
                            int readSize = this.getGenericSize(contentLength.available());                           
                            input = new BufferedInputStream(fis,readSize);
                            response.setContentType(contentType);
                            response.setContentLength(contentLength);
                            if(content) 
                               response.setHeader("Content-Disposition","attachment;filename=\"+fdto.getFileNameWidPath()+"\");
                            output = new BufferedOutputStream(response.getOutputStream(),readSize);
                            // output the streaming request
                            this.streamData(input,output,readSize);  
                       }catch(Exception e) {          
                            throw new Exception(e.getCause());
             /**The actual method which sends back the respective response to the supposed client by picking up the content from       
             the specified*/
             public void exportFile(HttpServletResponse reponse,String fileId,boolean content) throws Exception{
                      InputStream fis = null;                 
                      BufferedInputStream input = null;
                      BufferedOutputStream output = null;       
                      int contentLength = 0;
                      FileDTOBean fdto = this.fd.getFileDto(fileId);
                      URL url = null;
                      URLConnection urlConn = null;
                      try{
                            String filePath = fdto.getFileNameWidPath().trim();
                             if(!filename.startsWith("ftp://"))
                               fis = new FileInputStream(filname);
                             else{
                                url = new URL(filePath);
                                urlConn = url.openConnection(); 
                                fis = urlConn.getInputStream();
                            // Getting the Mime-Type
                           String contentType = URLConnection.guessContentTypeFromStream(fis);           
                           if(contentType == null)
                                contentType = "application/octet-stream";
                            contentLength = fis.available(); 
                            // Trying to get the Generic Buffer Size w.r.t other factors
                            int readSize = this.getGenericSize(contentLength.available());                           
                            input = new BufferedInputStream(fis,readSize);
                            response.setContentType(contentType);
                            response.setContentLength(contentLength);
                            if(content) 
                               response.setHeader("Content-Disposition","attachment;filename=\"+fdto.getFileNameWidPath()+"\");
                            output = new BufferedOutputStream(response.getOutputStream(),readSize);
                            // output the streaming request
                            this.streamData(input,output,readSize);  
                       }catch(Exception e) {          
                            throw new Exception(e.getCause());
              /**The actual method which sends back the respective response to the supposed client by picking up data from the database*/
              public void exportDBData(HttpServletResponse reponse,String fileId,boolean content) throws Exception{
                      FileInputStream fis = null;                 
                      BufferedInputStream input = null;
                      BufferedOutputStream output = null;       
                      int contentLength = 0;
                      FileDTOBean fdto = this.fd.getFileDto(fileId);
                      if(fdto == null)
                        return;
                      try{
                            // Getting the Mime-Type
                            String contentType = fdto.getContentType();
                            bis = new ByteArrayInputStream(fdto.getData());
                            contentLength = bis.available(); 
                            // Trying to get the Generic Buffer Size w.r.t other factors
                            int readSize = this.getGenericSize(contentLength);                           
                            input = new BufferedInputStream(bis,readSize);
                            response.setContentType(contentType);
                            response.setContentLength(contentLength);
                            if(content) 
                               response.setHeader("Content-Disposition","attachment;filename=\"+fileName+"\");
                            output = new BufferedOutputStream(response.getOutputStream(),readSize);
                            // output the streaming request
                            this.streamData(input,output,readSize);  
                       }catch(Exception e) {          
                            throw new Exception(e.getCause());
            /**Outputs given results as per decided constraits*/ 
            public void streamData(BufferedInputStream input,BufferedOutputStream output,int readSize)throws Exception{
                 try{
                    byte buffer[] = new byte[readSize]; 
                    int nByteRead = 0;
                    while((nByteRead = input.read(buffer)) != -1)
                        output.write(buffer);                         
                    output.flush();
                 }catch(Exception exp){
                   exp.printStackTrace(); 
                   throw new Exception(exp.getCause());
                 }finally{
                      if(input != null){
                            try {
                                input.close();
                            } catch (Exception ie) {
                             ie.printStackTrace(); 
                                throws new Exception(ie.getCause());
                      if (output != null) {
                              try {
                                 output.close();
                              } catch (Exception ie) {                     
                                 throws new Exception(ie.getCause());         
                      input = null;
                      output = null;
         /**Deciding Just by applying Best memory usage constraint and one can change the logic accordingly
          * with respective other factors like network load and etc
         public synchronize int getGenericSize(int length){
                 int bufferSize = 512;
                 MemoryUsage heapUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(); 
                 double usageFactor =    (heapUsage.getInit() - heapUsage.getUsed()) / heapUsage.getMax();            
                 bufferSize = (int)(length * usageFactor);
                 if(bufferSize <= 512)
                      bufferSize = 512;
                 else if(buffer >= 4096) 
                      bufferSize = 4096;                 
                 return bufferSize;                            
    }and the code in your Servlet/JSP/Struts Action/Backing bean would be like.
    public void processAction(HttpServletRequest request,HttpServletResponse.......)throws Exception{
        String fileId = request.getParameter("fid");
            lets assume file associated to fileId is "ftp://username:[email protected]/movie1Poster.jpg;type=i"
        if(fileId == null)
             throw new Exception("invalid fileid passed");
        //Assuming ServiceLocator returns instance FileServiceDelegateImpl
        FileServiceDelegate fsd = ServiceLocator.get(FileServiceDelegate.class);
         fsd.exportFile(response,fileId,false);
        /* or try using for secure FTP Access
             fsd.exportFTPFile(response,"ftp.foobar.com","username","password",fileId,false);
    }all you wud do in you jsp is to access respective file with
    http://HOST:appPort/webContextName/urlPatternAssociated?fid=<FileId>
    eg:
    <img src="FileServlet?fid=F13245" width="300" height="300" />
    <img src="FileAction.do?fid=F13245" width="300" height="300" />Hope this might help :)
    REGARDS,
    RaHuL

  • Content Type problem

    I am trying to retrieve the content type of a file.
    String strContentType ="";
              File file = new File(fileName);
              FileNameMap  fnmMime        = URLConnection.getFileNameMap ( ) ;
               if ( fnmMime != null ) {
                      strContentType = fnmMime.getContentTypeFor ( "file://c:2.avi" ) ;
    System.out.println(strContentType);It works perfect for image, video , sound formats, but it gives null for microsoft office documents and openoffice documents.
    can anyone help me?
    Thanks in Advance.

    Nirav-P-Thakar wrote:
    FileNameMap  fnmMime        = URLConnection.getFileNameMap ( ) ;
    fnmMime.getContentTypeFor(fileName);
    URLConnection.guessContentTypeFromName(fileName);I have tried out both methods but it returns null when the file is of type MS Office or Open Office.In reply 1 BalusC said..
    "Alternatively you can use ServletContext#getMimeType() for this. It guesses the content type based on the mime mapping as it is been definied in the web.xml of the application server and the webapplication. If it returns null, then you need to add new <mime-mapping> entry to the web.xml."
    I would try doing it this way. Try including entries for the mime mappings in the deployment descriptor of the web application.

  • Kerberos Ticket via Java to BW to access BW Querys with HTTP POST

    Hi and thanks for reading,
    im Working with 2004 and the NWDS SP10. We have a project which must show some reports from the HR system via backend and some BW Reports done with Web Application Designer 3.5.
    The user of the project application is able to select personnel numbers or org units in a tree UI element. At design time we do not know hwo many of each he might select (could be a couple of hundreds or even more).
    A URL isn't long enough to support our needs (255 characters border)
    A consultant said that we should use HTTP Post with a Form. He gave me an example like this
    <HTML>
    <BODY>
    <form name="querySelektion" action="<system name>" method="POST">
              <input type="submit" value="Formular senden" />
              <!-- Template Parameter -->
              <input name="SAP-LANGUAGE" type="hidden" value="D" />
              <input name="PAGENO" type="hidden" value="1" />
              <input name="CMD" type="hidden" value="LDOC" />
              <input name="TEMPLATE_ID" type="hidden" value="Z_TEST_AX" />
              <!-- Selektionsparameter -->
              <input name="var_name_1" type="hidden" value="H1_ORGST" /></td>
              <input name="VAR_NODE_IOBJNM_1" type="hidden" value="0ORGUNIT" />
              <input name="var_value_ext_1" type="hidden" value="50058503" />
         </form>
    </BODY>
    </HTML
    This is working beside the fact that i have to fill in my BW username and password. I translated this to Java with  the Jakarta HTTP Librarys into the following code.
    try
                HttpClient httpClient = new HttpClient();
                PostMethod post = new PostMethod("http://<system name>");
                NameValuePair[] data =
                        new NameValuePair("SAP-LANGUAGE", "D"),
                        new NameValuePair("PAGENO", "1"),
                        new NameValuePair("CMD", "LDOC"),
                        new NameValuePair("TEMPLATE_ID", "Z_TEST_AX"),
                        new NameValuePair("var_name_1", "H1_ORGST"),
                        new NameValuePair("VAR_NODE_IOBJNM_1", "0ORGUNIT"),
                        new NameValuePair("var_value_ext_1", "50058503")};
                post.setRequestBody(data);
                int iReturnCode = httpClient.executeMethod(post);
                wdContext.currentContextElement().setTextView(Integer.toString(iReturnCode ));
                post.releaseConnection();
            } catch (IOException ioe)
                wdContext.currentContextElement().setTextView(ioe.getMessage());
    All i get is an Error 401 which means "Not Authorized". The Portal (where the application is running) and the BW do both support Single Sign On and the BW System is configured in the Portal.
    I think the HTTP Post is to generic. I also think that i need to make a authorization before and post the Kereberos Ticket to the BW before.
    But how can i accomplish that? Is there a SAP HelperClass to configure or establish system connections of SSO enabled systems?
    Or is the approach with the HTTP Post in java wrong, maybe there is an easier way to do transfer a lot of personnel or orgunit numbers to the BW Query?
    Thanks in advance,
    Kai Mattern

    Since you mentioned, I now tried to modify the writeToFile method in a few ways (closing the streams, directly setting them to null...), but the "java.lang.IllegalStateException: Already connected" exception remains there
    Actually I suppose this has no effect on the originally reported cookie problem, because if I just completely remove this logwriting (+ the following URL disconnect-reconnect) from the code, the situation is the very same
    I paste my modified writeToFile method anyway, maybe you can tell what I do wrong here, and I can learn from that
        public void writeToFile ( HttpURLConnection urlConnection, String filename ) {
          try {
            BufferedReader bufferedReader = null;
            InputStreamReader inputStreamReader = null;
            // Prepare a reader to read the response from the URLConnection
            inputStreamReader = new InputStreamReader(urlConnection.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);
            String responseLine;
            PrintStream printStream = new PrintStream(new FileOutputStream (filename));
            // Read until there is nothing left in the stream
            while ((responseLine = bufferedReader.readLine()) != null)
                printStream.println(responseLine);
            inputStreamReader.close();
            bufferedReader.close();
            inputStreamReader = null;
            bufferedReader = null;
            printStream.close();
          catch (IOException ioException) { /* Exception handling */ }
        } //writeToFile()

  • How to access the images stored in folder which is kept inside theapplicati

    Iam new to java..
    I want to display the images (.jpeg,,.gif, flash) which are kept in one folder
    Using Jsp...
    Its Executing fine in local system..
    Its not working 1)when i execute that jsp from other system
    2)if i give the full url then only its executing in local system
    Please help me...
    thanks in advance...
    by Priya
    <%@ page import="java.io.*"%>
    <html>
    <head>
    <title>Movie Details</title>
    </head>
    <body text="#000000" bgcolor="#FFFFFF">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#FFFFFF" width="100%" id="AutoNumber1">
    <%
    File f=new File("..E:\application\Images");
    File []f2=f.listFiles();
    for(int ii=0;ii<f2.length;ii++)
    if(f2[ii].isFile())
    String fname=f2[ii].getPath();
    %>
    <tr>
    <td width="87%"><%=fname%> </td>
    <td width="14%"><img border="0" src="<%=fname%>" width="150" height="100" ></td>
    </tr>
    <%
    System.out.println(f2[ii].getPath());
    %>
    </table>
    </body>
    </html>

    Hi,
    Well i guess a Simple concept of a image servlet can cater your requirement here.
    checkout the below example of how to do it
    Configurations needed in /WEB-INF/web.xml:
    <servlet>
        <servlet-name>ImageServlet</servlet-name>
        <servlet-class>com.ImageServlet</servlet-class>
        <init-param>
           <param-name>backupFolderPath</param-name>
           <param-value>E:/application/Images</param-name>
           <!--Could use any backup folder Available on your Server and make sure we place a image file named noImage.gif which indicates that there is no file as such-->
        </init-param>
         <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/Image</url-pattern>
    </servlet-mapping>
    ImageServlet.java:
    package com;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    *@Author RaHuL
    /**Image Servlet
    *  which could be accessed Image?fid=fileName
    *  or
    *  http://HOST_NAME:APPLN_PORT/ApplnContext/Image?fid=fileName
    public class DownloadServlet extends HttpServlet{
      private static String filePath = new String();
      private static boolean dirExists = false;
      public void init(ServletConfig config){
          // Acquiring Backup Folder Part
          filePath = config.getInitParameter("backupFolderPath");
          dirExists = new File(filePath).exists();      
      private void processAction(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
           // getting fileName which user is requesting for
           String fileName = request.getParameter("fid");
           //Building the filePath
           StringBuffer  tFile = new StringBuffer();
           tFile.append(filePath);    
           tFile.append(fileName); 
           boolean exists = new File(tFile.toString()).exists();
           FileInputStream input = null;
           BufferedOutputStream output = null; 
           int contentLength = 0;
           // Checking whether the file Exists or not      
           if(exists){                  
            try{
                // Getting the Mime-Type
                String contentType = this.getContentType(tFile.toString());          
                input = new FileInputStream(tFile.toString());
                contentLength = input.available();
                response.setContentType(contentType);
                response.setContentLength(contentLength);
                 String contentDispo = "";
                  try{
                     contentDispo = request.getParameter("coid");
                  }catch(Exception exp){
                 if(contentDispo != null && contentDispo.equals("69125"))
                   response.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");       
                this.exportFile(input,response.getOutputStream());
             }catch(Exception exp){
                 exp.printStackTrace();
                 this.getServletContext().log("Exception Occured:"+exp.getMessage());
                 throw new ServletException(exp.getMessage());
           }else{
              try{
                 // Getting the Mime-Type
                String contentType = this.getContentType(filePath+"noImage.gif");          
                input = new FileInputStream(filePath+"noImage.gif");
                contentLength = input.available();
                response.setContentType(contentType);
                response.setContentLength(contentLength);
                this.exportFile(input,response.getOutputStream());
              }catch(Exception exp){
                 exp.printStackTrace();
                 this.getServletContext().log("Exception Occured:"+exp.getMessage());
                 throw new ServletException(exp.getMessage());
      /** Gets the appropriate ContentType of the File*/
      private String getContentType(String fileName){
            String url = java.net.URLConnection.guessContentTypeFromName(fileName);
               if(url == null)
                 return "application/octet-stream";
               else
                 return url;
           or one may use
           return new  javax.activation.MimetypesFileTypeMap().getContentType(fileName);
           NOTE: Do not forget to add activation.jar file in the classpath
      /** Prints the Image Response on the Output Stream*/
      private void exportFile(InputStream input,OutputStream out) throws ServletException,IOException{
             try{
                    output = new BufferedOutputStream(out);
                    while ( contentLength-- > 0 ) {
                       output.write(input.read());
                    output.flush();
              }catch(IOException e) {
                    e.printStackTrace();
                     this.getServletContext().log("Exception Occured:"+e.getMessage());
                     throw new IOException(e.getMessage());
              } finally {
                   if (output != null) {
                       try {
                          output.close();
                      } catch (IOException ie) {                     
                            ie.printStackTrace();
                         this.getServletContext().log("Exception Occured:"+e.getMessage());
                         throw new IOException(ie.getMessage());
      /** HttpServlet.doGet(request,response) Method*/
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{       
            // Calling  respective Action Method to Provide File Service
            this.processAction(request,response); 
      /** HttpServlet.doPost(request,response) Method*/
      public void doGet(HttpServletRequest request,HttpServletResponse response) throws         ServletException,IOException{
            // Calling  respective Action Method to Provide File Service
            this.processAction(request,response); 
    NOTE: The following code could be used to provide service to stream any sort of files with any sort of content
    with some minor modications.
    Inorder to access all the images you can restructure your jsp like the one below
    JSP:
    <!--
         And say we have are storing Image name & Movie details in the database and we are created a collection
         of all the database results like bean here is how we would display all the details with images
         Say you wrote a query to findout Moviename,timings,Hall Number & pictureFileName
         example:
            Movie: DIE HARD 4.0
            Timings: 10:00AM,2:00PM,9:15PM
            Hall NUmbers: 1,1,2,4 
            pictureFileName: die_hard_4.jpg
             or
            Movie: Transformers
            Timings: 11:20AM,2:20PM,10:15PM
            Hall NUmbers: 2,3,1,5 
            pictureFileName: transformers.jpg
         say you are saving the information in a dtoBean with properties like
          public class MovieBean{
             private String movieName;
             private String timings;
             private String pictureFileName;
             /* and followed by getters & setter of all those*/
          and say we have queried the database and finally collected an ArrayList<MovieBean> from the query results and
          saving it within the scope of session with the attribute name "MovieList"
    -->
    <%@ page language="java"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
    <html>
    <head>
    <title>Movie Details</title>
    </head>
    <body text="#000000" bgcolor="#FFFFFF">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#FFFFFF" width="100%" id="AutoNumber1">
    <thead>
    <tr>
        <td>Movie Name</td>
        <td>Timings</td>
        <td>Hall Numbers</td>
        <td>Poster</td>
    </tr>
    </thead>
    <tbody>
    <c:forEach var="movieBean" items="${sessionScope.MovieList}">
        <tr>
             <td><c:out value="${movieBean.movieName}"/></td>
             <td><c:out value="${movieBean.timings}"/></td>
             <td><c:out value="${movieBean.hallNo}"/></td>
             <!-- Here is where we are making use of image servlet and trying to retrive images -->
             <td><img src="Image?fid=<c:out value="${movieBean.pictureFileName}"/>" align="center" width="30" height="30"/></td>
        </tr> 
    </c:forEach>
    </tbody>
    </table>
    </body>
    </html>Hope this might help,If that does do not forget to assign the duke stars which you promised :)
    REGARDS,
    RaHuL

  • Extended Content type problem

    Extended Content type problem
    I want to extend the content type 'ExtendDocument' from 'Document'.
    So I use 'Oracle Internet File System Manager' to create a new Class Object named 'EXTENDDOCUMENT', which is extend from 'DOCUMENT', and add a attribute 'EXTENDURL'.
    This Class Object's bean class is 'ifs.beans.ExtendDocument' and server class is 'ifs.server.S_ExtendDocument'.
    I create these 2 java class and put the class files to ORACLE_AS_HOME\ifs\cmsdk\custom_classes directory.
    As I want to set the object type as 'ExtendDocument' when uploading a file which expend name is '*.wmv', so that need to change 2 default value 'ParserLookupByFileExtension' and 'IFS.PARSER.ObjectTypeLookupByFileExtension'
    So I add 'name=wmv, datatype=STRING, value=oracle.ifs.beans.parsers.ClassSelectionParser' to ParserLookupByFileExtension.
    And then add 'name=wmv, datatype=STRING, value=EXTENDDOCUMENT' to IFS.PARSER.ObjectTypeLookupByFileExtension.
    After done above actions, i restart my oracle application.
    I use CUP to upload a test file 'test.wmv' to CMSDK repository, and its type is 'EXTENDDOCUMENT'.
    But if I use FTP or WebStarterApp application to upload 'test.wmv' file to CMSDK repository, then its type is 'DOCUMENT'.
    Why and how to change to make FTP and WebStarterApp application can upload *.wmv file's type as 'EXTENDDOCUMENT'?
    anybody can help me?
    thanks.

    Nirav-P-Thakar wrote:
    FileNameMap  fnmMime        = URLConnection.getFileNameMap ( ) ;
    fnmMime.getContentTypeFor(fileName);
    URLConnection.guessContentTypeFromName(fileName);I have tried out both methods but it returns null when the file is of type MS Office or Open Office.In reply 1 BalusC said..
    "Alternatively you can use ServletContext#getMimeType() for this. It guesses the content type based on the mime mapping as it is been definied in the web.xml of the application server and the webapplication. If it returns null, then you need to add new <mime-mapping> entry to the web.xml."
    I would try doing it this way. Try including entries for the mime mappings in the deployment descriptor of the web application.

Maybe you are looking for

  • Report region with sql query

    Hi I have a report region with sql query. There are two regions in page. On top of page, user enters data and after that second region show enterd data which is report region based on sql query. Now,when this page is opned, as user had not entered an

  • How to partition a 2TB external drive to use with TM for a 250GB backup?

    My MBP only has a 250GB hard drive, but the new external drive is 2TB. I don't want to use the whole ext drive for TM back-up so what size should I create the TM backup partition so that I can use the rest for regular file storage? I saw a guideline

  • How do I open / run Cognos Impromptu Report from CSharp

    Hi, I am new to Csharp and using C# for my application development and I need to load Cognos Impromptu application and run a report from my application automatically and run the report to create ascii text file. Is there any code is available? I have

  • Photoshop cs6 crashing - using GeForce GTX680 GPU

    Hey there,     I am running a brand spanking new rig. Windows 7 pro intel i7-3930k cpu 3.2ghz 32 gig ram 64bit Geforce GTX 680 with updated drivers Adobe Photoshop CS6 keeps crashing. I do not think it supports this GPU, which is a major bummer. Do i

  • Errors with New Muse Download

    I just came back and rather than delete this post, I wanted to mention what I did in case anyone is still having problems. I just changed my preferences in the Adobe Application Manager and moved the location of the download to another drive. and all