Modifying a large string

I have a For Loop that reads and modifies a 40 meg file. The file is a log of GPS and CAN messages. The Labview App will modify the data of one certain message type. This all works but it takes 4 and a half minutes to complete. Is there a faster way to do this other than creating a DLL? Is it due to Labview creating a new string every time the string's modified with the Replace Substring Function?
Thank You
Attachments:
Labview VIs.zip ‏42 KB

Ah, I see what you are trying to do now.  You are taking the read distance, recomputing the distance, and replacing the same data in the file.
One of your biggest issues is that you are forking your wires a lot.  And that is a potential data copy.  And if you are copying large data, that takes a long time.  Instead, you should be trying to do as much in series as possible.  I changed your subVIs to use Scan From String and Format Into String instead of trying to increment value to read and convert to number multiple times.  This also allows you to build up the string to replace and do a single replacement.
It might be worth trying Raven's suggestion of reading a single line at a time.  You might also want to look into the Producer/Consumer architecture to put the writing to the new file in parallel with your processing of the file.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines
Attachments:
DistanceFix.zip ‏19 KB

Similar Messages

  • Need help on breaking a large string into substringsto fit in a line

    hii,suppose i have i have large string (the content of which is not apparently visible to me)which i want to show in a text area ,,,now how can i break it into multiple lines to be able view the total string...
    i dont want to use horizantal scrollbar...
    here i submit a sample code..and pls show me the neccesary modifications...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class textarea extends JFrame
    textarea()
    super("Text area length test");
    setSize(640,480);
    Container contentpane=getContentPane();
    JTextArea area=new JTextArea("Split panes allow the user to dynamically change the size of two or more components displayed side-by-side (within a window or another panel). Special dividers can be dragged with the mouse to increase space for one component and decrease the display space for another. Note that the total display area does not change. This gives applications a more modern and sophisticated view. A familiar example is the combination of a tree and a table separated by a horizontal divider (e.g. file explorer-like applications). The Swing framework for split panes consists only of JSplitPane.");
    area.setLayout(new BorderLayout());
    contentpane.add(area);
    setVisible(true);
    class texttest
    public static void main(String args[])
    new textarea();
    In the original code the Stron to be printed is not visible to me...

    Configure the text area so that it uses word wrap (see the javadoc)
    Kaj

  • Large string array in 6.1 is extremely slow

    Good day all,
    While this is in to tech support at NI, I wanted to see if anyone else has encountered it.
    I am upgrading from 6.0.2 to 6.1. Several large (2500 rows by 250 columns or larger) string arrays are used as inputs into subvi's. Under 6.0.2, these functions run in tenths of seconds, while under the converted 6.1 vi's they run in 20 seconds or more!
    Tracing back using probes, the problem is occurring at the point of the input. It is appears that the array is taking many seconds to copy from the input to the wire on the diagram.
    Array controls generated in 6.1 (not converted from 6.0.2) seem to function just fine. Using a save with options... to convert back to 6.0.2, the vi's again function in tenths of
    seconds.
    Anyone have any ideas?
    Thanks!

    I hear what you're saying about legacy code...
    Something you might want to be looking at for the future is migrating to a structure where the data is stored in a 1D array, where each element is a cluster contain the data that's now in a single row. This would be the most straight-forward change, but could make getting at the data tricky, depending on how you need to be able to search it.
    Alternately, you could have a cluster containing arrays of each of the row values.In this structure element 0 of all the arrays is the first "row", element 1 of the arrays is the second "row" and so on. This structure at first blush looks more complicated, but it's really not, plus it would allow you to use any value (or combination of
    values) to search for a specific row without a lot of parsing.
    If the data that is in the example VIs you posted is typical, either of these changes would be advantagous because it looks like there is a lot of reptative data that might be able to be encoded in an enum. Plus storing numbers as numbers often reduces the memory required and produces a predictable memory footprint (an I32 will always take-up 4 bytes per value regardless of how large of small the number is). My sense is that the variability of the string size is what's killing you.
    One thing that would make this sort of dramatic change somewhat easier is that because you are changing the basic datatype of the interface, you aren't going to have to worry about finding all the places the change will effect--the wires will be broken.
    If you ever decide to take this on, give a hollar.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Passing a large string in URL

    Hi
    The scenario is as follows
    There are two servers A and B on different locations. From Server A i want to send a request to a url on server B. The request contains a string parameter of very large value (more than 255 characters). The problem is that I cant use a get because of the restriction.
    How can I do the above in a jsp page. The string is generated dynamically when the user clicks on a link and also contains special characters like (+%)
    I know i need to encode the url. But how do i post to a url on a different server
    It would be nice if i can get the complete code. Short of time and cant read much thrugh the docs :)
    Thanks
    Sairam

    That depends, what type of field are you inserting the string into? What you need to do is check the size of the field and the length of the string. If the length exceeds the field size, then you either need to increase the field size or, if you know you will be generally inserting very large strings, change the field to a clob. Hope this helps.

  • Newbie question: Binding very large strings ( 4k) to OLAP query

    Hi there guys
    I am using Oracle 10.2 and I am trying to bind string variables to olap literals in my query string:
    SELECT TRUNC(IND-TO_DATE('01011900','ddmmyyyy')+2),VAL1
                   FROM (
                        SELECT *
                        FROM TABLE(
                             OLAP_TABLE(
                                  'OLAPFAME.MAG_CRD DURATION SESSION',
                                  :1 ))
                             MODEL
                                  DIMENSION BY(IND)
                                  MEASURES(VAL1,R2C1)
                                  RULES UPDATE SEQUENTIAL ORDER())
                   WHERE OLAP_CONDITION( R2C1, :2, 1 )=1
    I try and setString() to params 1 and 2, but it doesnt seem to work. The reason I am trying this is because when I pass large (>4K) DML string literals inline, I get ORA-01704. Hence me trying to bind to the variables via prepared statements (not even sure if this will get me past this 4k problem)!
    I have also read that I can store these large strings in variables and use those as a OLAP DML string via the ampersand syntax (not sure how to do this, ensuring that they would just have statement scope).
    Sorry if this is obtuse, but I'm at my wits end after a long days "trying stuff" :(
    Thanks in advance
    Adam

    Once again, I answer my own question. -_-;;
    The second process (fetch_comments) seems to be unnecessary. The Automated Row Fetch seems to be able to handle the 32K by itself. I'm still curious why the second process didn't work though....

  • To count number of occurances of a char in a very large string

    Hi All,
    I like to count the no of occurances of a char in a a very large string.
    for example
    char ch - 'c'
    string str - "practical example is always needed"
    c occured 2 times in the above string.
    Thanks,
    J.Kathir

    > string str - "practical example is always needed"
    Try to finish this:
            String str = "practical example is always needed";
            char search = 'c';
            int occurrence = 0;
            for(int i = 0; i < str.length(); i++) {
                // Use a method from the String-class to get a
                // char from a specific location in the String.
                // See: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
            System.out.println("Occerrence of char "+search+" in \""+str+"\" is: "+occurrence);

  • Very Large String

    I have a String that is suppose to hold info of about 200 MB, but when the string grows my program crashes giving a OutOfMemory Exception.
    Is there some JVM configuration that will help me solve this problem?
    Or will shifting to Java5.0 help solve this sort of problems.
    I understand that I have 128MB RAM which is lesser than 200MB what my program demands but I dont expect it to crash.

    I have a one-gallon tank of water, which is less than
    the five gallons I want to fill into it, but I don't expect it to overflowI very well understand what I am asking for.... I
    expect my system (program) to become slow because I
    guess we all know what Virtual memory stands for?Yes, very slow memory. o_O
    I dont expect the JVM to be decision maker of when to
    stop my application.It isn't.
    You did not tell the JVM to allocate enough heap to hold objects that large.
    You are free to configure your system with a large swap area
    and tell the JVM to allocate a large heap.
    Not sure if that will succeed though
    (AFAIK the JVM requests a contiguous memory block for the heap - your success might depend on your OS).
    Note, if you are building a large String, you should probably be using the StringBuffer class.
    If your largest object is expected to be in the order of 200MB in size, you'll probably need a heap size in the order of half a gig.
    Or will shifting to Java5.0 help solve this sort of problems.No, Java 1.5 will not alleviate your resource / configuration difficulties.

  • Large string into the VARCHAR2 field parsing problem

    Guys,
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE 10.2.0.4.0 Production
    TNS for Solaris: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    My problem is: The frontend of the application sends a large string into the VARCHAR2 (4000 BYTES) field.
    The string it sends is somewhat like the samples given below. I need to parse and put them in the tables
    as shown below. Please let me know, if you have any questions. -
    Crit: Some text1.
    Proficient (points 2): Some more text1.
    Comment1...........................................
    ..Comment1
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Table 1
    Crit          points          comment        morecomment
    Some text1.     2           Some more text1. Comment1.............................Comment1
    Some text2.     0           Some more text2.
    Some text3.     3           Some more text3.
    Some text4.     3           Some more text4.
    Table 2
    Overall Comment
    Crit: Some text1.
    Proficient (points 2): Some more text1.
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Overall comments:
    Blah2 Blah2 Blah2!
    Some more blah2 blah2 blah2.
    Table 1
    Crit          points          comment        morecomment
    Some text1.     2           Some more text1.
    Some text2.     0           Some more text2.
    Some text3.     3           Some more text3.
    Some text4.     3           Some more text4.
    Table 2
    Overall Comment
    Blah2 Blah2 Blah2!
    Some more blah2 blah2 blah2.
    Crit: Some text1.
    Proficient (points 2): Some more text1.
    Comment1...........................................
    ..Comment1.
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Comment2...............................Comment2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Overall comments:
    Blah1 Blah1 Blah1!Some more blah1 blah1 blah1.
    Table 1
    Crit          points          comment        morecomment
    Some text1.     2           Some more text1. Comment1.............................Comment1
    Some text2.     0           Some more text2. Comment2...............................Comment2.
    Some text3.     3           Some more text3.
    Some text4.     3           Some more text4.
    Table 2
    Overall Comment
    Blah1 Blah1 Blah1!Some more blah1 blah1 blah1.--------------------------------------------------------------------
    My code which doesn't work
    WITH t AS
    (SELECT 'Crit: Some text1.
    Proficient (points 2): Some more text1.
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.
    Overall comments:
    Blah2 Blah2 Blah2!
    Some more blah2 blah2 blah2.' string
    FROM   dual)
    SELECT SUBSTR(REGEXP_SUBSTR(string,'Crit: +$', 1, level), 12) "Crit",
           SUBSTR(REGEXP_SUBSTR(string,'points [^\)]+', 1, level), 8) "points",
           SUBSTR(REGEXP_SUBSTR(string,'\):^[[:alnum:]]+$', 1, level), 3) "comment",
           SUBSTR(REGEXP_SUBSTR(string,'^[[:alnum:]]+$', 1, level), 1) "morecomment"
    FROM   t
    CONNECT BY LEVEL <= (LENGTH(string) - LENGTH(REPLACE(string, 'Crit:')))/5
    WITH t AS
    (SELECT 'Crit: Some text1.
    Proficient (points 2): Some more text1.
    Comment1...........................................
    ..Comment1
    Crit: Some text2.
    Non-performance (points 0): Some more text2.
    Crit: Some text3.
    Distinguished (points 3): Some more text3.
    Crit: Some text4.
    Distinguished (points 3): Some more text4.' string
    FROM   dual)
    SELECT SUBSTR(string, INSTR(string, 'Overall comments:', -1) + 18) "overall_comment"
    FROM   t
    CONNECT BY LEVEL <= (LENGTH(string) - LENGTH(REPLACE(string, 'Crit:')))/5Edited by: abyss on Sep 17, 2010 12:26 PM

    Hi,
    Except for the morecomment column, you almost had it.
    Oracle documentation often refers to ^ and $ as meaning beginnig- and end-of-line, but they seem to mean beginning- and end-of-string.
    Aside from that , I just changed a few details (like ' +' to '.+').
    SELECT SUBSTR (REGEXP_SUBSTR (string, 'Crit:.+',          1, level), 6, 18)     AS Crit,
           SUBSTR (REGEXP_SUBSTR (string, 'points [^\)]+',           1, level), 8    )     AS points,
           SUBSTR (REGEXP_SUBSTR (string, '\):[ [:alnum:]]+',      1, level), 3     )     AS cmnt,
           REGEXP_REPLACE ( SUBSTR ( REGEXP_SUBSTR ( string || CHR(10) ||'Crit:'
                                                         , '.*?Crit:'
                                          , 1
                                          , LEVEL + 1
                                          , 'n'          -- . matches newline
                              , LENGTH ( REGEXP_SUBSTR ( string
                                                                , 'Crit:.*'
                                               , 1
                                               , LEVEL
                                      ) +
                              LENGTH ( REGEXP_SUBSTR ( string
                                                , 1
                                                , LEVEL
                                      ) - 2
                    , 'Crit:$'
                       ) more_cmnt
    FROM   t
    CONNECT BY LEVEL <= (LENGTH(string) - LENGTH(REPLACE(string, 'Crit:')))/5
    ; This gets the results you requested from the data you posted. I don't know if it gets those results for the right reasons or not, since you didn't post any reasons for why you want those results. Always explain why you want the results you do, giving specific examples from the sample data.
    The morecomment (called more_cmnt above) is much more complicated, since it involves scanning across multiple lines. I wouldn't be surprised if there is a simpler way than what I posted above.
    I do not recommend doing this in pure SQL. I suggest a PL/SQL function, because debugging and maintenance would be so much easier.
    To populate table2:
    WITH     got_pos         AS
         SELECT     string
         ,     INSTR (string, 'Overall comments:', -1)     AS pos
         FROM     t
    SELECT  SUBSTR ( string
                , pos + 18
                )     AS overall_comment
    FROM    got_pos
    WHERE     pos     > 0
    ;

  • Large String in ALV Cell

    Hi,
    what is the best way to get a large string into an ALV Grid cell?
    Any help is greatly appreciated.
    / Elvez

    Hi,
    I suggest that you place a button on the column, and when clicked show a TEXT editor (CL_GUI_TEXTEDIT) in a DOCKING container with the text that you want.
    Even if you use the full length of 255 for a column, for the user to see other columns, he has to scroll left / right.
    Regards,
    Ravi
    Note : Please mark the helpful answers

  • Send large string between servlets in different domain

    Hi,
    I need to send a large string from servlet in an web application to a
    servlet in another web application. Those two application are in
    different domains. I can't send the string as request parameter,
    bacause string is too large. I can't send as request attribute either,
    because attribute will lost during redirect to another domain.
    Any solutions? Thanks for any help.

    do set/getAttribute at the ServletContext level which is unique for a particular webapplication. from 1st application u can access the 2nd one using , getServletConfig().getServletContext().getContext("/uripath") which gives you the ServletContext handle of the other application and you can do getAttribute of this.
    Rgds
    Padmanava

  • Reading large large string from database

    I am reading is a large string value. It's data type in Oracle is CLOB. I was originally casting it to vARCHAR2(4000) in the select statement, but just realized the data can be larger than 4000. I took out the cast and have tried changing to several data types, but they all error out. How can I read in string data greater than 4000 characters?

    You must use Java to do this, the Execute Script operation makes it simple. I have put together a little process to demonstrate, and I can paste the Java from the Execute Script step below.
    It's all in the data-typing. In the sample I built, the BigString and NewBigString process variables are of LiveCycle type "string" with unlimited size. These become CLOBs in the database. When read as a CLOB object using JDBC, converted to Java Strings, they then can be loaded into the LiveCycle Process data and the API handles the rest.
    Let me know if I'm not clear enough with my explanation.
    Jeff A Yates
    http://www.avoka.com
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import javax.sql.DataSource;
    import javax.naming.InitialContext;
    int processId = patExecContext.getProcessDataIntValue("/process_data/@id");
    InitialContext context = new InitialContext();
    Connection connection = ((DataSource)context.lookup("java:/IDP_DS")).getConnection();
    String queryQuery = "select bigdocument, bigstring from tb_pt_workwithxlobs where process_instance_id = ?";
    PreparedStatement queryStatement = connection.prepareStatement(queryQuery);
    try {
    queryStatement.setInt(1, processId);
    ResultSet results = queryStatement.executeQuery();
    results.next();
    java.sql.Blob documentBlob = results.getBlob(1);
    com.adobe.idp.Document document = new com.adobe.idp.Document(documentBlob.getBinaryStream());
    patExecContext.setProcessDataValue("/process_data/@NewBigDocument", document);
    java.sql.Clob stringClob = results.getClob(2);
    patExecContext.setProcessDataValue("/process_data/@NewBigString", stringClob.getSubString(1L, (int)stringClob.length()));
    } catch(Exception ex) {
    ex.printStackTrace();
    queryStatement.close();
    connection.close();

  • Error returning large String arrays from web service

    Hi,
    I currently have an EJB that returns a String[] array that I have implemented as
    a Web Service. When I execute a Java client (JSP) from Weblogic, I don't have a problem
    as long as the returned array is relatively small, but when the array starts to get
    a little larger (say 20 elements, about 30 chars each), I consistently get:
    SAXException: java.lang.IllegalArgumentException:array element type mismatch.
    Strangely enough, when my web service client is a .asp page running under MS IIS
    (using the MS SOAP Toolkit), it works fine. I have returned as many as 15000 - 20000
    array elements in one call. And since I am calling the same Weblogic EJB with the
    MS client, I know it's a problem with the Java client, not the EJB.
    Anybody know of a bug or had this experience before? Or know what I might be doing
    wrong? FYI, I am using Weblogic 6.1 SP2.
    Thanks,
    Steve

    Hi Steve,
    Sure we're interested...I'll pass this along to the XML folks.
    Thanks for the feedback,
    Bruce
    Steve Alexander wrote:
    In case anyone is interested, I solved my problem. I was mis-diagnosing the problem
    - thinking it was a size issue when it actually was a data issue. On the calls where
    I was returning a large array, some of the array members were null. When I made them
    enpty strings "", it worked. Apparently the default SAX parser BEA uses doesn't like
    the nulls, whereas the MS parser doesn't care.
    "Steve Alexander" <[email protected]> wrote:
    Thanks Bruce,
    FYI - I have reproduced the problem on WL7.0. I have turned it in to support
    as you
    suggested.
    Steve
    Bruce Stephens <[email protected]> wrote:
    Hi Steve,
    This does not ring any bells, however I would suggest that you file a support
    case. If it
    is an option you might try a later release (7.0).
    Bruce
    Steve Alexander wrote:
    Hi,
    I currently have an EJB that returns a String[] array that I have implementedas
    a Web Service. When I execute a Java client (JSP) from Weblogic, I don'thave a problem
    as long as the returned array is relatively small, but when the arraystarts to get
    a little larger (say 20 elements, about 30 chars each), I consistentlyget:
    SAXException: java.lang.IllegalArgumentException:array element type mismatch.
    Strangely enough, when my web service client is a .asp page running underMS IIS
    (using the MS SOAP Toolkit), it works fine. I have returned as many as15000 - 20000
    array elements in one call. And since I am calling the same Weblogic
    EJB
    with the
    MS client, I know it's a problem with the Java client, not the EJB.
    Anybody know of a bug or had this experience before? Or know what I mightbe doing
    wrong? FYI, I am using Weblogic 6.1 SP2.
    Thanks,
    Steve

  • The most efficient way to search a large String

    Hi All,
    2 Quick Questions
    QUESTION 1:
    I have about 50 String keywords -- I would like to use to search a big String object (between 300-3000 characters)
    Is the most efficient way to search it for my keywords like this ?
    if(myBigString.indexOf("string1")!=1 || myBigString.indexOf("string2")!=1 || myBigString.indexOf("string1")!=1 and so on for 50 strings.)
    System.out.println("it was found");
    QUESTION 2:
    Can someone help me out with a regular expression search of phone number in the format NNN-NNN-NNNN
    I would like it to return all instances of that pattern found on the page .
    I have done regular expressions, in javascript in vbscript but I have never done regular expressions in java.
    Thanks

    Answer 2:
    If you have the option of using Java 1.4, have a look at the new regular expressions library... whose package name I forget :-/ There have been articles published on it, both at JavaWorld and IBM's developerWorks.
    If you can't use Java 1.4, have a look at the jakarta regular expression projects, of which I think there are two (ORO and Perl-like, off the top of my head)
    http://jakarta.apache.org/
    Answer 1:
    If you have n search terms, and are searching through a string of length l (the haystack, as in looking for a needle in a haystack), then searching for each term in turn will take time O(n*l). In particular, it will take longer the more terms you add (in a linear fashion, assuming the haystack stays the same length)
    If this is sufficient, then do it! The simplest solution is (almost) always the easiest to maintain.
    An alternative is to create a finite state machine that defines the search terms (Or multiple parallel finite state machines would probably be easier). You can then loop over the haystack string a single time to find every search term at once. Such an algorithm will take O(n*k) time to construct the finite state information (given an average search term length of k), and then O(l) for the search. For a large number of search terms, or a very large search string, this method will be faster than the naive method.
    One example of a state-search for strings is the Boyer-Moore algorithm.
    http://www-igm.univ-mlv.fr/~lecroq/string/tunedbm.html
    Regards, and have fun,
    -Troy

  • Format large string for mysql

    I am reading a large txt file that contains sigle quotes and double quotes... I want to format the string and send it to a blob cell in mysql. I need to add an escaoe character before single quotes and double quotes. Any suggestions?

    john joe wrote:
    I am reading a large txt file that contains sigle quotes and double quotes... I want to format the string and send it to a blob cell in mysql. I need to add an escaoe character before single quotes and double quotes. Any suggestions?
    Yes!  Use "Search and Replace String" with "replace all?" = True.  Replace "'" with "\'" and replace """ with "\"".
    Cheers.
    Message Edited by tbd on 02-12-2007 11:06 PM
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • Cipher - encrypt large String variable

    Hello,
    I have a jUnit test for a simple Cipher encryption/decryption.
    I want to write a test to encrypt large data.
    Do I have to change the encryption variable type from String to a Stream class?
    Anyone have suggestion?
    package no.ssb.cipher;
    import org.junit.*;
    import static org.junit.Assert.*;
    * Unit test for simple App.
    public class SimpleStringCipherTest {
    private SimpleStringCipher simpleStringCipher;
    * Create the test case
    * @param testName name of the test case
    @Before
    public void setUp()
    simpleStringCipher = new SimpleStringCipher("tvnw63ufg9gh5392");
    @Test
    public void testBasicEncyption() throws Exception {         
    String plainText = "2010 starts new decade.";
    String encrypted = simpleStringCipher.encrypt(plainText);
    System.out.println("Encrypted: " + encrypted);
    assertTrue(!plainText.equals(encrypted));
    String decrypted = simpleStringCipher.decrypt(encrypted);
    assertEquals(plainText, decrypted);
    @Test
    public void testEncryptionIsNotURLSafe() throws Exception{
    String plainText = "2010 starts new decade.";
    String expectedValue = "abe6vPUFQ4xSMezuFF2HBNC3dW98iifMeM027PKKnNw=";
    String encrypted = simpleStringCipher.encrypt(plainText);
    assertTrue(!plainText.equals(encrypted));
    assertTrue(expectedValue.equals(encrypted));
    String decrypted = simpleStringCipher.decrypt(encrypted);
    assertEquals(plainText, decrypted);
    @Test(expected=IllegalArgumentException.class)
    public void testInvalidSecretKey() throws Exception{
    SimpleStringCipher invalidCipher = new SimpleStringCipher("tull");
    @Test(expected=Exception.class)
    public void testDecryptInvalidEncryptedString() throws Exception {
    simpleStringCipher.decrypt("abe6vPUFQ4xSMezuFF2HBNC3dW98jjfMeM027PKKnNw");
    }

    Sorry, I am beginner and new in Cipher.
    Hope my following question make more sense.
    In production we have an error when decrypting
    large data.
    My existing unit test is shown and class I am testing
    How can I write a new test, simulating the production error we have?
    1.@Test
    2.public void testBasicEncyption() throws Exception {
    3.String plainText = "text to be encrypted."
    4.String encrypted = simpleStringCipher.encrypt(plainText);
    5.System.out.println("Encrypted: " + encrypted);
    6.assertTrue(!plainText.equals(encrypted));
    7.String decrypted = simpleStringCipher.decrypt(encrypted);
    8.assertEquals(plainText, decrypted);
    * Class to test *
    package no.ssb.cipher;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;
    public class SimpleStringCipher {
    private static byte[] linebreak = {}; // Remove Base64 encoder default
    // linebreak
    private String secret; // secret key length must
    // be 16
    private SecretKey key;
    private Cipher cipher;
    private Base64 coder;
    public SimpleStringCipher(String secretKey) {
    if(secretKey.length()!=16){
    throw new IllegalArgumentException("secretKey must be 16 digits");
    this.secret = secretKey;
    try {
    key = new SecretKeySpec(secretKey.getBytes(), "AES");
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    coder = new Base64(32, linebreak, false);
    } catch (Throwable t) {
    t.printStackTrace();
    public synchronized String encrypt(String plainText)
    throws Exception {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(plainText.getBytes());
    return new String(coder.encode(cipherText));
    public synchronized String decrypt(String codedText)
    throws Exception {
    byte[] encypted = coder.decode(codedText.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encypted);
    return new String(decrypted);
    Edited by: 999969 on Apr 14, 2013 10:38 PM

Maybe you are looking for

  • Create PDF's in an older Version

    Dear Sir or Madam, our company works with an interface for PDF forms. The fields of a form are automatically recognized. For option fields are the possible element values selectable. That works fine with forms made with the Distiller 7.0. Newly we bo

  • Drill Down  In classical report

    Hi i had done a classical report ,but now user wants in in drill down , My output now is Planned Downtime IDLE MACHINE TIME (DUE TO) 25.50 47.60 % PREVENTATIVE MAINTENANCE 88.50 0.32 % HOLIDAYS 288 1.05 % Unplanned Downtime 0.00 0.00 % SHIFT START-UP

  • Mac pro and viewsonic vp930b lcd display

    mac pro and viewsonic vp930b lcd display i have two monitors set up, a viewsonic vp191b and a vp930b lcd, connected via both dvi ports on the mac pro. the vp930b when the computer goes to sleep cycles on and off with the input message. if i put the m

  • List of modules

    Is there anywhere that I can find a list of the modules (and their C source name) for a plain vanilla install of Tiger server? I copied a plist from a Panther server over to Tiger. It was only when the Web server fell over, and the logs complained ab

  • Adobe flash 10.3 hangs firefox on closing....is there an alt flash i can install that will work with firefox?

    since updating my adobe flash to 10.3 it hangs firefox from closing and no matter how i search cant find a download for the previos adobe flash i had that was workn