Setting contentType...

A very simple question:
how do you set the content type so I can use html formatting? I saw somewhere it's like this
msg.setcontent("text/html"); but that doesnt seem to work...

The Part interface has 2 setContent methods with the following signatures:
setContent(ObjectsetContent(java.lang.Object obj, java.lang.String type)
AND
setContent(Multipart mp).
Examples can be found in the tutorial listed below. Additional details can be found in the JavaMail API (also listed below).
Tutorial - http://java.sun.com/developer/onlineTraining/JavaMail/
API - http://java.sun.com/products/javamail/javadocs/index.html
Best of Luck,
∞ brewman ∞

Similar Messages

  • SOAP Adapter without SOAP envelope sets contenttype to application/xml

    Hi,
    I wrote a adaptermodul for the SOAP adapter to create a SOAP:HEADER.
    I disable the SOAP envelope in the communication channel.
    Now I get a error from the WebService Provider because the SOAP Adapter sends with Content-Type application/xml and not text/xml. I set the content-type in the adapter module but it seens to not work.
    How can I correct this ?
    Regards,
    Gerald

    Hi
    Simple answer is NO, it is not possible (without party/channel/ service etc to process the request)
    but it is worth a try to check if the URL encoding works.. though I have not tried..
    for example sending the hex value of the "?" -   %3F%
    URL is a generic topic, you can search that to get more information
    (ex  :  http://www.blooberry.com/indexdot/html/topics/urlencoding.htm)
    Regards
    Vishnu

  • Setting contenttype to UTF-8 not working!!!

    I have this in my test.jsp page. When I run it in Jrun3.0 server, I got '500 internal server error'
    <%@page contentType="text/html;charset=utf8"%>
    <html>
    <head>
    <title>Untitled</title>
    </head>
    <body>
    Test
    </body>
    </html>500 Internal Server Error
    /500 Internal Server Error
    /test.jsp:
    null
    java.lang.NullPointerException
         at sun.io.Converters.getConverterClass(Converters.java:78)
         at sun.io.Converters.newConverter(Converters.java:124)
         at sun.io.ByteToCharConverter.getConverter(ByteToCharConverter.java:67)
         at java.io.InputStreamReader.(InputStreamReader.java:78)
         at allaire.jrun.jsp.JSPParser.writeXML(JSPParser.java:146)
         at allaire.jrun.jsp.JSPParser.generateXML(JSPParser.java:124)
         at allaire.jrun.jsp.JSPParser.generateXML(JSPParser.java:81)
         at allaire.jrun.jsp.JSPServlet.parsePage(JSPServlet.java:403)
         at allaire.jrun.jsp.JSPServlet.createServlet(JSPServlet.java:375)
         at allaire.jrun.jsp.JSPServlet.loadPage(JSPServlet.java:201)
         at allaire.jrun.jsp.JSPServlet.service(JSPServlet.java:168)
         at allaire.jrun.servlet.JRunSE.service(JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(JRunSE.java:925)
         at allaire.jrun.servlet.JRunRequestDispatcher.forward(JRunRequestDispatcher.java:88)
         at allaire.jrun.servlet.JRunSE.service(JRunSE.java:1131)
         at allaire.jrun.servlet.JvmContext.dispatch(JvmContext.java:330)
         at allaire.jrun.jrpp.ProxyEndpoint.run(ProxyEndpoint.java:354)
         at allaire.jrun.ThreadPool.run(ThreadPool.java:267)
         at allaire.jrun.WorkerThread.run(WorkerThread.java:74)

    Its UTF-8 and not UTF8
    You missed the hyphen ('-') in your code.

  • PayloadZipBean - variable filename inside the archive

    Hi,
    I'm using the Adapter-Specific Message Properties in a sender fileadapter to determine the incoming filename, which has variable components (i.e. date and time). After changing the prefix and suffix in a Message-Mapping the new name is applied in a receiver fileadapter. The new name is now part of the payload in the tag <Filename>. The receiver fileadapter contains the PayloadZipBean to compress the output file, everything works fine.
    Now I want the file inside my compressed archive always to have the same name as my archive has. In Stefan Grube's blog about the PayloadZipBean I only found the possibility to choose a fix name by using the MessageTransformBean (name="file.txt").
    Example:
    1. variable input filename:                       IN_RNK_20080227_1006.txt
    2. filename after Message-Mapping:        OUT_RNK_20080227_1006.gz
    3. archive filename after receiver adapter: OUT_RNK_20080227_1006.gz
        filename inside the archive:                 MainDocument (this is the default (payload-name))
    I would like to name the file inside the archive OUT_RNK_20080227_1006, too.
    Question 1: Is there any possibility to read out the mapped <Filename>-tag from the payload to use it for the element inside my archive (File Name Scheme and Variable Substitution don't work when using Adapter-Specific Message Properties).
    Question 2: Is there a way to modify the name of the payload so that I can change "MainDocument" to "OUT_RNK_20080227_1006"?
    I'm on XI 3.0 - SP19.
    Many thanks,
    Ralph

    >
    Stefan Grube wrote:
    > In this thread there is a module for reading the content type and setting the dynamic configuration:
    > sender mail adapter - attachment name
    > It should be not be so difficult to derive the reverse way
    Thanks for this info Stefan.
    [Stefan Grube's webinar on custom adapter module development|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/64a6bdab-0c01-0010-079a-b3707717cecd?prtmode=navigate]
    The code of the EJB module we had to write to get the filename from the Dynamic Configuration (ASMA) and then set the content type of the message is given below.
    * Created on Apr 23, 2008
    package zfilezipper;
    * @author Krishneel Goundar
    import javax.ejb.CreateException;
    import javax.ejb.SessionBean;
    import javax.ejb.SessionContext;
    import com.sap.aii.af.mp.module.*;
    import com.sap.aii.af.ra.ms.api.*;
    * @ejbHome<{com.sap.aii.af.mp.module.ModuleHome}>
    * @ejbLocal<{com.sap.aii.af.mp.module.ModuleLocal}>
    * @ejbLocalHome<{com.sap.aii.af.mp.module.ModuleLocalHome}>
    * @ejbRemote<{com.sap.aii.af.mp.module.ModuleRemote}>
    * @stateless
    public class SetContentTypeEJB implements SessionBean, Module{
         private SessionContext myContext;
         public void ejbRemove() {}
         public void ejbActivate() {}
         public void ejbPassivate() {}
         public void setSessionContext(SessionContext context) {
         myContext = context;
         public void ejbCreate() throws CreateException{}
         public ModuleData process(ModuleContext moduleContext,ModuleData inputModuleData) throws ModuleException{
              try {               
                   Message msg = (Message) inputModuleData.getPrincipalData();     //Used to read dynamic configuration data
                   TextPayload payload = msg.getDocument();     //Used to set 'contentType' value
                   //The name of the file to be zipped is read from the dynamic configuration.
                   String fileName = msg.getMessageProperty("http://sap.com/xi/XI/System/File", "FileName");
                   if(fileName == null)     //If no file name can be determined we set 'contentType' to "defaultbeanile.txt"
                        payload.setContentType("text/plain;charset = \"UTF-8\";filename=\"defaultbeanfile.txt\"");     
                   else     //If a file name can be found we set 'contentType' to the name of the file.
                        payload.setContentType("text/plain;charset = \"UTF-8\";filename=\"" + fileName + "\"");     
                   //After setting the value of 'contentType' we need to update the ModuleData object (inputModuleData).
                   inputModuleData.setPrincipalData(msg);
              } catch (Exception e) {
                   ModuleException me = new ModuleException(e);
                   throw me;
              return inputModuleData;          //Return the updated ModuleData object.
    Edited by: Charu Kulkarni on Apr 28, 2008 1:41 AM

  • File Download with Servlet

    In my application i have to download a file with the help of servlet.
    Everything works fine except the case where i want to open the dialog box or just let that file open in the browser.
    For e.g. when i am trying to download an excel file and i want to have a dialog box open for save, it doesnt does that but automatically open the file in browser.
    But for the above case if i dont set the "ContentType" as "application/vnd.ms-excel" then it works fine like it will open a dialog box if in the header the value of "Content-Disposition" has "attachment;" and will open it if it has "inline;"
    Could you guide me to some good study material on what can be issues or the fundamentals of setting the "fileName with extension", what if i dont set "ContentType" and what is the difference between "Attachment" and "Inline"
    Thanks

    actually youre using the trick most ppl use.. force the content type to be something else than the ms-excel..
    the content type is ment to be a guide to the browser on how to interprete the content..
    if it doesnt it will prompt you to download i.e. show the file save dialog..

  • Sending HTML in email

    HI All
    I am trying to send a email and want to be able to put a html table, the mail gets sent and after I open the email in outlook I still find html tags instead of html table.
    Can you please tell me what is the problem in my code:
    I did not have msg.setContentType option available ( when I tried to set contenttype as text/html) is the jar version I am using old?
    <code>
    import javax.mail.*;
    import javax.mail.internet.*;
    import com.sun.mail.smtp.SMTPTransport;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    public class mailHelper {
         public static void emailResults(HashMap hmTestResults) throws Exception{
              StringBuffer emailText = new StringBuffer();
              emailText.append("Hello \n");
              emailText.append("This is automatically generated message from Guidewire Regression Testing \n");
              emailText.append("\n");
              Set set = hmTestResults.entrySet();
         Iterator i = set.iterator();
         emailText.append("<html>");
         emailText.append("<body>");
         emailText.append("<table>");
         while(i.hasNext()){
              emailText.append("<tr>");
         Map.Entry me = (Map.Entry)i.next();
         emailText.append("<td>"+me.getKey() + "</td> <td> " + me.getValue()+"</td>");
         emailText.append("</tr>");
         emailText.append("</table>");
         emailText.append("</body>");
         emailText.append("</html>");
              boolean sessionDebug = false;
              Properties props = System.getProperties();
              props.put("mail.smtp.host", "host");
              props.put("mail.transport.protocol", "smtp");
              Session session = Session.getDefaultInstance(props, null);
              session.setDebug(sessionDebug);
              try
                   Message msg = new MimeMessage(session);
                   msg.setFrom(new InternetAddress("[email protected]"));
                   msg.setRecipients(Message.RecipientType.TO,     InternetAddress.parse("[email protected]", false));
                   msg.setSubject("Guidewire Regression Testing Results");
                   // create and fill the first message part
              MimeBodyPart mbp1 = new MimeBodyPart();
              mbp1.setText(""+emailText);
              // create the second message part
              MimeBodyPart mbp2 = new MimeBodyPart();
              // create the Multipart and add its parts to it
              Multipart mp = new MimeMultipart();
              mp.addBodyPart(mbp1);
              //mp.addBodyPart(mbp2);
              // add the Multipart to the message
              msg.setContent(mp);
              // set the Date: header
              msg.setSentDate(new Date());
                   SMTPTransport t =     (SMTPTransport)session.getTransport("smtp");
                   t.connect();
                   t.sendMessage(msg, msg.getAllRecipients());
              catch (Exception mex)
                   mex.printStackTrace();
         public static void main(String[] args){
              try {
                   HashMap hm = new HashMap();
                   hm.put("one", "Passed");
                   hm.put("two", "Failed");
                   mailHelper.emailATFResults(hm);
              } catch (Exception e) {
                   e.printStackTrace();
    </code>

    Thanks for the response.
    I could not use mbp1.setText(emailText.toString(), null, "html");
    Error: method setText(string, string) in the type mimebodypart not applicable for the arguments (string, null, string)
    I tried mbp1.setText(emailText.toString(), "text/html");
    I get the error
    javax.mail.MessagingException: IOException while sending message;
    nested exception is:
         java.io.UnsupportedEncodingException: text/html
         at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:421)
         at com.ccmc.gwatf.utils.mailHelper.emailATFResults(mailHelper.java:76)
         at com.ccmc.gwatf.utils.mailHelper.main(mailHelper.java:90)
    I am using multipart as I want to attach image at a later point of time.
    Please let me know.
    Thanks

  • Cache problem for servlet opening new browser window

    Requirement:
    I have JSP page say summary.jsp with link "print account summary"
    When user clicks on this link, new browser open with PDF document of summary.jsp
    This new browser window should not have address bar and toolbar.
    Solution:
    Servlet called PrintSummary which sets contenttype=application/pdf and sends the data to outputstream.
    href of link is
    Java script function is:
    function openWindow(url){
    window.open(url,'blank','toolbar=no')
    Problem:
    Since the URL of this new window is
    http:// host:portnumber/PrintSummary
    Even if I click the "Print summary" link for account2,
    being the same URL (http:// host:portnumber/PrintSummary) it accesses the existing page in the cache which is created for account 1.
    In href if I just use servlet url as
    I get the expected behaviour but then I don't have control on browser appearance and browser window will be with address bar and toolbar.
    The only option I could think of was changing URL as follows:
    <% String url ="javascript:openWindow('PrintSummary? var1="+ Math.random()+"')";
    So that URL is different all the time
    Is there any way to solve this problem?
    Thanks in advance
    M.

    I'd definitely try to use a Flex popup... but the
    flash.net.navigateToURL method is a simple way to open a popup
    window in a new browser. You can pass any data needed by the new
    page using the URLRequest and/or URLVariables. The URL you navigate
    to could, of course, be another Flex application if necessary. I
    use this only when I need to open a popup window on another site,
    or an HTML formatter report or something similar.
    Concerning yourself with the size of the popup window may be
    a bad design choice also. I, for example, have my browser
    configured to open all popups in a new tab regardless of sizing
    constraints imposed by the designer. If it is absolutely necessary
    for you to have control over the size of your popup window, you
    should follow the advice given by others and use a Flex
    popup.

  • Working Sample Code: File Download Servlet

    Pardon the cross-posting (Java Servlet Technology), but when I was researching this problem I found alot of people asking this question in here as well as in the servlet forum. So I thought this code would be helpful here too.
    Here is a complete working servlet for downloading virtually any type of file to a browser.
    It uses a file called application.properties to specify the location of the folder where the files to be downloaded reside. Of course you could modify this to allow the users to select the location as well.
    A sample URL to call the Servlet would look like this:
    http://localhost/website/servlet/DownloadAssistant?YourFileName.ext
    I tested this with varying filenames. It did have some issues if the file contained special characters like # symbol. This should be manageable however.
    Hope someone finds this useful.
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.zip.GZIPOutputStream;
    public class DownloadAssistant extends HttpServlet
    private static final String DIR = "dir";
    private String separator;
    private String root;
    public DownloadAssistant()
    Properties propFile = null;
    FileInputStream in = null;
    String JAVA_HOME = "C:\\jrun\\servers\\default\\filetest\\application.properties";
    // Get a handle on the peoperties file
    try{
    in = new FileInputStream(JAVA_HOME);
    propFile = new Properties();
    propFile.load(in);
    catch (IOException ignore){}
    separator = "/";
    // Get the directory from the application.properties file
    // e.g. C:\\Temp\\Files\\
    root = propFile.getProperty("app.directory");
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    processRequest(request, response);
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    processRequest(request, response);
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    PrintWriter out = null;
    ServletOutputStream stream = null;
    GZIPOutputStream zipstream = null;
    Object obj = null;
    String s = "";
    //determine if there is a filename appended to the url
    // If so, then decode it
    s = HttpUtils.getRequestURL(request).toString();
    int i;
    if((i = s.indexOf("?")) > 0)
    s = s.substring(0, i);
    String s1;
    if((s1 = request.getQueryString()) == null)
    s1 = "";
    else
    //s1 = decode(s1);
    s1 = URLDecoder.decode(s1);
    // No filename, so set contentType and generate error message
    if(s1.length() == 0)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<p>Could not get file name ");
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Restriction while gaining access to the file
    if(s1.indexOf(".." + separator) > 0)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<br><br><br>Restrictions on filename");
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Try to get a handle on the file
    File file = new File(root + s1);
    // Couldn't get the file, return an error message
    if(file == null)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<p>Could not read file: " + s1);
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Either the file doesn't exist or it can't be read, return an error message
    if(!file.exists() || !file.canRead())
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html><font face=\"Arial\" size=\"+1\">");
    out.println("<p>Could not read file " + s1);
    out.print("<br>Reasons are: ");
    if(!file.exists())
    out.println("file does not exist");
    else
    out.println("file is not readable at this moment");
    out.println("</font></html>");
    out.flush();
    out.close();
    return;
    // Looks like we can read/access the file, determine its type
    String s2 = request.getHeader("Accept-Encoding");
    // Is this a zip file?
    boolean flag = false;
    if(s2 != null && s2.indexOf("gzip") >= 0)
    flag = true;
    flag = false;
    if(flag)
    response.setHeader("Content-Encoding", "gzip");
    response.setHeader("Content-disposition", "attachment;filename=" + s1);
    stream = response.getOutputStream();
    zipstream = new GZIPOutputStream(stream);
    downloadFile(root + s1, zipstream);
    zipstream.close();
    stream.close();
    // It's not a zip file so treat it as any other file
    else
    response.setContentType("application/force-download");
    response.setHeader("Content-disposition", "attachment;filename=" + s1);
    stream = response.getOutputStream();
    downloadFile(root + s1, stream);
    stream.flush();
    stream.close();
    }// end processRequest()
    // This method downloads the file to the browser
    private void downloadFile(String s, OutputStream outstream)
    String s1 = s;
    byte abyte0[] = new byte[4096];
    try
    BufferedInputStream instream = new BufferedInputStream(new FileInputStream(s1));
    int i;
    while((i = instream.read(abyte0, 0, 4096)) != -1)
    outstream.write(abyte0, 0, i);
    instream.close();
    catch(Exception _ex) { }
    }//end downloadFile()
    public void init(ServletConfig servletconfig)
    throws ServletException
    super.init(servletconfig);
    String s;
    if((s = getInitParameter("dir")) == null)
    s = root;
    separator = System.getProperty("file.separator");
    if(!s.endsWith(separator))
    s = s + separator;
    root = s;
    }//end init()
    }//end servlet()

    Yes - it is useful

  • Mail Adapter - PayloadSwapBean - MessageTransformBean - German umlauts

    Hi there,
    I'm receiving mails with an attachment (.csv / .txt) that I want to process to get IDocs. Everything works fine but the conversion of German umlauts. I tried to apply several charsets (i.e. iso-8859-1, iso-8859-2, utf-8) in the contentType parameter without success. The result in my payload after swapping and transforming is a message without umlauts. All these characters have been replaced by the same 'character' that looks like a quadrangle. Therefore even the earliest possible mapping comes too late to convert this character back into umlauts, because I don't know anymore the original ones.
    When I process the same attachment with a <u>file</u> <u>adapter</u> in the same manner (until getting an IDoc) there are no problems with umlauts, the payload looks fine!
    I even checked the note 881308 (although it's said to be for the mail receiver) but it's already in the system (XI 3.0, SP 14)
    Anyone an idea to solve my problem?
    Regards,
    Ralph

    Hi Ralph,
    now I got the solution:
    Allpy the MessageTransformBean twice.
    First you set the code page for the mail attachment, how it comes to the system.
    Then you do the conversion and set the code page how the target xml should be.
    Make two entries in Module configuration:
    localejbs/AF_Modules/MessageTransformBean - contenttype
    localejbs/AF_Modules/MessageTransformBean - tranform
    as paramters you set:
    contentType - Transform.ContentType - text/plain; charset=iso-8859-1
    transform     - Transform.ContentType - text/xml; charset=UTF-8
    transform     - Transform.Class           - com.sap.aii.messaging.adapter.Conversion
    and so on.
    The problem is that outlook does not provide the content type for the attachment, so the MailTransformBean assumes UTF-8, but the attachment has iso-8859-1, so you have to set this before the conversion.
    I have tested this with XI 3.0 SP17 with note 960501 included.
    Regards
    Stefan

  • How to store images in database and retrieve them back to page?

    Well I don't know how to store an image file to a database (say MSSQL) from the JSP and retrieve it back whenever needed and put it on the JSP page? Please help me.

    I am not sure how to store images in database but what you can do is store the image into particular folder using FileOutputStream and its unique name into the database...and than retrieve it from the folder using that name retrieved from database...
    <%
    response.setContentType("text/html");
    response.setHeader("Cache-control","no-cache");
    String err = "";
    String lastFileName = "";
    String contentType = request.getContentType();
    String boundary = "";
    final int BOUNDARY_WORD_SIZE = "boundary=".length();
    System.out.println("contentType --> "+contentType);
    System.out.println("BOUNDARY_WORD_SIZE --> "+BOUNDARY_WORD_SIZE);
    if(contentType == null || !contentType.startsWith("multipart/form-data"))
    err = "Ilegal ENCTYPE : must be multipart/form-data\n";
    err += "ENCTYPE set = " + contentType;
    else
    boundary = contentType.substring(contentType.indexOf("boundary=") + BOUNDARY_WORD_SIZE);
    System.out.println("boundary --> "+boundary);
    boundary = "--" + boundary;
    try
    ServletInputStream sis = request.getInputStream();
    byte[] b = new byte[1024];
    int x=0;
    int state=0;
    String name=null,fileName=null,contentType2=null;
    java.io.FileOutputStream buffer = null;
    while((x=sis.readLine(b,0,1024))>-1)
         System.out.println("************ x ********** "+x);
         String s = new String(b,0,x);
                   System.out.println("************ s ********** \n"+s);
         if(s.startsWith(boundary))
         state = 0;
         System.out.println("name="+name);
         System.out.println("filename="+fileName);
         name = null;
         contentType2 = null;
         fileName = null;
         else if(s.startsWith("Content-Disposition") && state==0)
              System.out.println("-- 1 --");
              state = 1;
              System.out.println("s.indexOf(filename=) --> "+s.indexOf("filename="));
              if(s.indexOf("filename=") == -1)
                   name = s.substring(s.indexOf("name=") + "name=".length(),s.length()-2);
                   System.out.println("after name substring 1 "+name);
              else
                   name = s.substring(s.indexOf("name=") + "name=".length(),s.lastIndexOf(";"));
                   System.out.println("after name substring 2 "+name);
                   fileName = s.substring(s.indexOf("filename=") + "filename=".length(),s.length()-2);
                   System.out.println("fileName --> "+fileName);
                   //String fileName1 = s.substring(s.indexOf("filename=") + "filename=".length(),s.length());
                   //System.out.println("fileName1 -->"+fileName1);
                   if(fileName.equals("\"\""))
                   fileName = null;
                   else
                        String userAgent = request.getHeader("User-Agent");
                        System.out.println("userAgent --> "+userAgent);
                        String userSeparator="/"; // default
                        if (userAgent.indexOf("Windows")!=-1)
                        System.out.println("test --> "+"\\");
                        userSeparator="\\";
                        if (userAgent.indexOf("Linux")!=-1)
                        userSeparator="/";
                        System.out.println("userSeparator "+userSeparator);
                        System.out.println("fileName before inserting userSeparators "+fileName);
                        fileName = fileName.substring(fileName.lastIndexOf(userSeparator)+1,fileName.length()-1);
                        System.out.println("fileName after userSeparators "+fileName);
                        if(fileName.startsWith( "\""))
                        fileName = fileName.substring( 1);
              name = name.substring(1,name.length()-1);
              System.out.println("name 2 --> "+name);
              System.out.println("final file name "+fileName);
              if (name.equals("file"))
                   if (buffer!=null)
                   buffer.close();
                   lastFileName = fileName;
                   buffer = new java.io.FileOutputStream("/Documents and Settings/sunil/Desktop/images/"+fileName);
         else if(s.startsWith("Content-Type") && state==1)
                             System.out.println("-- 2 --");
              state = 2;
              contentType2 = s.substring(s.indexOf(":")+2,s.length()-2);
              System.out.println("contentType2 --> "+contentType2);
         else if(s.equals("\r\n") && state != 3)
                   System.out.println("-- 3 --");
              state = 3;
         else
              System.out.println("-- 4 --");     
              if (name.equals("file"))
              System.out.println("Final x :: "+x);     
              buffer.write(b,0,x);
    }     // while closing
    sis.close();
    buffer.close();
    }catch(java.io.IOException e)
    err = e.toString();
    boolean ok = err.equals("");
    if(!ok)
    out.println(err);
    else
    %>
              <SCRIPT language="javascript">
              history.back(1);
              alert('Uploaded <%=lastFileName%>');
              window.location.reload(false);
              </SCRIPT>
    <%
         out.println("done");
    %>
    </BODY>
    </HTML>
    I think it will solve ur problem..

  • How to show chinese char form db in my jsp portlet?

    How to show chinese char form db in my jsp portlet?
    I had tried to set contentType in renderResponse, but itn't work ..

    Bent,
    You can access the database from your Java portlet, just like from any other Java/JSP environment. Yes, you can use JDBC, as well as BC4J.
    The Discussion Forum portlet was built using BC4J, take a look at it's source to see how it was done.
    Also, check out Re: BC4J Java portlet anyone?, it contains a lot of useful information too.
    Peter

  • Working Sample Code: FileDownload Servlet

    Here is a complete working servlet for downloading virtually any type of file to a browser.
    It uses a file called application.properties to specify the location of the folder where the files to be downloaded reside. Of course you could modify this to allow the users to select the location as well.
    A sample URL to call the Servlet would look like this:
    http://localhost/website/servlet/DownloadAssistant?YourFileName.ext
    I tested this with varying filenames. It did have some issues if the file contained special characters like # symbol. This should be manageable however.
    Hope someone finds this useful.
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.zip.GZIPOutputStream;
    public class DownloadAssistant extends HttpServlet
    private static final String DIR = "dir";
    private String separator;
    private String root;
    public DownloadAssistant()
    Properties propFile = null;
    FileInputStream in = null;
    String JAVA_HOME = "C:\\jrun\\servers\\default\\filetest\\application.properties";
    // Get a handle on the peoperties file
    try{                         
    in = new FileInputStream(JAVA_HOME);
    propFile = new Properties();
    propFile.load(in);
    catch (IOException ignore){}
    separator = "/";
    // Get the directory from the application.properties file
    // e.g. C:\\Temp\\Files\\
    root = propFile.getProperty("app.directory");
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    processRequest(request, response);
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    processRequest(request, response);
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    PrintWriter out = null;
    ServletOutputStream stream = null;
    GZIPOutputStream zipstream = null;
    Object obj = null;
    String s = "";
    //determine if there is a filename appended to the url
    // If so, then decode it
    s = HttpUtils.getRequestURL(request).toString();
    int i;
    if((i = s.indexOf("?")) > 0)
    s = s.substring(0, i);
    String s1;
    if((s1 = request.getQueryString()) == null)
    s1 = "";
    else
    //s1 = decode(s1);
    s1 = URLDecoder.decode(s1);
    // No filename, so set contentType and generate error message
    if(s1.length() == 0)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<p>Could not get file name ");
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Restriction while gaining access to the file
    if(s1.indexOf(".." + separator) > 0)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<br><br><br>Restrictions on filename");
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Try to get a handle on the file
    File file = new File(root + s1);
    // Couldn't get the file, return an error message
    if(file == null)
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html>");
    out.println("<p>Could not read file: " + s1);
    out.println("</html>");
    out.flush();
    out.close();
    return;
    // Either the file doesn't exist or it can't be read, return an error message
    if(!file.exists() || !file.canRead())
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("<html><font face=\"Arial\" size=\"+1\">");
    out.println("<p>Could not read file " + s1);
    out.print("<br>Reasons are: ");
    if(!file.exists())
    out.println("file does not exist");
    else
    out.println("file is not readable at this moment");
    out.println("</font></html>");
    out.flush();
    out.close();
    return;
    // Looks like we can read/access the file, determine its type
    String s2 = request.getHeader("Accept-Encoding");
    // Is this a zip file?
    boolean flag = false;
    if(s2 != null && s2.indexOf("gzip") >= 0)
    flag = true;
    flag = false;
    if(flag)
    response.setHeader("Content-Encoding", "gzip");
    response.setHeader("Content-disposition", "attachment;filename=" + s1);
    stream = response.getOutputStream();
    zipstream = new GZIPOutputStream(stream);
    downloadFile(root + s1, zipstream);
    zipstream.close();
    stream.close();
    // It's not a zip file so treat it as any other file
    else
    response.setContentType("application/force-download");
    response.setHeader("Content-disposition", "attachment;filename=" + s1);
    stream = response.getOutputStream();
    downloadFile(root + s1, stream);
    stream.flush();
    stream.close();
    }// end processRequest()
    // This method downloads the file to the browser
    private void downloadFile(String s, OutputStream outstream)
    String s1 = s;
    byte abyte0[] = new byte[4096];
    try
    BufferedInputStream instream = new BufferedInputStream(new FileInputStream(s1));
    int i;
    while((i = instream.read(abyte0, 0, 4096)) != -1)
    outstream.write(abyte0, 0, i);
    instream.close();
    catch(Exception _ex) { }
    }//end downloadFile()
    public void init(ServletConfig servletconfig)
    throws ServletException
    super.init(servletconfig);
    String s;
    if((s = getInitParameter("dir")) == null)
    s = root;
    separator = System.getProperty("file.separator");
    if(!s.endsWith(separator))
    s = s + separator;
    root = s;
    }//end init()
    }//end servlet()

    Instead of hardcoding the directory where the files are located, I keep that in a file called application.properties.
    there is a property there which looks like this
    app.directory=C:\\Temp\Files\\
    It's easier to change this rather than recompiling the servlet.
    I also use that file to hold things like the JDBC driver I will be using as well as other application specific properties I don't want to hardcode.
    HTH

  • Adding CDATA To every element in xml _ JDOM

    Hi,
    I need to parse xml using JDOM and add
    CDATA to every element.
    Could anyone help me in that ?
    When I append CDATA using org.jdom.Element.setText("<!CDATA"+Mystring +"]]>" );
    CDATA has been treated like text but not as an instruction .

    Question: Please see the code below.............
    I am copying a text which is in Hindi(DBWT-yogesh font) in JTextPane. When I am trying to retrieve hindi text from JTextpane using getText() I am obtaining hashampersand123,hashampersand156(hashsymbol,ampsymbol,123;like that ) some thing like this.
    If I dont set contentType to text/html and use getText()
    I obtain some junk characters. If I copy those junk characters in xml
    and view the xml with notepad and change the font to DBWT-yogesh
    I can see hindi text.
    I need to setContentType to html because I want to display text
    as bold or italic depending on html tags in content. when I use getText() I obtain some thing like this. If I store these characters even after changing font to DBWT-Yogesh I am not able to see hindi text.
    I want to convert (hashsymbol,ampsymbol,123;like that ) to junk characters so that when I change font using notepad I must be able to see hindi text.
    Please provide help............................. your earlier answer took me in the right direction.
    package swin;
    import java.awt.Font;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    public class TextPaneProblem extends JFrame implements WindowListener{
    JTextPane jtp=null;
    public TextPaneProblem() {
    jtp=new JTextPane();
    jtp.setContentType("text/html");
    jtp.setFont(new Font("DWB-Yogesh",Font.PLAIN,24));
    getContentPane().add(jtp);
    setVisible(true);
    public static void main(String[] args) {
    TextPaneProblem TPP=new TextPaneProblem();
    TPP.addWindowListener(TPP);
    public void windowOpened(WindowEvent e) {
    public void windowClosing(WindowEvent e) {
    }

  • Displaying image on jsp

    Hi,
    I am setting image byte array to servlet output stream after setting content type as "image/jpg".
    Problem 1:
    if I set contentType as "image/jpeg" or "image/gif" it is showing some image on page and for some image red cross mark comes in upper corner.
    Problem 2 :
    For "image/jpg", File Download window pops up and asks me for saving the file. I don't want to save it.
    Below is the sequence of code in my action class.
    response.resetBuffer();
    response.setContentType("image/jpeg");
    servletOutputStream.write(barray);
    servletOutputStream.flush();
    servletOutputStream.close();
    this image should be displayed on new opened window from where i have called above action.

    Problem 1:
    if I set contentType as "image/jpeg" or "image/gif" it is showing some image on page and for some image red cross mark comes in upper corner.Well, what is the correct contentType? You can't just set it on whim, it needs to be the correct type. Which is probably why the image that are actually that type show up, while others don't.
    Take a look at these to understand how to improve your code:
    - [http://balusc.blogspot.com/2007/04/imageservlet.html]
    - [http://www.exampledepot.com/egs/javax.servlet/GetImage.html]
    For example, you should set your content length.

  • Can't change mp3 file association

    I am trying to make mp3s open up in quicktime instead of iTunes. I tried changing the association by 'get info' and changing all to quicktime however this does not change the association.
    I have also tried the following in terminal:
    System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchSer vices.framework/Versions/A/Support/lsregister \ -kill -r -domain local -domain system -domain user
    This didn't help either.
    Please help!

    As I mentioned, just because files have an mp3 extension does not mean that they are all of the same type, so I did a search to see if there were any rogues hiding somewhere.
    I didn't see anything, so I changed the associations of types MPG3 to QuickTime, and they all changed as expected. You might try changing the associations from a new user account, or check the types of the files you are trying to change to see if they match (my .mp3 files have a file type of MPG3 and a content type of public.mp3). If you don't have a utility handy, the following AppleScript will put up an information alert for each selected FInder item:
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px;
    color: #000000;
    background-color: #FFEE80;
    overflow: auto;"
    title="this text can be pasted into the Script Editor">
    -- get file types of current Finder selection
    set HomeFolder to (POSIX path of (get path to home folder))
    tell application "Finder" to get the selection as alias list
    repeat with AnItem in the result
    set ItemPath to POSIX path of AnItem
    if ItemPath contains HomeFolder then -- shorten the item name a bit
    set TheItem to "~" & text (count HomeFolder) thru -1 of ItemPath
    else
    set TheItem to ItemPath
    end if
    set {kind:TheKind, file type:FileType} to (info for AnItem)
    set TheKind to "Kind = " & quoted form of TheKind
    set FileType to "File Type = " & quoted form of FileType
    set ContentType to (do shell script "mdls -name kMDItemContentType " & quoted form of ItemPath)
    display alert ¬
    "File Types" message ¬
    TheItem & return & return & ¬
    TheKind & return & ¬
    FileType & return & ¬
    ContentType ¬
    buttons {"Cancel", "OK"} cancel button "Cancel"
    end repeat
    </pre>

Maybe you are looking for

  • MDB and XA

     

  • Start over in Dreamweaver CS6

    Does anyone know how to delete everything I've done in CS6 so I can start again from scratch?

  • Combining files into a single pdf stopped working

    I used to be able to combine files into a single pdf on my Mac using Adobe Acrobat XI Professional. Now when I select "combine files into a single pdf", I just get a short vertical line with a gray cloud around it in the center of my screen. Do I nee

  • Connection pool

    Dear All, I am searching a way to make a connection to a MSSql from my custom iView. Is it possible to make the connection by using the connection pool that located in the "KM Admin > Configuration > Content Management > Utilities > JDBC Connection P

  • Cloning an 9.0.4.2 Environment

    Good Morning. Looking for some help with a clone environment. What I have is two servers on Solaris 9. One is a webcache reverse proxy and the other is my mid tier/infra/repository. I have made a flar of both servers and put them on two identical box