UnsupportedEncodingException

Hello

I'm doing some encryption and the following code works on the Simulator, but not once I put it on my real blackberry I get an UnsupportedEncodingException:

String charset = "iso_8859_1;

.. ethical left our here

AbstractDigest ad = cl.newInstance ((AbstractDigest));
ad. Update (hashInput.ToString (). GetBytes (CharSet));

There the encodings that are guaranteed to be supported?  What are my options?

Thanks for any help.

Use dashes ('-') instead of underscores ('_') on behalf of charset: iso-8859-1.

Tags: BlackBerry Developers

Similar Questions

  • trade 11 - CIM - UnsupportedEncodingException

    Hi all

    I get the below exception when I try to run CIM

    Java.io.unsupportedEncodingException: cp720

    I use oracle 11, weblogic 10.3.6 trade and JDK 1.7 update 51

    Thanks in advance,

    I found the problem in the coding of the CMD (command line)

    to resolve this problem, Start--> Run they type

    cmd /k chcp 1250

    This encoding of cmdWindows-1250

    below are the encoding codes:

    DOS Latin1 850
    DOS Latin2 852
    Windows-1250 1250
    Windows-1252 1252
    UTF-8 65001
    ISO-8859-1 88591
    ISO-8859-2 88592

    Thank you

  • sending request giving 401 unauthorized error in Twitter

    Hi am using the following code to update my status in twitter, but gives a 401 unauthorized error

    can any one help on this... its urgency.

    Thank you

    cordially yakubpasha

    Sub update (String username, String password, string status) throws IOException {}
    String response = null;
    HttpConnection connection = null;

    /*
    * ask a String upadte my status
    */
    String query = "status =" + urlEncode (status);
    String length = String.valueOf (query.length ());
            

    /*

    * username and password code here
    */

    String userPass = username + ":" + password;
    Byte [] encrypted = Base64OutputStream.encode (userPass.getBytes (), 0,
    userPass.length (), false, false);
    String url = "https://twitter.com/statuses/update.xml";
                 
    try {}
    Connection = (HttpConnection) Connector.Open (URL);
    connection.setRequestMethod (HttpConnection.POST);
    connection.setRequestProperty ("User-Agent", "profile/MIDP-2. ("0 configuration/CLDC - 1.0");
    connection.setRequestProperty ("Content-Type", "application/x-www-formulaires-urlencoded");
    connection.setRequestProperty ("authorization", "Basic" + new String (encoded));
    connection.setRequestProperty("Content-Length",length);
                
    //
    connection.setRequestProperty ("Content-Length", len);
    OutputStream os = connection.openOutputStream ();
    OS. Write (u.GetBytes ());
    Dialog.Alert ("" + Connection.getResponseCode () + Connection.getResponseMessage ());
    If (connection.getResponseCode () == HttpConnection.HTTP_OK) {}
    StringBuffer buffer = new StringBuffer();
    InputStream is = connection.openInputStream ();
    int c;
                    
    ("Connection") Dialog.Alert;
    While ((c = is.read (())! = - 1) {}
                        
    buffer. Append ((Char) c);
                        
    }
    is. Close();
    response = buffer.toString ();
    Dialog.Alert (Response);
    }
    } catch (Exception ex) {}
    Dialog.Alert ("error message");
    System.out.println ("sdcfsdfsdfs" + ex.getMessage ());
    } {Finally
    If (connection! = null) {}
    try {Connection.Close ;}
    catch (IOException ext) {}
    }
    }
    }

    Hey I made with her...

    If any want to post a status lets you next...

    its works perfectly

    Sub update (String username, String password, string status)
    throws IOException {}
    String response = null;
    HttpConnection connection = null;

    String query = "status =" + urlEncode (status);
    String length = String.valueOf (query.length ());

    String userPass = username + ":" + password;
    Byte [] credentialsBytes = (username + ":" + password) .getBytes ();
    Byte [] encodedBytes = Base64OutputStream.encode (credentialsBytes, 0,)
    userPass.length (), false, false);
    String credentialString = new String (encodedBytes);

    String url = "https://twitter.com/statuses/update.xml";
        
    try {}
    connection = (HttpConnection), Connector.open (url);
    connection.setRequestMethod (HttpConnection.POST);

    connection.setRequestProperty ("Content-Type",
    "application/x-www-formulaires-urlencoded");
    connection.setRequestProperty ("authorization", "Basic"
    (+ credentialString);
    connection.setRequestProperty ("Content-Length", length);
    DataOutputStream out = new DataOutputStream (connection
    (. openDataOutputStream());
    out. Write (Query.GetBytes ());
    out. Flush();
    out. Close();
    If (connection.getResponseCode () == HttpConnection.HTTP_OK) {}
    StringBuffer buffer = new StringBuffer();
    InputStream is = connection.openInputStream ();
    int c;

    ("Connection") Dialog.Alert;
    While ((c = is.read (())! = - 1) {}

    buffer. Append ((Char) c);

    }
    is. Close();
    response = buffer.toString ();
    Dialog.Alert (Response);
    }
    } catch (Exception ex) {}
    Dialog.Alert ("error message");
    System.out.println ("sdcfsdfsdfs" + ex.getMessage ());
    } {Finally
    If (connection! = null) {}
    try {}
    Connection.Close;
    } catch (IOException ext) {}
    }
    }
    }
    }

    This code I copied from somewere am thanking him for sharing this code snippet
    public static String urlEncode(String s) {}
    If (s! = null) {}
    try {}
    s = String (new s.getBytes("UTF-8"), 'ISO-8859-1');
    } catch (UnsupportedEncodingException e) {}
    }
    StringBuffer tmp = new StringBuffer();
    try {}
    for (int i = 0; i)< s.length();="" i++)="">
    int b = (int) s.charAt (i);
    If ((b > = 0 x 30 && b <= 0x39)="" ||="" (b="">= 0 x 41 && b))<=>
    || (b > = 0x61 & b)<= 0x7a))="">
    tmp. Append ((Char) b);
    } Else if (b == 0x20) {}
    tmp. Append("+");
    } else {}
    tmp. Append ("%");
    If (b<= 0xf)="">
    tmp. Append ("0");
    }
    tmp. Append (Integer.toHexString ((b));
    }
    }
    } catch (Exception e) {}
    }
    Return tmp.toString ();
    }
    Returns a null value.
    }

  • How to recover the art Image since an .mp3 file ID3

    Hi all

    Is it possible to recover images art ID3 of an audio file. I used successfully MetaDataControl API to retrieve other properties of file but I can't find the art inside picture specification.

    OK, I was interested in how do you extract the image of myself, I gave you just a generalization of what to do. I wrote a 'fast' service and dirty. Fuction has many types of treaties even if not used and I have not tested on several types of images and MP3s so use at your own risk. It is not optimized and don't go back not the 'mime type' when the runction is returned because I finished creating a new string rather than edit an existing one.

    Anyway, that this should work:

    public static net.rim.device.api.system.EncodedImage getID3Image(java.io.InputStream fs, long fsPos, long fsLength, String mimeType)
            throws java.io.UnsupportedEncodingException, java.io.IOException
    {
        /*---------------------------
         * ID3 v1 tags cannot contain images, so no need to process them.
         * ID3 v1 tags are also placed at the end of the MP3 so checking the beginning of the file won't do anything useful.
         *---------------------------
         */
    
        //Read the tags, searching for the album artwork
        byte[] imageData = null;
        boolean foundImage = false;
        mimeType = null;
        while (!foundImage)
        {
            byte[] buffer = new byte[10];
            fs.mark(10);
            if ((fs.read(buffer, 0, 10) != 10) || !(new String(buffer, 0, 3, "UTF-8").equals("ID3")))
            {
                fs.reset();
                break;
            }
            fsPos += 10;
            //Found a ID3 version 2 or greater tag
    
            //Now to actually parse a tag
            int majorVersion = buffer[3] & 0xFF;
            byte minorVersion = buffer[4];
            byte[] destinationArray = new byte[4];
            System.arraycopy(buffer, 6, destinationArray, 0, 4);
            //Read a 28bit int for size
            int size = (((((destinationArray[0] & 0xFF) << 0x15) | ((destinationArray[1] & 0xFF) << 14)) | ((destinationArray[2] & 0xFF) << 7)) | (destinationArray[3] & 0xFF));
            long end = fsPos + size;
            fs.mark((int)size);
            long dataLength = end - 11L;
    
            boolean ver2 = true;
    
            if (majorVersion == 2)
            {
                //ID3 v2.2
                ver2 = true;
            }
            else if (majorVersion == 3 || majorVersion == 4)
            {
                //ID3 v2.3/ID3 v2.4
    
                //Extra data seems might exist, go through
                boolean hasExtendedHeader = (buffer[5] & 0x40) == 0x40;
                if (hasExtendedHeader)
                {
                    byte[] exHeadBuf = new byte[4];
                    fs.read(exHeadBuf, 0, 4);
                    fsPos += 4;
                    int exHeadLength = (((((exHeadBuf[0] & 0xFF) << 0x18) | ((exHeadBuf[1] & 0xFF) << 0x10)) | ((exHeadBuf[2] & 0xFF) << 8)) | (exHeadBuf[3] & 0xFF));
                    byte[] exHeadData = new byte[exHeadLength + 4];
                    System.arraycopy(exHeadBuf, 0, exHeadData, 4, exHeadLength);
                    fs.read(exHeadData, 4, exHeadLength);
                    fsPos += exHeadLength;
                    //No use for this data in the pic so just ignore it
                }
                ver2 = false;
            }
    
            for (boolean flag = true; (fsPos < dataLength) && flag; )
            {
                //Get the frame header and make sure that it is a valid frame.
                byte[] fBuf = new byte[ver2 ? 6 : 10];
                if ((fs.read(fBuf, 0, fBuf.length) != fBuf.length) || ((fBuf[0] & 0xFF) <= 0))
                {
                    flag = false;
                    continue;
                }
                fsPos += fBuf.length;
                String frameId = new String(fBuf, 0, ver2 ? 3 : 4, "UTF-8");
                destinationArray = new byte[ver2 ? 3 : 4];
                System.arraycopy(fBuf, destinationArray.length, destinationArray, 0, destinationArray.length);
                int frameCount = 0;
                switch (majorVersion)
                {
                    case 2:
                        //24bit
                        frameCount = ((((destinationArray[0] & 0xFF) << 0x10) | ((destinationArray[1] & 0xFF) << 8)) | (destinationArray[2] & 0xFF));
                        break;
                    case 3:
                        //32bit
                        frameCount = (((((destinationArray[0] & 0xFF) << 0x18) | ((destinationArray[1] & 0xFF) << 0x10)) | ((destinationArray[2] & 0xFF) << 8)) | (destinationArray[3] & 0xFF));
                        break;
                    case 4:
                        //28bit
                        frameCount = (((((destinationArray[0] & 0xFF) << 0x15) | ((destinationArray[1] & 0xFF) << 14)) | ((destinationArray[2] & 0xFF) << 7)) | (destinationArray[3] & 0xFF));
                        break;
                    default:
                        continue;
                }
                //Now read the data and check to see if it is a picture
                fBuf = new byte[frameCount];
                if (fs.read(fBuf, 0, frameCount) == frameCount)
                {
                    fsPos += frameCount;
                    if (frameId.equals("PIC") || frameId.equals("APIC"))
                    {
                        //Got the frame data
                        int refPoint = 0;
                        //First we get the encoding type
                        int encType = (fBuf[refPoint++] & 0xFF); //0=ISO8859, 1=Unicode,2=UnicodeBE,3=UTF8
                        //Second we get the mime type
                        int indexPoint = refPoint;
                        while (fBuf[refPoint++] != 0)
                        {
                        }
                        int mimeLength = refPoint - indexPoint;
                        if (mimeLength > 1)
                        {
                            mimeType = new String(fBuf, indexPoint, mimeLength - 1, "ISO-8859-1");
                        }
                        //Third we get the picture type
                        int picType = (fBuf[refPoint++] & 0xFF);
                        //Fourth we load the picture description
                        byte[] desBuf;
                        switch (encType)
                        {
                            case 0:
                            case 3:
                                //8bit string
                                byte num;
                                net.rim.device.api.util.ByteVector list = new net.rim.device.api.util.ByteVector();
                                while ((refPoint < fBuf.length) && ((num = fBuf[refPoint++]) != 0))
                                {
                                    list.addElement(num);
                                }
                                desBuf = list.toArray();
                                break;
                            case 1:
                            case 2:
                                //16bit string
                                list = new net.rim.device.api.util.ByteVector();
                                do
                                {
                                    byte item = fBuf[refPoint++];
                                    byte num2 = fBuf[refPoint++];
                                    if ((item == 0) && (num2 == 0))
                                    {
                                        break;
                                    }
                                    if (((item != 0xff) || (num2 != 0xfe)) || (encType != 1))
                                    {
                                        list.addElement(item);
                                        list.addElement(num2);
                                    }
                                }
                                while (refPoint < (fBuf.length - 1));
                                desBuf = list.toArray();
                                break;
                            default:
                                throw new java.io.UnsupportedEncodingException("Cannot get picture description. Frame Encoding is invalid.");
                        }
                        String description;
                        switch (encType)
                        {
                            case 0:
                                description = new String(desBuf, "ISO-8859-1");
                                break;
                            case 1:
                                description = new String(desBuf, "UTF-16");
                                break;
                            case 2:
                                description = new String(desBuf, "UTF-16BE");
                                break;
                            case 3:
                                description = new String(desBuf, "UTF-8");
                                break;
                        }
                        //Finally, THE MAIN EVENT, the image data
                        int imCount = fBuf.length - refPoint;
                        imageData = new byte[imCount];
                        System.arraycopy(fBuf, refPoint, imageData, 0, imCount);
                        foundImage = true;
                        break;
                    }
                }
                continue;
            }
            fs.reset();
            continue;
        }
        if (imageData != null)
        {
            //We found the image
            if(mimeType != null && mimeType.length() > 0)
            {
                //Save some time in searching for image type
                return net.rim.device.api.system.EncodedImage.createEncodedImage(imageData, 0, imageData.length, mimeType);
            }
            else
            {
                return net.rim.device.api.system.EncodedImage.createEncodedImage(imageData, 0, imageData.length);
            }
        }
        //No image found
        mimeType = null;
        return null;
    }
    

    The sample code I used was:

    try
    {
        javax.microedition.io.file.FileConnection file = (javax.microedition.io.file.FileConnection)javax.microedition.io.Connector.open(path, javax.microedition.io.Connector.READ);
        if(file.exists())
        {
            java.io.InputStream fs = file.openInputStream();
            long pos = 0L;
            long length = file.fileSize();
            String mime = "";
            net.rim.device.api.system.EncodedImage image = getID3Image(fs, pos, length, mime);
            fs.close();
        }
        file.close();
    }
    catch(Exception e)
    {
    }
    

    Just the value of 'path' and an image will be returned.

    Edit: Added an if statement that changed value Boolean ver2. Also the length and the position probably don't matter, but it was just for safety, but I says that it can decode the description with UTF-16, the javadoc for 4.7.0 (the version I made and tested with) said that he supports of UTF-16 (Big Endian), but does not specify if Big Endian UTF-16 (not) is supported. Finally, a few points of optimization could be:

    • remove the descriptions (don't know not 100% if they determine if it is album art, the logo of the Publisher, etc.)
    • remove the image type (variable picType)
    • remove the minor version
    • change (if you decide to keep) "get byte" code description image so just realize that the bytes and let Java take care to get the bytes (as what the code for the type MIME)
    • replaceing the MIME parameter with a StringBuffer type so that you can get the MIME type when the function returns.
    • remove the "if(majorVersion == 2)" block because ver2 is set to true already and does not need to be redefined.

    Edit 2: Fixed a quick Oops, also found this which sets the value type (variable picType) image:

    • X 00 other
    • x 01 32 x 32 pixels 'file icon' (PNG only)
    • x 02 other file icon
    • X 03 cover (front)
    • x 04 (back) cover
    • x 05 page of the brochure
    • x 06 Media (e.g. lable side of the CD)
    • x 07 lead artist/lead performer/soloist
    • x 08 artist/performer
    • x 09 conductor
    • X0A Band/Orchestra
    • x0B composer
    • lyricist/text writer x0C
    • Saving x0D location
    • X0E during recording
    • x0F during execution
    • x 10 screenshot of film/video
    • X 11 has light colored fish
    • X 12 illustration
    • X 13 logo group/artist
    • x 14 logo editor/Studio

    From: http://www.id3.org/id3v2.3.0

  • Coding SMS problem

    Hi guys,.

    Here is my code. When I send a sms via Simulator 8900 with the Chinese language, msg was wrong. It's unreadable code. (not only?)

    Datagram d = _dc.newDatagram(_dc.getMaximumLength());
    ...
    String msg = new String(d.getData(),"UTF-8");
    
    Dialog.Alert(msg);
    

    1. in fact, my Simulator can input and Chinese appears correctly. I see even Chinese words in the display of sms. I think that maybe there is a problem of encoding converting msg to the Chinese police.

    2 and I found that if I change the format UTF-8-GB2312, will give a UnsupportedEncodingException.

    How can I get the right encoding here?

    Any suggestion?

    Ok. I found UTF-16BE.

  • simple text to the acceptability of url?

    I want to convert the spaces containing simple text, url, so that he can bhi added to the browser

    as I am adding text to share the Tweets: TWITTER_URL + "Hello this is sample text."

    But how can I convert the string in characters acceptable browser?

    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    
    /**
     * Adapted from J2SE java.net.URLEncoder.
     */
    public class URLEncoder {
    
      public static String encode(String s, String enc)
        throws UnsupportedEncodingException {
    
        boolean needToChange = false;
        boolean wroteUnencodedChar = false;
        int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now
          StringBuffer out = new StringBuffer(s.length());
        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    
        OutputStreamWriter writer = new OutputStreamWriter(buf, enc);
    
        for (int i = 0; i < s.length(); i++) {
            int c = (int) s.charAt(i);
            //System.out.println("Examining character: " + c);
            if (dontNeedEncoding(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            //System.out.println("Storing: " + c);
            out.append((char)c);
            wroteUnencodedChar = true;
            } else {
            // convert to external encoding before hex conversion
            try {
                if (wroteUnencodedChar) { // Fix for 4407610
                    writer = new OutputStreamWriter(buf, enc);
                wroteUnencodedChar = false;
                }
                writer.write(c);
                /*
                 * If this character represents the start of a Unicode
                 * surrogate pair, then pass in two characters. It's not
                 * clear what should be done if a bytes reserved in the
                 * surrogate pairs range occurs outside of a legal
                 * surrogate pair. For now, just treat it as if it were
                 * any other character.
                 */
                if (c >= 0xD800 && c <= 0xDBFF) {
                /*
                  System.out.println(Integer.toHexString(c)
                  + " is high surrogate");
                */
                if ( (i+1) < s.length()) {
                    int d = (int) s.charAt(i+1);
                    /*
                      System.out.println("\tExamining "
                      + Integer.toHexString(d));
                    */
                    if (d >= 0xDC00 && d <= 0xDFFF) {
                    /*
                      System.out.println("\t"
                      + Integer.toHexString(d)
                      + " is low surrogate");
                    */
                    writer.write(d);
                    i++;
                    }
                }
                }
                writer.flush();
            } catch(IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = CCharacter.forDigit((ba[j] >> 4) & 0xF, 16);
                // converting to use uppercase letter as part of
                // the hex value if ch is a letter.
    //            if (Character.isLetter(ch)) {
    //            ch -= caseDiff;
    //            }
                out.append(ch);
                ch = CCharacter.forDigit(ba[j] & 0xF, 16);
    //            if (Character.isLetter(ch)) {
    //            ch -= caseDiff;
    //            }
                out.append(ch);
            }
            buf.reset();
            needToChange = true;
            }
        }
    
        return (needToChange? out.toString() : s);
      }
    
     static class CCharacter {
        public static char forDigit(int digit, int radix) {
          if ((digit >= radix) || (digit < 0)) {
              return '\0';
          }
          if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) {
              return '\0';
          }
          if (digit < 10) {
              return (char)('0' + digit);
          }
          return (char)('a' - 10 + digit);
      }
      }
      public static boolean dontNeedEncoding(int ch){
        int len = _dontNeedEncoding.length();
        boolean en = false;
        for(int i =0;i< len;i++){
          if(_dontNeedEncoding.charAt(i) == ch)
          {
            en = true;
            break;
          }
        }
    
        return en;
      }
      //private static final int caseDiff = ('a' - 'A');
      private static String _dontNeedEncoding = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -_.*";
    
      /**
       * @param args  test string
       */
      public static void main(String[] args) {
        String s = args[0];
        try {
          System.out.println(encode(s,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
      }
    }
    
  • SHA1

    Hello

    I try to get the type (php default) sha1 of a string. Here's what I have so far:

    SHA1Digest sha1Digest = new SHA1Digest();
    Sha string = "test string"; This string has been changed for security reasons

    sha1Digest.Update (SHA. GetBytes(), 0, sha.length ());
    Digest of Byte [] = sha1Digest.getDigest ();
    SHA = "";
    for (int a = 0;< digest.length;="">
    {
    SHA += digest [a];
    }
    System.out.println ("sha:" + sha);

    but it brings something like 69785171-7241-731860-91-81-11884-401-11041-56-40-88 for example, an incorrect value

    can you guys help out me? Anyone know what I'm doing wrong? Or maybe someone knows a better way to do this?

    Note: I already have stuff of security using the IDE Edit > preferences > Code Signing > RIM Crypto API (marked true)

    and all the keys have been acquired and installation

    Thanks for your help guys

    I agree with mreed that you use Integer.toHexString (0xFF & digest [a]). Also I suggest you use getBytes otherwise because your use is based on several aspects of default encoding. For example in some encodings .length str.getBytes () is not the same as str.length (). And there may be no appropriate code some non standard symbols. I suggest to use UTF - 8 (or uses the same encoding of your PHP code).

    private void doTest() throws UnsupportedEncodingException
    {
        SHA1Digest sha1Digest = new SHA1Digest();
        String sha = "teststring";
    
        byte[] inpData = sha.getBytes("UTF-8");
        sha1Digest.update(inpData, 0, inpData.length);
        byte[] digest = sha1Digest.getDigest();
        StringBuffer shaRes = new StringBuffer(40); //40 hex char is size of 160-bit SHA-1 result
        for (int a = 0; a < digest.length; a++)
        {
            String tmp = Integer.toHexString(0xff & digest[a]);
            if(tmp.length() == 1) //If hex value is "0X" then tmp is just one digit "X"      {
                shaRes.append('0');
            }
            shaRes.append(tmp);
        }
        System.out.println("shaRes: " + shaRes.toString());
    }
    

    This code gives me the same result as the implementation for the http://jssha.sourceforge.net/

    You can encapsulate byte [] inpData = sha.getBytes("UTF-8"); in try/catch and ignore UnsupportedEncodingException because as far as I KNOW UTF - 8 is supported by all BB devices.

    PS code is updated according to the mreedof fix for '0' in the result.

  • SocketConnection packets TCP 1 byte

    I encounter strange behavior when using SocketConnection. I use JDE 4.6.0 and you encounter the problem on a "Bold" 4.6.0.185 OS as well as the OS 4.6.0.216.

    When sending a string/bytes on a SocketConnection device sends each byte as a single TCP packet. Is this a bug in the OS or I do something wrong?

    My code looks like this (Simplified):

      public void connect() {      sendThread = new SendThread();      sendThread.start();
    
          connectionThread = new ConnectionThread();      connectionThread.start();  }
    
      public void send( String data ) {    /* put data into sending queue */  }
    
      public class ConnectionThread extends Thread {      public void run() {          SocketConnection connection = (SocketConnection)Connector.open( "socket://" + host + ":" + port + ";deviceside=true;interface=wifi;ConnectionTimeout=1800000" ); 
    
          InputStream readerStream = connection.openInputStream();      OutputStream writerStream = connection.openOutputStream();
    
          // put some data into sending queue      send( " version='1.0'>" );
    
          while( true ) {        readerStream.read();      }    }  }
    
      public class SendThread extends Thread {      public void run() {            while( true ) {        for( /* sending queue */ ) {          _send( data );        }      }    }
    
        private void _send( String data ) {            byte [] encodedBuffer = null;          try {            encodedBuffer = xmpp.getBytes("UTF-8");          } catch( UnsupportedEncodingException e ) {            encodedBuffer = xmpp.getBytes();          }        }
    
            try {          writerStream.write( encodedBuffer );          writerStream.flush();        }        catch(IOException e)        {        }       }    }  } 
    

    I don't change any SocketStream options. Access to the file sending is correctly synchronized. Reading in the ConnectionThread is more sophisticated and actually consume the data.

    That's what I see on the network. Using another (Windows) client to connect to the server works properly, so this isn't a problem with the server.

    root@Debian-40-etch-32-minimal: ~ #.

    signature ngrep w - q r the 76.110.XX host. XX and port 5222
    Interface: eth0 (85.10.193.64/255.255.255.224)
    filter: (ip or ip6) and (76.110.XX the host. XX and port 5222)

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    s

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    t

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    r

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    e

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    one

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    m

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    :

    (...)

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    .

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    0

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    '

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    >

    T 85.10.XX. XX:5222-> 76.110.XX. XX:55192 [AP]
    http://EtheRx.Jabber.org/streams"xmlns =" jabber client: "from =" host.com"id ="59649 b 8"XML: lang ="en"version ="1.0">"

    T 85.10.XX. XX:5222-> 76.110.XX. XX:55192 [AP]
    arams:XML:ns:XMPP - tls ">arams:xml:ns:xmpp - sasl" >DIGEST-MD5PLAINANONYMOUSCRAM-MD5SHAREDSECRET JIVEhttp://jabber.org/features/compress "' >zlib <> xmlns ="http://jabber.org/features/iq-auth "/ >: features >

    (actually two bytes * here seem to Miss! There should be"<' and="">

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    q

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    t

    T 76.110.XX. XX:55192-> 85.10.XX. XX:5222 [AP]
    There

    OK, so I found the problem :-)

    My code is actually oversimplified, and I left out an important part. I was not using OutputStream but instead to use a derived class, that I would spend the OutputStream of the connection.openOutputStream call.

    The problem with my derived class was that she only substitute write (int data) and do not write (byte [] data).

    What happens in this case, it's that the default implementation calls OutputStream.write (byte [] data) write (int data) for each single byte.

    The fix was also replace write (byte [] data) and call the write method (byte [] data) of the original stream.

  • With the help of several classes and create an object of a class and calling its method in a different class.

    Creating a new class, I need to move my main method class SaveDate DynamicTest class. Below I've listed the code of both classes. The goal is to be able to run my class DynamicTest program. I need help to understand the process of moving my main method of a different class and creating an object of a class and calling its method.

    public class {SaveData

    private public static final map < String, Object > myCachedTreeMap = new TreeMap < String, Object > ();

    public static final List < String > getLines (final String resourceParam, final Charset charset) throws IOException {}

    System.out.println ("please:" + resourceParam);

    If {(myCachedTreeMap.containsKey (resourceParam))

    Use the file cached, to avoid a further reading.

    System.out.println ("found in memory:" + resourceParam);

    }

    else {}

    Load the file from the disk

    System.out.println ("found in memory:" + resourceParam);

    }

    Returns a null value.

    }

    Public Shared Sub main (String [] args) throws IOException {}

    String target_dir = "C:\\myfiles\\config\\en";

    Line = "C:\\myfiles\\config\\en\\output.txt";

    File dir = new File (target_dir);

    File files [] = dir.listFiles ();

    If (file == null: files.length < 1) {}

    System.out.println ("file list is empty...");

    return;

    }

    Open the Printwriter

    PrintWriter OutputStream = new PrintWriter (output);

    try {}

    for (textFile file: files) {}

    If (textFile.isFile () & & textFile.getName () .endsWith (".txt")) {}

    readFromDisk (textFile);

    }

    }

    }

    {Finally

    outputStream.close ();

    }

    String fileNameFromCache = "en_synonyms.txt";

    Sheet1 = myCachedTreeMap.get (fileNameFromCache) object;

    System.out.println (fileNameFromCache + ": \n" + "Sheet1");

    }

    @SuppressWarnings ("resource")

    private static Sub readFromDisk(File textFile) throws FileNotFoundException, IOException {}

    BufferedReader InputStream;

    inputStream = null;

    String content = "";

    try {}

    inputStream = new BufferedReader (new FileReader (textFile));

    content = readFile (textFile);

    System.out.println ("bytes read =" + content.length ());

    Save the content

    FileContentsObject Sheet1 = new FileContentsObject (System.currentTimeMillis (),

    textFile.lastModified (), content,

    textFile.getName (),

    getLines (null, null));

    Add to the map

    myCachedTreeMap.put (textFile.getName (), Sheet1);

    }

    {Finally

    If (inputStream! = null) {}

    inputStream.close ();

    }

    }

    }

    private static String readFile(File f) throws FileNotFoundException, IOException, UnsupportedEncodingException {}

    Text of StringBuilder = new StringBuilder (1024);

    read int, N = 1024 * 1024;

    char [] buffer = new char [N];

    BufferedReader br = null;

    try {}

    BR = new BufferedReader)

    (new) InputStreamReader

    (new FileInputStream (f), 'UTF8'));

    While (true) {}

    read = br.read (buffer, 0, N);

    If (read > 0)

    Text.Append (new String (buffer, 0, read));

    if(Read < N) {}

    break;

    }

    }

    }

    {Finally

    If (br! = null)

    Br. Close();

    }

    Return text.toString ();

    }

    private static final class FileContentsObject {}

    private long cachedTime; currentTime

    private long lastModifiedTimestamp;

    private string content

    List < String > lines;

    private String fileName;

    public FileContentsObject (long cachedTime, long lastModifiedTimestamp,

    Content string, String fileName, List < String > lines) {}

    this.cachedTime = cachedTime;

    this.lastModifiedTimestamp = lastModifiedTimestamp;

    This.contents = content;

    this.fileName = filename;

    This.Lines = lines;

    SimpleDateFormat sdf = new SimpleDateFormat ("MM/dd/yy hh: mm :"); ")

    System.out.println ("time & Date:" + sdf.format (cachedTime));

    System.out.println ("' last modification timestamp:" ")

    + sdf.format (lastModifiedTimestamp));

    }

    /**

    *

    * @return the lines of the file

    */

    List < String > getLines() {}

    Return this.lines;

    }

    public String toString() {}

    "return"Sheet1 {}"+" fileName =' ' + filename + '------"+", content = "" "

    + content + "\"+ ", lastModifiedTimestamp ="

    + lastModifiedTimestamp + ', CurrentTime & Date ='

    {+ cachedTime + '}';

    }

    }

    }

    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    public class DynamicTest {}

    Public Shared Sub main (String [] args) {}

    Game characters charset = Charset.forName("UTF-8");

    try {}

    List < String > = CacheData.getLines lines ("en_synonyms", character set);

    If (rows! = null) {}

    System.out.println ("number of rows:" + lines.size ());

    for {(String ligne: lines)}

    System.out.println ("DynamicTest:" + line);

    }

    }

    } catch (IOException e) {}

    e.printStackTrace ();

    }

    try {}

    List < String > = CacheData.getLines lines ("en_stopwords", character set);

    If (rows! = null) {}

    System.out.println ("number of rows:" + lines.size ());

    for {(String ligne: lines)}

    System.out.println ("DynamicTest:" + line);

    }

    }

    } catch (IOException e) {}

    e.printStackTrace ();

    }

    }

    }

    I have read and watched videos about the creation of an object of a class and calling its method in a different class. I'm still confused on how to do it properly. By using the code below if someone can explain how to properly call the method of objects from my hand.

    Huh? You have NOT posted any 'hand' or any 'method of objects '.

    If you need help with the code, you need to view the code.

    The Java tutorials has dozens of trails "Classes and objects": what they are, how to create and how to use them.

    https://docs.Oracle.com/javase/tutorial/Java/javaOO/classes.html

    1. create an instance of a class

    2. call to one or more of the public methods of this class

    If the class has public static methods, you don't need to create an instance first.

    I suggest that you work your way through these tutorials. They include the WORKING example code.

  • How to get an overview of a document within the framework in my application

    Hello

    I have an ADF project that integrates with Cloud Computing service for the oracle document

    I can download, download, create folder, delete the folder and file list version using my ADF application.

    My problem is one which is how can I preview the document on cloud of in my adf page. I don't want to download the file, I want to see it.

    I tried to accomplish this task, but I faced this error

    but this error occurs

    java.lang.RuntimeException: failed: HTTP error code: 400

    State Info: Bad Request


    What follows is the source of the page

      <af:panelStretchLayout id="psl1" binding="#{backingBeanScope.backing_WEBINF_fragments_previewDoc.psl1}"
                               dimensionsFrom="parent" topHeight="250px" endWidth="50px">
            <f:facet name="center">
                <af:panelBox text="Preview Area" id="pb4"
                             binding="#{backingBeanScope.backing_WEBINF_fragments_previewDoc.pb4}" type="stretch"
                             styleClass="AFStretchWidth">
                    <f:facet name="toolbar"/>
                    <af:inlineFrame id="if1" source="#{cloud.frameSource}" partialTriggers="b1"/>
                  
                   
                </af:panelBox>
            </f:facet>
            <f:facet name="top">
        <af:panelBox text="Preview Uploaded File By File ID" id="pb2">
                        <f:facet name="toolbar"/>
                            <af:inputText label="Enter File Id" id="it1"                                     
                                          value="#{cloud.fileId}" placeholder="Copy and paste the file id here"/>
                            <af:button text="Preview" id="b1"                                 
                                       action="#{cloud.viewFileAction}"/>
                       
                    </af:panelBox>
                </af:panelGroupLayout>
    

    When the user click on the Preview button, the document should be included as part of the line

    It is the method that returns the string url of the document. To be honest, as this method is not mine, I took this post How to integrate oracle doucument cloud service at my request

    And I add a few modifications to this

    public String getFileUrl() {
    
    
            //Read properties file to get host, port, contextroot, username, password
            try {
                m_protocol = SamplesUtils.readConfigFileValue("protocol", m_cfgFilePath);
                m_host = SamplesUtils.readConfigFileValue("host", m_cfgFilePath);
                m_username = SamplesUtils.readConfigFileValue("username", m_cfgFilePath);
                m_password = SamplesUtils.readConfigFileValue("password", m_cfgFilePath);
                m_contextroot = SamplesUtils.readConfigFileValue("contextroot", m_cfgFilePath);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return;
            }
    
    
            try {
                Client client = SamplesUtils.getClient();
                String resourceStr = m_protocol + "://" + m_host + "/" + m_contextroot;
                System.out.println("Calling GET on " + resourceStr + m_restresource);
                WebResource webResource = client.resource(resourceStr + m_restresource);
                String authString = m_username + ":" + m_password;
    
    
                try {
                    authString = DatatypeConverter.printBase64Binary(authString.getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
    
    
                ClientResponse response =
                    webResource.header("Authorization", "Basic " + authString).post(ClientResponse.class);         
              
                if (response.getStatus() != 200) {
                    throw new RuntimeException("Failed : HTTP error code: " + response.getStatus() + "\nStatus Info: " +
                                               response.getStatusInfo());
                }         
                Item item = response.getEntity(Item.class);
    
    
                //To print out all folder and item info, just call toString on the Object. A little verbose, however.
                System.out.println(item);
    
    
                //Print out individual top level variables of FolderItems object
                System.out.println("*************************************************************************");
                System.out.println("Name: " + item.getName());
                System.out.println("Owned by: " + item.getOwnedBy().getDisplayName());
                System.out.println("Created by: " + item.getCreatedBy().getDisplayName());
                System.out.println("Modified time: " + item.getModifiedTime());
                System.out.println("Id: " + item.getId());
                System.out.println("Parent Id: " + item.getParentID());
                System.out.println("ErrorCode: " + item.getErrorCode());
                System.out.println("Size in bytes: " + item.getSize());
                System.out.println("Version: " + item.getVersion());
                System.out.println("*************************************************************************");
    
    
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
      return resourceStr+"applinks/file/"+item.getId()
        }
    

    You have a bad request. You are not passing in the attributes assignerUser and role on the URL that is required to create Applink. You pass to one these two parameters in like a load of JSON or URL params.

    JsonPayload String = "{\"assignedUser\":\. "" + m_assignedUser + "\",\"role\":\ " » » + m_role + « \ »} » ;

    Or on the URL:

    /API/1.1/applinks/file/DCA4BBA0908AE2F497832BC2T0000DEFAULT00000000?assignedUser=someusername&role=Downloader

    Example below shows passing as a string in JSON format.  I also atrtached the POJO AppLink.java I use entitled it the answer, so the values are accessed.

    
    /* ********************************************************************************************************************
     * Sample class to create an AppLink using POST against document cloud using the Jersey API.
     * Tested on JDeveloper 12c, with libraries JAX-RS Jersey (Bundled) and JAX-RS Jackson (Bundled) attached to project. JDK 1.7.
     *
     * Compile jar list includes:
     * javac -classpath C:\JDeveloper\mywork\JerseyRestClient\Project1\classes;C:\jdev12\oracle_common\modules\asm-3.1.jar;C:\jdev12\oracle_common\modules\jersey-core-1.18.jar;C:\jdev12\oracle_common\modules\jersey-server-1.18.jar;C:\jdev12\oracle_common\modules\jersey-servlet-1.18.jar;C:\jdev12\oracle_common\modules\jersey-json-1.18.jar;C:\jdev12\oracle_common\modules\jersey-client-1.18.jar;D:\JerseySamples\modules\jersey-multipart-1.12.jar C:\JDeveloper\mywork\JerseyRestClient\Project1\src\project1\DCJerseyClientTestGet.java
     *
     * Update the config.properties file for the POST request to run the desired Documents Cloud service.
     * Update the m_assignedUser to any user id. User can be a provisioned user id, or a non-provisioned ad-hoc value.
     * Update the role to be viewer, downloader, or contributor
     *********************************************************************************************************************/
    
    package documents.cloud.restsamples;
    
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    
    import documents.cloud.pojos.AppLink;
    
    import java.io.UnsupportedEncodingException;
    
    import javax.xml.bind.DatatypeConverter;
    
    public class CreateFileAppLink {
        // Configuration values. May need to change m_cfgFilePath to point to properties file if at a different location.
        static public String m_cfgFilePath = "src/documents/cloud/restsamples/config.properties";
        static public String m_protocol, m_host, m_username, m_password, m_contextroot = null;
        //Rest resource needs a valid GUID for the file to copy
        static public String m_restresource = "/api/1.1/applinks/file/DCA4BBA0908AE2F497832BC2T0000DEFAULT00000000";
        //Payload parameters needed for POST
        static public String m_assignedUser = "MyTestUser";
        static public String m_role = "viewer";
    
        @SuppressWarnings("oracle.jdeveloper.java.semantic-warning")
        public static void main(String[] args) {
    
            //Read properties file to get host, port, contextroot, username, password
            try {
                m_protocol = SamplesUtils.readConfigFileValue("protocol", m_cfgFilePath);
                m_host = SamplesUtils.readConfigFileValue("host", m_cfgFilePath);
                m_username = SamplesUtils.readConfigFileValue("username", m_cfgFilePath);
                m_password = SamplesUtils.readConfigFileValue("password", m_cfgFilePath);
                m_contextroot = SamplesUtils.readConfigFileValue("contextroot", m_cfgFilePath);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return;
            }
    
            try {
                //POST needs a json payload with parameters for new applink
                String jsonPayload = "{\"assignedUser\":\"" + m_assignedUser + "\",\"role\":\"" + m_role + "\"}";
                //Call static method to get client object for calling rest
                Client client = SamplesUtils.getClient();
                String resourceStr = m_protocol + "://" + m_host + "/" + m_contextroot;
                System.out.println("Calling POST on " + resourceStr + m_restresource + " with payload " + jsonPayload);
                WebResource webResource = client.resource(resourceStr + m_restresource);
                String authString = m_username + ":" + m_password;
    
                try {
                    authString = DatatypeConverter.printBase64Binary(authString.getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
    
                ClientResponse response =
                    webResource.header("Authorization", "Basic " + authString).header("Content-Type",
                                                                                      "application/json").post(ClientResponse.class,
                                                                                                               jsonPayload);
    
                //Check for success, otherwise exit.
                if (response.getStatus() != 200) {
                    throw new RuntimeException("Failed : HTTP error code: " + response.getStatus() + "\nStatus Info: " +
                                               response.getStatusInfo());
                }
    
                //If pure json response is needed, use String.class to get the response.
                //String output = response.getEntity(String.class);
                //System.out.println(output);
    
                //Declare object that JSON string will be mapped into, then get the response into that object
                AppLink al = response.getEntity(AppLink.class);
    
                //To print out all applink info, just call toString on the Object.
                System.out.println(al);
    
                //Print out individual top level variables of file applink object
                System.out.println("*************************************************************************");
                System.out.println("URL: " + al.getAppLinkUrl());
                System.out.println("Access Token: " + al.getAccessToken());
                System.out.println("AppLink ID: " + al.getAppLinkID());
                System.out.println("Refresh Token: " + al.getRefreshToken());
                System.out.println("Error Code: " + al.getErrorCode());
                System.out.println("ID: " + al.getId());
                System.out.println("*************************************************************************");
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
  • The ADF security: end_url is not used when logout

    Hello

    JDev 11.1.2.4

    We have activated ADF security and use OAM to manage security. When disconnect you, we want to redirect to a page with the following code:

    {} public void logout())

    FacesContext fctx = FacesContext.getCurrentInstance ();

    ExternalContext ectx = fctx.getExternalContext ();

    String endUrl = null;

    try {}

    endUrl = URLEncoder.encode ("http://www.google.com", "UTF - 8");

    } catch (UnsupportedEncodingException e) {}

    _logger.severe ("Url of late encoding of exception", e);

    }

    String url = ectx.getRequestContextPath () + "/ adfAuthentication?" Logout = true & amp; end_url ="+ endUrl;

    try {}

    ectx. Redirect (URL);

    } catch (IOException e) {}

    e.printStackTrace ();

    }

    fctx.responseComplete ();

    }

    It works with IE, the user is redirected to google. But it does not for Firefox or Chrome. The generated URLS are:

    IE: http://myserver:14100 / oam/Server/osso_logout? p_done_url = http://www.google.com

    FF/Chrome: http://myserver:14100 / oam/Server/osso_logout? p_done_url=

    Is this a bug?

    Thank you

    ' / adfAuthentication? Logout = true & end_url ='

    URL params are separated by ' & ' character which should be: "/ adfAuthentication?»»» Logout = true & end_url ='

    Dario

  • Deployed Captcha Code on webcenter spaces using custom task flow

    Dear,

    I use Captcha Code, the new workflow and the fragment to be deployed on webcenter spaces, the code works correctly when am run of JDeveloper 11.1.1.4.0, but when I deploy him on spaces webcenter 11.1.1.5 version and call this webcenter flow task space image appears not (actually its code Servlet).

    as mentioned on Oracle PDF (http://www.oracle.com/technetwork/developer-tools/adf/learnmore/index-101235.html)-> How to use Captcha with ADF Faces and Oracle ADF

    Add Servlet in web.xml, then do Managed Bean Code (add in faces-config. (XML), then create a new task workflow and call the method that run the managed Bean of ADF task flow Page.

    1 - Servlet in web.xml:
    < servlet >
    < name servlet - > CaptchaServlet < / servlet-name >
    > the servlet class < nl.captcha.servlet.SimpleCaptchaServlet < / servlet-class >
    < init-param >
    width of < param-name > < / param-name >
    < param-value > 250 < / param-value >
    < / init-param >
    < init-param >
    height of < param-name > < / param-name >
    < param-value > 75 < / param-value >
    < / init-param >
    < / servlet >
    < servlet-mapping >
    < name servlet - > CaptchaServlet < / servlet-name >
    captchaservlet.jpg < url-pattern > < / url-pattern >
    < / servlet-mapping >

    2 - managed Bean:
    public void callMethod() {}

    FacesContext fctx = FacesContext.getCurrentInstance ();
    ExternalContext ectx = fctx.getExternalContext ();
    HttpServletRequest request = (HttpServletRequest) ectx.getRequest ();
    CAPTCHA captcha (Captcha) = ectx.getSessionMap () .get (Captcha.NAME);
    try {}
    request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {}
    bad luck - but ignore
    System.out.println ("unsupported UTF!");
    }
    String response = (String) ectx.getRequestMap () .get ("bestGuess");
    If (response! = null & & captcha.isCorrect (answer)) {}
    sendMail();
    SendMail_ToExternal();

    } else {}
    fctx.addMessage (null,
    new FacesMessage (FacesMessage.SEVERITY_ERROR, "Please enter the number shown in the picture",
    null));
    }

    }


    I'm download the JAR of Captcha of Oracle: http://www.oracle.com/technetwork/developer-tools/adf/learnmore/index-101235.html, Captcha download a use as task flow to deploy on webcenter spaces, but as I told you when I run this code of JDeveloper works correctly, but the problem when I deploy him on webcenter spaces code Servlet with image does not appear. I want to know if the servlet working with deployed code task flow on the webcenter spaces, or not?

    Please advise...

    Thank you

    Did you add the configuration of servlet to WebCenter spaces? See the documentation for steps to do this: http://docs.oracle.com/cd/E25054_01/webcenter.1111/e12405/wcadm_app_config_files.htm#CHDJCCBI

  • Variable recovery of ODI in Java Beanshell (target Beanshell Source Oracle)

    Hi guys:

    I am faced with a simple problem, but I am not able to find the solution in the documentation or any post in this forum. I have a procedure where I use the two tabs (Source and target) and need to retrieve the result of the 'StrParam' (query Oracle) in a variable BeanShell (OracleMessageData).

    In the target tab, I have these commands (Java BeanShell Techonology):

    < @.
    to import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;

    String OracleMessageData = "#strParam";
    String PathOfXMLFiles = "< %=odiRef.getSchemaName ("LS_FILE_XMLFULL","D") % > ';
    .
    .
    .
    @ >

    In the Source tab, I have this command (Techonology Oracle):

    SELECT MESSAGEDATA < %=odiRef.getSchemaName ("LS_ORACLE_ODI_WRK", "D") % >. CONTENT_RIB_MSGDATA strParam

    ---------------------

    How can I recover the contents of the command Source in the variable in the target? The line below does not work:

    String OracleMessageData = "#strParam";


    I use ODI_11.1.1.6.0_GENERIC_111219.1055

    Kind regards.
    Luiz Araujo

    Published by: Luiz_Araujo on 25/07/2012 06:43

    Published by: Luiz_Araujo on 25/07/2012 06:45

    Hello Luiz

    Use under query on the source tab.

    SELECT STRPARAM MESSAGEDATA< %="odiRef.getSchemaName" ("ls_oracle_odi_wrk",="" "d")="" %="" >.="">

    Then use the target tab

    String OracleMessageData = "#STRPARAM";

    If it does not try to put colon.

    String OracleMessageData = ": STRPARAM «;»»

    Thank you.

  • InternetAddress misunderstanding

    Hello

    I'm trying to set the name of the person when instantiating an object InternetAddress (new InternetAddress (Object sender, 'My Name')) in a class of mail to java, but it seems to be ignored. When I validated this class I just get the default username in the 'From' line of the customer email not 'my name', but I can substitute this in Outlook clues would be appreciated. Here is the code for the class (with some obvious changes)
    package uk.ac.package.utils;
    
    /**
     *
     * @author Tony Attwood
     */
    import java.io.UnsupportedEncodingException;
    import java.security.Security;
    import java.util.Properties;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class SendMail {
    
        public synchronized void sendMail(String subject, String body, String recipients, String bcc) throws MessagingException {
    
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    
            String sender = "[email protected]";
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", "smtp.server.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.from", sender);
            props.put("mail.debug","true");
            props.setProperty("mail.smtp.quitwait", "false");
    
            Session session = Session.getDefaultInstance(props,
                    new javax.mail.Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication("username", "password");
                        }
                    });
    
            MimeMessage message = new MimeMessage(session);
            try {
                message.setSender(new InternetAddress(sender, "My Name"));
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            message.setSubject(subject);
            message.setContent(body, "text/plain");
            if (recipients.indexOf(',') > 0) {
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
                if(bcc != null) {
                    if(bcc.indexOf(",")>0) {
                        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
                    } else {
                        message.setRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
                    }
                }
            } else {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
                if(bcc != null) {
                    if(bcc.indexOf(",")>0) {
                        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
                    } else {
                        message.setRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
                    }
                }
            }
    
            Transport.send(message);
    
        }
    
        public static void main(String args[]) throws Exception {
            SendMail mailutils = new SendMail();
            mailutils.sendMail("test "+Math.random(), "test which is in the body", "[email protected]", null);
        }
    }

    Use setFrom.

  • Failed to get file name of attachment on a part (with non ascii characters)

    Hello, all, and good year :)

    My problem is with non-ascii file name in attachments... Yes, I read the FAQ: http://www.oracle.com/technetwork/java/faq-135477.html#encodefilename

    I can't get the file name of the part of the body for this kind of attachments

    Here is my unit test:

    /**
    * contains different parts of various mailer coded in different ways...
    *
    */
    Private enum EncodedFileNamePart {}
    OUTLOOK ("Content-Type: text/plain;") \n name =------"=?" ISO-8859-1? ' Q? this estd = E9j = E0no = E7ac = EBl'estcool.txt? =-"\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; \n filename =------"=? ISO-8859-1? Q? it estd = E9j = E0no = E7ac = EBl'estcool.txt? =-"\n\nnoel 2010\n", "it estdejanoelcac'estcool.txt" ').

    GMAIL ("Content-Type: text/plain;") charset = US-ASCII; name =------=? " ISO-8859-1? B? ZOlq4G5v62znYWNlc3Rjb29sLnR4dA is? =-"\nContent-Disposition: attachment;" filename =------=? " ISO-8859-1? B? ZOlq4G5v62znYWNlc3Rjb29sLnR4dA is? =-"' \nContent-Transfer-Encoding: base64\nX-attachment-Id: f_giityr5r0\n\namluz2xligjlbgxziqo=\n","dejanoelcacestcool.txt"), "

    THUNDERBIRD ("Content-Type: text/plain;") \n name =------"=?" ISO-8859-1? Q? d = E9j = E0no = E7acestcool = 2Etxt = EBl? =-"\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment;" "\n filename*0*=ISO-8859-1''%64%E9%6A%E0%6E%6F%EB%6C%E7%61%63%65%73%74%63%6F;\n filename*1*=%6F%6C%2E%74%78%74\n\njingle bells! \n","dejanoelcacestcool.txt"), "

    EVOLUTION ("Content-Disposition: attachment;") the file name * = ISO-8859-1 "d%E9j%E0no%EBl.txt\nContent-Type: text/plain; name * = ISO-8859-1 "d%E9j%E0no%EBl.txt; "charset =------'UTF - 8\' \nContent-Transfer-Encoding: 7bit\n\njingle bells\n","dejanoel.txt"), "

    ;

    String content = null;
    The string target = null;
    Private EncodedFileNamePart (string target, string content) {}
    This.Content = content;
    This.Target = target;
    }

    part public get() {}
    try {}
    ByteArrayInputStream bis = new ByteArrayInputStream (this.content.getBytes ());
    Part part = new MimeBodyPart (bis);
    bis. Close();
    return the part;
    }
    {} catch (Throwable e)
    Returns a null value.
    }
    }

    public String getTarget() {}
    Return this.target;
    }
    }

    @Test
    Public Sub testJavamailDecode() throws MessagingException, UnsupportedEncodingException {}

    System.setProperty ("mail.mime.encodefilename", "true");
    System.setProperty ("mail.mime.decodefilename", "true");

    for (EncodedFileNamePart party: EncodedFileNamePart.values ())
    assertEquals (part.name (), MimeUtility.decodeText (part.get () .getFileName (), part.getTarget ());

    }


    I take a NullPointerExcepion in the decodeText because getFileName() returns a null value in the case of EVOLUTION and works well with OUTLOOK, THUNDERBIRD and GMAIL.

    Content type of evolution is ' Content-Disposition: attachment; " the file name * = ISO-8859-1 'd%E9j%E0no%EBl.txt' which does not resemble the other (it looks like the RFC 2616 or RFC5987 to do this.)

    How can I handle this situation except by writing my own decoder?

    Thanks for your replies!

    Published by: user13619058 on 4 Jan. 2011 07:44

    Set the system property "mail.mime.decodeparameters" "true" to enable support of RFC 2231.
    See the javadocs of the package javax.mail.internet for the list of properties.

    Yes, the FAQ entry should contain details as well.

Maybe you are looking for