Cast SharedByteArrayInputStream to Multipart

I get this exception java.lang.ClassCastException: javax.mail.util.SharedByteArrayInputStream cannot be cast to javax.mail.Multipart, the error appears when i try this, I already do the conexion to the server POP3. Could anyone help me??
Thanks! Here is the code...
Message [] mensajes = folder.getMessages();
for (int i=0;i<mensajes.length;i++)
System.out.println("---------->From:"+mensajes.getFrom()[0].toString());
System.out.println("Subject:"+mensajes[i].getSubject());
System.out.println("Subject:"+mensajes[i].getSentDate());
// Si es compuesto, su MIME type es multipart
if (mensajes[i].isMimeType("multipart/*"))
// Obtenemos el contenido, que es de tipo MultiPart.
Multipart multi = null;
try{
//Object la = (Object)mensajes[i].getContent();
//Vector la = (Vector)mensajes[i].getContent();
//multi = (Multipart)la;
multi = (Multipart)mensajes[i].getContent();
}catch(ClassCastException cce){
System.out.println("nel" + cce);

So then don't cast it to Multipart. Use the instanceof operator to see if it's a Multipart before you try to cast it.

Similar Messages

  • ClassCastException at Multipart mp = (Multipart) msg[i

    i want to get the attachments from emails. most of the times it works, but then i send a new mail and nothing works anymore. does anybody knows how to handle this problem, that it works really anything i need it.
    here a short extract out of my code:
                   Properties props = System.getProperties();
                   Session session = Session.getDefaultInstance(props, null);
                   Store store = session.getStore("pop3");
                   store.connect(hostname, username, password);
                   Folder folder = store.getFolder("INBOX");
                   folder.open(Folder.READ_ONLY);
                   System.out.println(folder.getMessageCount() + " Nachricht(en) vorhanden");
                   Message [] msg = folder.getMessages();
                   for (int i=0; i < msg.length; i++){
                        Files tmp = new Files();
                        Address[] adr = msg.getFrom();
                        tmp.setEmail(adr[0].toString());                    
                        Multipart multipart = (Multipart) msg[i].getContent();
                        String inputFile = null;
                        for(int j=0; j < multipart.getCount(); j++){
                             inputFile = processPart(multipart.getBodyPart(j));
                        }//for

    Hi,
    Only if the type of your content is multipart you should cast it to multipart.
    msg.getContentType();
    Tricae
    maybe this code will help:
    you should call the dumpPart method like this
    dumpPart( msg );
    Store store;
    Folder folder;
    static boolean verbose = false;
    static boolean debug = false;
    static boolean showStructure = true;
    private static void dumpPart(Part part) throws
    Exception {
    if (part instanceof Message)
    dumpEnvelope((Message) part);
    /** //Dump input stream ..
    InputStream is = part.getInputStream();
    // If "is" is not already buffered, wrap a
    BufferedInputStream
    // around it.
    if (!(is instanceof BufferedInputStream))
    is = new BufferedInputStream(is);
    int c;
    while ((c = is.read()) != -1)
    System.err.write(c);
    pr("CONTENT-TYPE: " + part.getContentType());
    * Using isMimeType to determine the content type
    avoids
    * fetching the actual content data until we need it.
    if (part.isMimeType("text/plain")) {
    pr("This is plain text");
    pr("---------------------------");
    if (!showStructure)
    System.out.println((String) part.getContent());
    } else if (part.isMimeType("multipart/*")) {
    pr("This is a Multipart");
    pr("---------------------------");
    Multipart mp = (Multipart) part.getContent();
    level++;
    int count = mp.getCount();
    for (int i = 0; i < count; i++)
    dumpPart(mp.getBodyPart(i));
    level--;
    } else if (part.isMimeType("message/rfc822")) {
    pr("This is a Nested Message");
    pr("---------------------------");
    level++;
    dumpPart((Part) part.getContent());
    level--;
    } else if (!showStructure) {
    * If we actually want to see the data, and it?s not a
    * MIME type we know, fetch it and check its Java type.
    Object o = part.getContent();
    if (o instanceof String) {
    pr("This is a string");
    pr("---------------------------");
    System.out.println((String) o);
    } else if (o instanceof InputStream) {
    System.err.println("HELLO CAU 1111");
    pr("This is just an input stream");
    pr("---------------------------");
    InputStream is2 = (InputStream) o;
    int c2;
    while ((c2= is2.read()) != -1)
    System.out.write(c2);
    System.err.println("\nHELLO CAU");
    } else {
    pr("This is an unknown type");
    pr("---------------------------");
    pr(o.toString());
    } else {
    pr("This is an unknown type");
    pr("---------------------------");
    private static void dumpEnvelope(Message msg) throws
    Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;
    // FROM
    if ((a = msg.getFrom()) != null) {
    for (int j = 0; j < a.length; j++)
    pr("FROM: " + a[j].toString());
    //TO
    if ((a = msg.getRecipients(Message.RecipientType.TO))
    != null) {
    for (int j = 0; j < a.length; j++)
    pr("TO: " + a[j].toString());
    // SUBJECT
    pr("SUBJECT: " + msg.getSubject());
    // DATE
    Date d = msg.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() :
    "UNKNOWN"));
    //FLAGS
    Flags flags = msg.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the
    system flags
    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
    String s;
    Flags.Flag f = sf;
    if (f == Flags.Flag.ANSWERED)
    s = "\\Answered";
    else if (f == Flags.Flag.DELETED)
    s = "\\Deleted";
    else if (f == Flags.Flag.DRAFT)
    s = "\\Draft";
    else if (f == Flags.Flag.FLAGGED)
    s = "\\Flagged";
    else if (f == Flags.Flag.RECENT)
    s = "\\Recent";
    else if (f == Flags.Flag.SEEN)
    s = "\\Seen";
    else
    continue; // skip it
    if (first)
    first = false;
    else
    sb.append(' ');
    sb.append(s);
    String[] uf = flags.getUserFlags(); // get user-flag
    strings
    for (int i = 0; i < uf.length; i++) {
    if (first)
    first = false;
    else
    sb.append(' ');
    sb.append(uf[i]);
    pr("FLAGS: " + sb.toString());
    // X-MAILER
    String[] hdrs = msg.getHeader("X-Mailer");
    if (hdrs != null)
    pr("X-Mailer: " + hdrs[0]);
    else
    pr("X-Mailer NOT available");
    static String indentStr = " ";
    static int level = 0;
    * Print a, possibly indented, string.
    public static void pr(String s) {
    if (showStructure)
    System.out.print(indentStr.substring(0, level * 2));
    System.out.println(s);

  • How to extract a .eml (e-mail file) "attachment" from an e-mail

    Hi,
    I have a slight problem with e-mail attachments. It's quite an explanation, so stick with me please.
    I have to extend, debug and adapt an e-mail archive for my company.
    I already worked on this project for 2 months, to make an extra batch and change some functionality of the existing e-mail archive.
    I've been outsourced for a montsh, and now back on the e-mail archive.
    There were some problems with e-mail attachments. (.gif, .doc, ...)
    Some of them weren't shown in the web application.
    The code that already has been written has a custom Email object. This e-mail object contains custom EmailBodyPart objects. Every EmailBodyPart has a disposition (Part.INLINE or Part.ATTACHMENT).
    In every JavaMail Message object, every BodyPart is read, the disposition is extracted, and an EmailBodyPart is created with the disposition and some other data. Then, this EmailBodyPart is added to the Email object.
    But sometimes, an attachment (.gif, .doc, ...) doesn't have the correct disposition in a Message, and isn't added as attachment, but as INLINE.
    This way, in the web application, there aren't any attachments visible for the e-mail, but when you send the mail back to your inbox through the web interface, you can see the attachments again.
    I had to solve this, and make the attachments visible in the web interface, and i did. I just checked if a filename was present, and if it wasn't an image (images still can be inline), then the disposition of the EmailBodyPart is set to Part.ATTACHMENT. It is visible now.
    But now on to the problem...Sometimes, an e-mail (.eml file) is added to an other e-mail as an attachment. But, this e-mail isn't included as disposition attachment, but just as an other message within the message. It doesn't even have a file name. It seems like this is just a forward or something.
    This e-mail should be visible as an attachment of the surrounding e-mail within the web interface. Does anyone have an idea how i can accomplish this and extract this body part as an attachment? Are there any headers i can check? (I printed the headers of the body part and there were only three, content-type, encoding en such ... but nothing like disposition. I tried to set the disposition to attachment to make it visible as an attachment, but that didn't work.
    Thanks already in advance.

    Hi there,
    Thanks for your reply.
    Well, it was kind of a mistake in the webapplication itself. The object passed to the related method was an instance of MimeMessage (the previous programmer only checked MimeMultiParts), and those weren't added to the vector of attachments. Now they are.
    But now i still have problems. I have to give those attachments a file name. I tried extracting the subject from the message, but in the related method the message is casted to a multipart (is needed for further processing), and i can't fetch the sub-message's subject (if i get the part, i can't get the subject header anymore).
    If i don't give the file a .eml extension, it opens a MHTML file or something, and it is unreadable by windows. If i get an InputStream of the part's content, and return that, and give the attachment a .eml extension, i get the outlook window , but all the text is pure HTML code. Not like it should be, and the mail in Outlook doesn't have any headers (no from, no to, no subject, ...)
    Any idea here ? I could suply you with some code, but i don't understand all the steps myself, i got on this project which was build by someone else. It's quite a lot of code.
    Thanks in advance.

  • Java Mail not working in Oracle

    Hi,
    I created an Java program to import attachments from a exchange server mailbox using POP3S .It works fine when run as a java application.
    But when i put this inside Oracle11g using load java and while executing it gives an error at
    Multipart mp = (Multipart) message.getContent();
    Error:
    Content-Type: multipart/mixed;
         boundary="_002_A0C2E09A..................................."
    java.lang.ClassCastException
         at Newmail.mailPOP3(Newmail:71)
    Could someone explain why I am getting this error? What can I do to resolve this error?Any help would be much appreciated.
    Regards,
    Joseph

    I assume you're checking that the message is a multipart message before casting it to Multipart.
    Is Oracle 11g running JDK 1.6?
    Are you using the latest version of JavaMail?
    Sometimes this fails because it can't find the required configuration files, due to the different
    environment in the database version of Java. Try the workaround described here:
    Re: JavaMail Problem with JRE 6.0 in an applet

  • Java Class for mail in oracle

    Hi,
    I created an Java program to import attachments from a exchange server mailbox using POP3S .It works fine when run as a java application.
    But when i put this inside Oracle11g using load java and while executing it gives an error at
    Multipart mp = (Multipart) message.getContent();
    Error:
    Content-Type: multipart/mixed;
    boundary="_002_A0C2E09A..................................."
    java.lang.ClassCastException
    at Newmail.mailPOP3(Newmail:71)
    Could someone explain why I am getting this error? What can I do to resolve this error?Any help would be much appreciated.
    Regards,
    Joseph

    Hai Matt,
    The actual class i am tested as follows,
    import java.util.Properties;
    import javax.mail.Authenticator;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.Part;
    import javax.mail.Multipart;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.internet.MimeMessage;
    public class Newmail
    public Newmail()
    super();
    public static int mailPOP3(String phost,
    String pusername,
    String ppassword)
    Folder inbox =null;
    Store store =null;
    int result = 1;
    try
    String host=phost;
    final String username=pusername;
    final String password=ppassword;
    System.out.println("Authenticator");
    Authenticator auth=new Authenticator()
    protected PasswordAuthentication getPasswordAuthentication()
    return new PasswordAuthentication(username, password);
    System.out.println("Certificate");
    String filename="D:\\Certi\\jssecacerts";
    String password2 = "changeit";
    System.setProperty("javax.net.ssl.trustStore",filename);
    System.setProperty("javax.net.ssl.trustStorePassword",password2);
    Properties props = System.getProperties();
    System.out.println("host-----"+props);
    props.setProperty("mail.imaps.port", "993");
    props.setProperty("mail.imaps.starttls.enable","true");
    props.setProperty("mail.imaps.ssl.trust", "*");
    Session session = Session.getInstance(props,auth);
    session.setDebug(true);
    store = session.getStore("imaps");
    System.out.println("store------"+store);
    store.connect(host,username,password);
    System.out.println("Connected...");
    inbox = store.getDefaultFolder().getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Message[] msgs = inbox.getMessages();
    System.out.println("msgs.length-----"+msgs.length);
    result = 0;
    int no_of_messages = msgs.length;
    for ( int i=0; i < no_of_messages; i++)
    System.out.println("msgs.count-----"+i);
    System.out.println("Attachment....>"+msgs.getContentType());
    // Casting message to multipart
    *Multipart mp = (Multipart)msgs[i].getContent();* System.out.println("Casting Success" + mp.getContentType());
    catch(Exception e)
    e.printStackTrace();
    finally
    try
    if(inbox!=null)
    inbox.close(false);
    if(store!=null)
    store.close();
    return result;
    catch(Exception e)
    e.printStackTrace();
    return result;
    In this class when running from oracle using a procedure "Multipart mp = (Multipart)msgs[i].getContent();" throws exception..
    Error:
    Content-Type: multipart/mixed;
    boundary="_002_A0C2E09A..................................."
    java.lang.ClassCastException
    at Newmail.mailPOP3(Newmail:71)
    Thanks & Regards
    Joseph

  • Error in cast to MULTIPART

    Hi, I test the follow Jguru tutorial code for getting atacchements
    Multipart multipart = (Multipart)message.getContent();
    for (int i=0, n=multipart.getCount(); i<n; i++) {
    Part part = multipart.getBodyPart(i));
    String disposition = part.getDisposition();
    if ((disposition != null) &&
    ((disposition.equals(Part.ATTACHMENT) ||
    (disposition.equals(Part.INLINE))) {
    saveFile(part.getFileName(), part.getInputStream());
    But i have a problem of cast in this line
    Multipart mp = (Multipart)message.getContent();
    the error of CastClass is:
    java.lang.String cannot be cast to javax.mail.Multipart
    why????? Please help me
    Thanks

    Most likely you don't have a multipart message. See the msgshow.java
    demo program that comes with JavaMail.

  • Message object returns SharedByteArrayInputStream instead of Multipart.

    Dear friends,
    I am using java Mail API v 1.3.1 to access POP3 server.
    I am getting problem while I try to read an RTF message from POP3 server.
    When I try to access the data through getContent() method on javax.mail.Message Object, it sometimes gives me correct result as a Multipart data, while sometimes, it returns an object of type com.sun.mail.util.SharedByteArrayInputStream.
    Although it returns SharedByteArrayInputStream object, when I invoke getContentType() on Message Object, it returns Multipart as correct.
    I think this is some problem with the JavaMail API.
    Going specifically, I use the POP server : ksc.th.com
    Waiting for reply,
    -> Maulik Soni.

    hi,
    I have the same Problem,too. But now, i have found the reason.
    the javamail jar delivers a file named 'mailcap' in the META-INF dir of the library jar with
    the following content:
    text/plain;;          x-java-content-handler=com.sun.mail.handlers.text_plain
    text/html;;          x-java-content-handler=com.sun.mail.handlers.text_html
    text/xml;;          x-java-content-handler=com.sun.mail.handlers.text_xml
    multipart/*;;          x-java-content-handler=com.sun.mail.handlers.multipart_mixed
    message/rfc822;;     x-java-content-handler=com.sun.mail.handlers.message_rfc822
    now while creating the default instance of MailcapCommandMap (activation framework),
    this class is searching the 'mailcap' file in the META-INF dir. if 'mailcap' is not found, the
    activation framework don't map these mimetyps.
    workaround:
    make sure, that the MailcapCommandMap can find the mailcap file in META-INF or in user.home dir
    or
    map manually (javax.activation.MailcapCommandMap):
    MailcapCommandMap map = (MailcapCommandMap)MailcapCommandMap.getDefaultCommandMap();
    map.addMailcap("text/plain;;x-java-content-handler=com.sun.mail.handlers.text_plain");
    map.addMailcap("text/html;;x-java-content-handler=com.sun.mail.handlers.text_html");
    map.addMailcap("text/xml;;x-java-content-handler=com.sun.mail.handlers.text_xml");
    map.addMailcap("multipart/*;;x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    map.addMailcap("message/rfc822;;x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    simple,
    if you known it.
    thx, bye.
    franz bartlechner

  • JSF RI 1.0 File Uploads mit Multipart Filter

    Hi there,
    I already posted my problem - I need support for a basic file upload. My requirement is, that I want to access teh file data in a Managed Bean method and then decice what to to with it.
    I decided to use Jason Hunters Multipart Filter, that comes with the oreilly servlet jar file. My problem with the following code is, that the upload() method is never called. I think the filter is not invoked, but I don't know why. Could anyone please see, if I am on the right track?
    First, here is my web.xml with the filter:
         <!-- OReilly MultiPart Filter - by Jason Hunter -->
         <!-- JSF RI 1.0 cannot handle MutliPart Requests -->
    <filter>
    <filter-name>multipartFilter</filter-name>
    <filter-class>com.oreilly.servlet.MultipartFilter</filter-class>
    <!-- we do not specify a special directory, the servlet containers tmp directory is used
    <init-param>
    <param-name>uploadDir</param-name>
    <param-value>/tmp</param-value>
    </init-param>
    -->
    </filter>
    <filter-mapping>
    <filter-name>multipartFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    --> this code comes at the end of my web.xml, so after the jsf cotnroller servlet is configured, etc.
    in my jsp page, I got this form:
    <h:form enctype="multipart/form-data">
    <table width="100%" border="1" cellspacing="2" cellpadding="2">
    <tr>
    <td width="25%" align="right">Bild</td>
    <td width="75%"><input type="file" name="file"></td>
    </tr>
    <tr>
    <td> </td>
    <td><h:commandButton id="upload" action="#{uploadBean.upload}" value="#{messages.uploadFile}"/>
         </td>
    </tr>
    </table>
    </h:form>
    --> the file upload is done with a normal html tag, because there is no jsf tag for it.
    then, here us may upload() method in the managed bean:
    (the upload method is never called... why???? )
         public String upload()
              log.debug("entering upload()...");
              // Files can be read if the request class is MultipartWrapper
              // Init params to MultipartWrapper control the upload handling
              HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
              if (request instanceof MultipartWrapper)
                   log.debug("The MultiPart Filter recognized the mulitpart request.");
                        // Cast the request to a MultipartWrapper
                        MultipartWrapper multi = (MultipartWrapper) request;
                        // Show which files we received
                        Enumeration files = multi.getFileNames();
                        while (files.hasMoreElements())
                             String name = (String) files.nextElement();
                             String filename = multi.getFilesystemName(name);
                             String type = multi.getContentType(name);
                             File f = multi.getFile(name);
                             log.debug("name: " + name);
                             log.debug("filename: " + filename);
                             log.debug("type: " + type);
                             if (f != null)
                                  log.debug("length: " + f.length());
              return "upload";
    THANX! it would be great to get this sample running!

    Hello!
    I have a photo which I store in MSSQL db as a BLOB so it looks like:
    | |
    | Photo |
    | |
    -----------------------+
    | c:\my.jpg | choose |
    -----------------------+
    where
    <f:verbatim>
    <input name="photo" id="photo" type="file">
    </f:verbatim>
    is rendered into standard choose file dialog (unfortunately I can't change it).
    So when user click "choose" it's able to select local file (a picture).
    Then in textbox (input) appear the path (of course it can write it directly).
    A click to the picture
    a) launch javascript:
    onclick="document.getElementById('photo').name='#{DatosPersonalesForm.foto}';"
    that change image value (file name) so I could know which file to look for later:
    <h:graphicImage value="#{DatosPersonalesForm.foto}" ...
    b) after this id calls the actionListener:
    <h:commandLink actionListener="#{DatosPersonalesForm.uploadPhoto}" ...
    In DatosPersonalesForm I have foto property (with get/set) which store foto
    public String getFoto()
    public void setFoto()
    The problem is how to return foto: I put an image in a session and get it from another servlet (registred in web.xml) which intercepts /images/* and return ones from the session.
    I tried use Base64 encoding to embedd images directly, but it works only in Mozilla (even it's html 4.01).
    here is my full DatosPersonalesForm.class (with some additional crap):
    public class DatosPersonalesForm implements Observer, Serializable
    private int idCentro = 1;
    private CurrentClient client;
    private String foto;
    //private String data;
    private Abonado abonado;
    private Persona persona;
    private DireccionTableModel direcciones;
    public DatosPersonalesForm()
    abonado = new Abonado();
    persona = new Persona();
    direcciones = new DireccionTableModel();
    public void setClient(CurrentClient client)
    this.client = client;
    client.addObserver(this);
    public void setIdCentro(int idCentro)
    this.idCentro = idCentro;
    direcciones.setIdCentro(idCentro);
    public void setIdAbonado(int idAbonado)
    if (idAbonado > 0)
    try
    abonado = AbonadoDAO.load(idAbonado, idCentro);
    persona = PersonaDAO.load(idAbonado, idCentro);
    catch (Exception ex)
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    else
    abonado = new Abonado();
    persona = new Persona();
    direcciones.setIdPersona(idAbonado);
    public Abonado getAbonado() { return abonado; }
    public void setAbonado(Abonado abonado) { this.abonado = abonado; }
    public Persona getPersona() { return persona;}
    public void setPersona(Persona persona) { this.persona = persona; }
    public DireccionTableModel getDirecciones() { return direcciones; }
    public void setDirecciones(DireccionTableModel direcciones) { this.direcciones = direcciones; }
    //public String getData() { return data; }
    public String getFoto()
    if (persona != null)
    try
    Imagenes imagenes = ImagenesDAO.load(persona.getIdImagen(), idCentro);
    if (imagenes != null)
    foto = "/images/" + putImage(imagenes.getImagen());
    //data = Base64Encoder.encode(imagenes.getImagen());
    catch (Exception ex)
    foto = "/img/photo_unavailable.jpg";
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    return foto;
    public void setFoto(String foto) { this.foto = foto; }
    public void uploadPhoto(ActionEvent e)
    // for which person to upload???
    if (persona != null)
    HttpServletRequest r = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    if (r instanceof ServletRequestWrapper)
    ServletRequest req = ((ServletRequestWrapper)r).getRequest();
    if (req instanceof MultipartRequestWrapper)
    MultipartRequestWrapper request = (MultipartRequestWrapper)req;
    byte[] photo = (byte[])request.getFiles().get(foto);
    if (photo != null)
    try
    BufferedImage original = ImageIO.read(new ByteArrayInputStream(photo));
    if (original == null) // not an image?
    return;
    BufferedImage scaled = new BufferedImage(128, 160, BufferedImage.TYPE_INT_RGB);
    Graphics g = (Graphics2D)scaled.getGraphics();
    g.drawImage(original,0,0,128,160,null);
    g.dispose();
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
    ImageIO.write(scaled, "jpg", out);
    photo = out.toByteArray();
    catch (IOException ex)
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    return;
    Imagenes imagenes = new Imagenes();
    imagenes.setIdCentro(idCentro);
    imagenes.setIdImagenes(persona.getIdImagen());
    imagenes.setImagen(photo);
    try
    ImagenesDAO.save(imagenes);
    catch (Exception ex)
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    return;
    putImage(imagenes.getImagen());
    public String clear()
    if (client != null)
    client.setIdAbonado(0);
    // must be mapped in faces-config.xml
    return "clear";
    public void save(ActionEvent e)
    try
    if (persona.getIdPersona() == 0)
    abonado.setIdCentro(idCentro);
    persona.setIdCentro(idCentro);
    Connection con = DatasourceFactory.getConnection();
    try
    con.setAutoCommit(false);
    PersonaDAO.create(con, persona);
    abonado.setIdAbonado(persona.getIdPersona()); // idPersona == idAbonado is autoGenerated by database
    AbonadoDAO.create(con, abonado);
    con.commit();
    catch(SQLException ex)
    con.rollback();
    persona.setIdPersona(0);
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    finally { con.close(); }
    // notify all about client change
    if (client != null)
    client.setIdAbonado(persona.getIdPersona());
    else
    Connection con = DatasourceFactory.getConnection();
    try
    con.setAutoCommit(false);
    PersonaDAO.save(con, persona);
    AbonadoDAO.save(con, abonado);
    con.commit();
    catch(SQLException ex)
    con.rollback();
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    finally { con.close(); }
    catch (Exception ex)
    FacesContext.getCurrentInstance().getExternalContext().log(ex.toString());
    direcciones.save(e);
    private String putImage(byte[] image)
    String name;
    HttpSession ses = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    if (ses != null)
    name = "photo_" + String.valueOf(idCentro) + "_" + String.valueOf(persona.getIdPersona()) + ".jpg";
    HashMap map = (HashMap)ses.getAttribute("ImageMap");
    if (map == null)
    map = new HashMap();
    ses.setAttribute("ImageMap", map);
    map.put(name, image);
    else
    name = null;
    return name;
    public void update(Observable o, Object arg)
    if (o instanceof CurrentClient)
    CurrentClient bean = (CurrentClient)o;
    setIdAbonado(bean.getIdAbonado());
    Cheers,
    D.
    P.S. I live in Spain so in Spanish it's foto :-) Sometimes I got crazy coz neither Spanish nor English are my native languages...
    More... in MultipartRequestWrapper you can easy remove
    public Object getAttribute(String name) method. It's my intention to map messages to request properties for easy access (like check if message exists to change style of some textfield in case of error). Do you know the better way???

  • Error in cast a variable

    these are few lines from my long STORED PROCEDURE actually i am new to oracle 11g please
    declare
    v_s nvarchar2(10);
    p_RN nvarchar2(10);
    begin
    v_s := v_s || cast(p_RN as nvarchar2(10)); - ERROR IS COMING IN THIS LINE
    end;
    error
    ORA-06550: line 5, column 39:
    PLS-00103: Encountered the symbol "(" when expecting one of the following:
    06550. 00000 - "line %s, column %s:\n%s"
    *Cause:    Usually a PL/SQL compilation error.
    *Action:
    please somebody help me

    Just a little explanation about the error message.
    ORA-06550: line 5, column 39:
    PLS-00103: Encountered the symbol "(" when expecting one of the following:
    Line 5 column 39 is the starting parenthesis of the "(10)". For using cast you can't add a lenght to the datatype.
    If you change that, then you get a different error message:
    declare
    v_s nvarchar2(10);
    p_RN varchar2(10);
    begin
      v_s := v_s || cast(p_RN as nvarchar2); -- ERROR IS COMING IN THIS LINE
    end;
    Fehler beim Start in Zeile 13 in Befehl:
    declare
    v_s nvarchar2(10);
    p_RN varchar2(10);
    begin
      v_s := v_s || cast(p_RN as nvarchar2); -- ERROR IS COMING IN THIS LINE
    end;
    Fehlerbericht:
    ORA-06550: line 5, column 22:
    PLS-00382: expression is of wrong type
    ORA-06550: line 5, column 3:
    PL/SQL: Statement ignored
    06550. 00000 -  "line %s, column %s:\n%s"
    *Cause:    Usually a PL/SQL compilation error.
    *Action:ORA-06550: line 5, column 22:
    PLS-00382: expression is of wrong type
    This shows that you can't convert/cast a nvarchzar type into another nvarchar type.
    It would work if you cast a number into a varchar2 type for example
    declare
    v_s nvarchar2(10);
    p_RN number(10);
    begin
      v_s := v_s || cast(p_RN as nvarchar2); -- ERROR IS COMING IN THIS LINE
    end;
    anonymer Block abgeschlossen.

  • Error in cast multiset in collections

    DECLARE
    TYPE emp_dept_rec IS RECORD (
    v_sal emp.sal%TYPE,
    v_name emp.ename%TYPE,
    v_deptname dept.DEPTNAME%type
    TYPE emp_dept_tab_type IS TABLE OF emp_dept_rec;
    l_emp_dept_tab emp_dept_tab_type;
    type emp_tab is table of emp%rowtype;
    type l_emp_tab is table of emp%rowtype;
    type dept_tab is table of dept%rowtype;
    type l_dept_tab is table of dept%rowtype;
    cursor e1 is
    select * from emp;
    cursor d1 is select * from dept;
    begin
    OPEN e1;
    FETCH e1
    BULK COLLECT INTO l_emp_tab;
    open d1;
    FETCH d1
    BULK COLLECT INTO l_dept_tab;
    select cast(multiset (select em.sal,em,ename ,dep.DEPTNAME
    from table(l_emp_tab) em,table(l_dept_tab) dep
    where em.deptno=dep.deptno)
    as emp_dept_tab_type)
    into l_emp_dept_tab ;
    end;
    it is giving error as
    ORA-06550: line 43, column 25:
    PL/SQL: ORA-00923: FROM keyword not found where expected
    ORA-06550: line 39, column 5:
    PL/SQL: SQL Statement ignored

    Here is an example.
    SQL> CREATE OR REPLACE TYPE emp_rec IS OBJECT (
      2                      v_sal    NUMBER(7,2),
      3                      v_name   VARCHAR2(35),
      4                      v_empno  NUMBER(4),
      5                      v_deptno NUMBER(2)
      6                      )
      7  ;
      8  /
    Type created.
    SQL> CREATE OR REPLACE TYPE emp_tab IS TABLE OF emp_rec;
      2  /
    Type created.
    SQL> CREATE OR REPLACE TYPE dept_rec IS OBJECT (
      2                      v_deptno NUMBER,
      3                      v_dname VARCHAR2(50)
      4                      )
      5  ;
      6  /
    Type created.
    SQL> CREATE OR REPLACE TYPE dept_tab IS TABLE OF dept_rec;
      2  /
    Type created.
    SQL> CREATE OR REPLACE TYPE emp_dept_rec IS
      2                     OBJECT (
      3                      v_sal     NUMBER,
      4                      v_name     VARCHAR2(35),
      5                      v_deptname VARCHAR2(30)
      6                      );
      7  /
    Type created.
    SQL> CREATE OR REPLACE TYPE emp_dept_tab_type IS TABLE OF emp_dept_rec;
      2  /
    Type created.
    SQL> set serverout on
    SQL> DECLARE
      2    l_emp_dept_tab emp_dept_tab_type; --emp_dept_tab_type declared in database
      3    l_emp_tab      emp_tab; --emp_tab declared in database
      4    l_dept_tab     dept_tab; --dept_tab declared in database
      5 
      6    CURSOR e1 IS
      7      SELECT emp_rec(sal, ename, empno, deptno) FROM emp; --Note the type casting here
      8 
      9    CURSOR d1 IS
    10      SELECT dept_rec(deptno, dname) FROM dept; --Note the type casting here
    11  BEGIN
    12    OPEN e1;
    13 
    14    FETCH e1 BULK COLLECT
    15      INTO l_emp_tab;
    16 
    17    OPEN d1;
    18 
    19    FETCH d1 BULK COLLECT
    20      INTO l_dept_tab;
    21 
    22    SELECT CAST(MULTISET (SELECT em.v_sal, em.v_name, dep.v_dname
    23                   FROM TABLE(l_emp_tab) em, TABLE(l_dept_tab) dep
    24                  WHERE em.v_deptno = dep.v_deptno) AS emp_dept_tab_type)
    25      INTO l_emp_dept_tab
    26      FROM DUAL;
    27    FOR i IN 1 .. l_emp_dept_tab.COUNT LOOP
    28      dbms_output.put_line(l_emp_dept_tab(i)
    29                           .v_sal || '--' || l_emp_dept_tab(i)
    30                           .v_name || '--' || l_emp_dept_tab(i).v_deptname);
    31    END LOOP;
    32 
    33  END;
    34  /
    1300--MILLER--ACCOUNTING
    5000--KING--ACCOUNTING
    2450--CLARK--ACCOUNTING
    3000--FORD--RESEARCH
    1100--ADAMS--RESEARCH
    3000--SCOTT--RESEARCH
    2975--JONES--RESEARCH
    800--SMITH--RESEARCH
    950--JAMES--SALES
    1500--TURNER--SALES
    2850--BLAKE--SALES
    1250--MARTIN--SALES
    1250--WARD--SALES
    1600--ALLEN--SALES
    PL/SQL procedure successfully completed.It is just for educational purpose, because the thing you have achieved by so much programming can be done easily by simple join in the table itself.
    user10447332 Newbie
    Handle: user10447332
    Status Level: Newbie
    Registered: Oct 20, 2008
    Total Posts: 227
    Total Questions: 153 (152 unresolved) >
    What a record! and most of the time you don't care to follow/revisit the thread also!.

  • Could not type cast in java embedding

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    org.xml.sax.InputSource in = (org.xml.sax.InputSource) getVariableData("Invoke_1_getRoutingAndFrameJumpers_OutputVariable","getRoutingAndFrameJumpersResponse");
    Document doc = db.parse(in);
    In the above code I am trying to type cast the variable getRoutingAndFrameJumpersResponse into org.xml.sax.InputSource so that i can parse.
    I am not getting any error during compilation
    but I am unable to type cast some run time error is coming in the line were I am type casting but I am not able to see the runtime error.
    How can I see the runtime error in java embedding, how to type cast a variable into xml so that I can parse it.

    Hi Arun,
    Could you try using the bpelx:rename extension in an assign activity enables a BPEL process to rename an element through use of XSD type casting.
    <bpel:assign>
    <bpelx:rename elementTo="QName1"? typeCastTo="QName2"?>
    <bpelx:target variable="ncname" part="ncname"? query="xpath_str" />
    </bpelx:rename>
    </bpel:assign>
    Cheers
    A

  • Derive found flag in SQL with where clause using TABLE(CAST function

    Dear All,
    Stored procedure listEmployees
    ==========================
    CREATE OR REPLACE TYPE STRING_ARRAY AS VARRAY(8000) OF VARCHAR2(15);
    empIdList STRING_ARRAY
    countriesList STRING_ARRAY
    SELECT EMP_ID, EMP_COUNTRY, EMP_NAME, FOUND_FLAG_
    FROM EMPLOYEE WHERE
    EMP_ID IN
    (SELECT * FROM TABLE(CAST(empIdList AS STRING_ARRAY))
    AND EMP_COUNTRY IN
    (SELECT * FROM TABLE(CAST(countriesList AS STRING_ARRAY))
    =================
    I have a stored procedure which lists the employees using above simple query.
    Here I am using table CAST function to find the list of employees in one go
    instead of looping through each and every employee
    Everything fine until requirements forced me to get the FOUND_FLAG as well.
    Now I wanted derive the FOUND_FLAG by using rownum, rowid, decode functions
    but I was not successful
    Can you please suggest if there is any intelligent way to say weather the
    row is found for given parameters in the where clause?
    If not I may have to loop through each set of empIdList, countriesList
    and find the values individually just to set a flag. In this approach I can’t use
    the TABLE CAST function which is efficient I suppose.
    Note that query STRING_ARRAY is an VARRAY. It is very big in size and this procedure
    suppose to handle large sets of data.
    Thanks In advance
    Regards
    Charan
    Edited by: kmcharan on 03-Dec-2009 09:55
    Edited by: kmcharan on 03-Dec-2009 09:55

    If your query returns results, you have found them... so your "FOUND" flag might be a constant,...

  • Casting in ABAP Objects

    Why the cast error generates only in Widening cast?

    Hi Shyam,
    WELCOME TO SDN!!!
    Please check this link
    http://abapprogramming.blogspot.com/2007/10/oops-abap-8.html
    The widening cast in this case does not cause an error because the reference airplane actually points to an instance in the subclass lcl_cargo_airplane. The dynamic type is therefore u2018REF TO lcl_cargo_airplaneu2019.
    Here the widening cast produces the MOVE_CAST_ERROR runtime error that can be caught with u201CCATCH ... ENDCATCHu201D, because the airplane reference does not point to an instance in the subclass lcl_cargo_airplane, but to a u201Cgeneral airplane objectu201D. Its dynamic type is therefore u2018REF TO lcl_airplaneu2019 and does not correspond to the reference type cargo_airplane.
    The widening cast logically represents the opposite of the narrowing cast. The widening cast cannot be checked statically, only at runtime. The Cast Operator u201C?=u201D (or the equivalent u201CMOVE ... ?TO u2026u201D) must be used to make this visible.
    With this kind of cast, a check is carried out at runtime to ensure that the current content of the source variable corresponds to the type requirements of the target variables. In this case therefore, it checks that the dynamic type of the source reference airplane is compatible with the static type of the target reference cargo_airplane. If it is, the assignment is carried out. Otherwise the catchable runtime error u201CMOVE_CAST_ERRORu201D occurs, and the original value of the target variable remains the same.
    Best regards,
    raam

  • Can not cast from object to int

    Hi All,
    I have the following bunch of code
    Session session;
              session = getSessionFactory().openSession();
              Query query;
              int MaxPageId = 0;
              List list;
              try{
                   query = session.createQuery("select max(emp.id) from EmpBean emp");
                   list = query.list();
                   MaxPageId = (int) list.get(0);
                   return MaxPageId;
              catch(Exception e){
                   System.out.println(e.getMessage());
              return MaxPageId;
    The query executed successfully but when i get the max id in a integer variable by the following statement
    MaxPageId = (int) list.get(0);
    I get the following error "can not cast from object to int"
    Please suggest for the same.
    -Thanks

    Cast to an Integer, not an int, and let autoboxing turn the Integer into an int.
    int maxPageId;
    maxPageId = (Integer) list.get(0);You can't cast objects into primitives.
    Autoboxing isn't casting.
    And use Java naming conventions. Local variables start with a lower-case letter.

  • Com.oreilly.servlet.multipart writeTo() question

    I am trying to write a upload servlet with com.oreilly.servlet.multipart.
    The problem I am having is specifiying the name of file on the server's side.
    When I looked at the documentation for FilePart.writeTo() ...
    com.oreilly.servlet.multipart
    Class FilePart
    java.lang.Object
    |
    --com.oreilly.servlet.multipart.Part
    |
    --com.oreilly.servlet.multipart.FilePart
    writeTo
    public long writeTo(java.io.File fileOrDirectory) throws java.io.IOException
    Write this file part to a file or directory. If the user supplied a file, we write it to that file, and if they supplied a directory, we write it to that directory with the filename that accompanied it. If this part doesn't contain a file this method does nothing.
    Returns: number of bytes written
    Throws: java.io.IOException - if an input or output exception has occurred.
    ... I figured all I had to do was supply a file to writeTo(), so that writeTo() would write to that file.
    So I modified the example servlet code (DemoParserUploadServlet.java) to do this ...
    code:
         String outFileName = dirName + "/" + xyz_UpLoadUser + "/" + name + "_" + getTS() + ".dat";
         file = new File( outFileName );
         size = filePart.writeTo(file);
    ... and I get the error ...
    javax.servlet.ServletException: Supplied uploadDir ./TEST001/FILE_1_20040220085207.dat is invalid
    I took a look at DemoRequestUploadServlet.java but that only shows me would to write files to the /tmp directory not how to change the file's name from what the user supplied in the form.
    Please help!

    Thanks for your reply :)
    I just resorted to doing something like this ...
    public void init ( ...
    dir = new File ( dirName );
    public void doPost ( ...
    String oldFileName = filePart.getFileName();
    String newFileName = dirName + "/" + xyz_UpLoadUser + "/" + name + "_" + getTS() + ".dat";
    size = filePart.writeTo(dir);
    File oldFile = new File( oldFileName );
    File newFile = new File( newFileName );
    boolean rc = oldFile.renameTo( newFileName );

Maybe you are looking for

  • IPhone 4 IOS software update

    I was asked to update my IOS software on my iPhone 4, and now it is giving me no other option than to plug it into iTunes and restore it, I dont want to lose everything, is there anything I can do?! Please help!

  • UDF for Line item number

    Hi All, Currently i'm working on a EDI2JDBC scenario. we have a field called LINE_ITEM_NUMBER at the target side. The incoming EDI signal doesn't contain the line item number and at the target side for every line item we need a create line item numbe

  • Play HD .MKV Files in Front Row

    Hi, I wish to play .MKV HD films on my Mac Mini. I have installed the latest Perian - http://perian.org/ and it plays them but they are ever so slightly jerky, i can notice it and its annoying. I have played them in VLC media player and they are perf

  • Cannot set new in points or out points

    Just installed Premier Elements 9.  These controls are missing in my Preview panel, in the sceneline. I have one inpoint and 1 outpoint per clip, cannot add new ones. I also tried configuring keyboard short cuts for these functions, no effect. What c

  • Changing music format

    I'm trying to download music to my verizon phone and it says it does not support the format- can the format be changed on my computer to transfer over to the phone?