Line wrap in JTextPane

I didn't see a setLineWrap(boolean) method in JTextPane (as you can tell from my previous posts I'm having trouble going from a JTextArea to a text component that can format text). How would I force it to line wrap like a JTextArea would if you called
tp.setLineWrap(true);
tp.setWrapStyleWord(true); ?
I've set the JTextPane in a JScrollPane, so I'm worried it will not wrap.
thanks for the info.

I just finished some testing and it seems the the line wrapping is set to the way I wanted by default, ie by just like I had called the above methods on a JTextField
thanks

Similar Messages

  • Custom line wrapping in JTextPane, StyledEditorKit

    Hello to everybody.
    I have a question. I've been stuck with this for several days now, and I couldn't find a solution on this forum or elswhere on the internet.
    I'm using a JTextPane, with a StyledEditorKit. I need to do line breaking on certain specific tokens. However, the ParagraphView which the StyledEditorKit uses only breaks on whitespaces. I've tried going into the java sources, but I can't figure out how to do it.
    Is there a simple way to change the delimiters it breaks on ? If not, is there any sample code I can use to figure out what classes/methods I need to overwrite?
    Thanks,
    Andrei

    Hello, I am having the same need of the problem posed here. I tried to use the code refered in the previous post, but (maybe my case is differente) if I am editing in the component (JTextPane) I start to have some odd behaviours, like this:
    1: After pressing Alt+Enter (my key mapping to insert a '\r') the caret remains in the same line, in order to have the caret in next line, I have to insert more characters
    2: After the first '\r', the other '\r' doesn't do the expected behavior, its as you haven't insert anything
    I'd be great if you could help me please!!!
    Thanx.

  • Problems with JTextPane line wrapping

    Hi to all.
    I'm using a code like this to make editable a figure that I paint with Java 2D. This JTextPane don't has a static size and for that, the text in it cannot be seen affected by the natural line wrap of the JTextPane component. The problem is that I have to set a maximun size for the JTextPane and I want to use the line wrap only when the width of the JTextPane be the maximun width. How can I do this?
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_RIGHT);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Dimension d = getPreferredSize();
                d.width += 10;
                setSize(d);
            public void removeUpdate(DocumentEvent e) {
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }Thanks for read.

    I'm working hard about that and I can't find the perfect implementation of this. This is exactly what I want to do:
    1. I have a Ellipse2D element painted into a JPanel.
    2. This ellipse is painted like a circle.
    3. Into the circle there's a text area, that user use to name the cicle.
    4. The text area is a JTextPane.
    5. When the user insert a text area, it can increase it size, but it can't be bigger than the circle that it contains.
    6. There is a maximun and a minimun size for the circle.
    7. When the user write into de JTextPane, it grows until arriving at the limit.
    8. When the JTextPane has the width size limit, if the user writes more text into it, the JTextPane write it into another line.
    9. The size of the JTextPane has to be the optimun size, it cannot have empty rows or empty lines.
    This code does all this except 9, cause if the user remove some text of the text area, the form of the JTextPane changes to a incorrect size.
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                //If it has the maximun width and the maximun height, the user cannot
                //write into the JTextPane
                /*AbstractDocument abstractDoc;
                if (doc instanceof AbstractDocument) {
                abstractDoc = (AbstractDocument) doc;
                abstractDoc.setDocumentFilter(new DocumentSizeFilter(this, 15));
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Runnable doRun = new Runnable() {
                    public void run() {
                        int MAX_WIDTH = 200;
                        Dimension size = getSize();
                        Dimension preferred = getPreferredSize();
                        if (size.width < MAX_WIDTH) {
                            size.width += 10;
                        } else {
                            size.height = preferred.height;
                        setSize(size);
                SwingUtilities.invokeLater(doRun);
            public void removeUpdate(DocumentEvent e) {
                this.setSize(this.getPreferredSize());
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }I know that the problem is into the removeUpdate method, but I have to set to the JTextPane, allways the optimun size, how can I do this?
    Thanks to all.
    Edited by: Daniel.GB on 06-jun-2008 18:32

  • Line wrapping - JTextPane

    Hi,
    Does anyone know how to disable line wrapping in a JTextPane?
    Thanks,
    Michael

    there 2 ways of achieving it.
    1. Instead of adding the editorpane to the JScrollPane, add the JEditorPane to a JPanel(BorderLayout->CENTER) and then the JPanel to the JScrollPane. Then you can avoid the said problem
    2. JEditorPane ta= new JEditorPane(){
    public boolean getScrollableTracksViewportWidth(){
    return false;
    use this to create ur JEditorpane.
    But the problem here is that your JEditorpane width is dynamic depending on ur text size.
    so when you add it to the JScrollPane you will not c it fitting exactly into the scrollpane width.
    hope it helps.

  • How to detect the line wrap event of JTextPane?

    Hi all,
    I'd like to detect the line wrapping event of JTextPane, so as to adjust the visible rows of JTextPane. How could I do this? Thanks!
    Yi Bing

    there is no wrap event.
    Wrap happens during relayout. The event which invokes relayout could be different. E.g. change size or chane model (document).
    Just add document listener and componnet listener.
    Regards,
    Stas

  • Force word wrap in JTextPane (using HTMLEditorKit)

    Hi!
    I have a JTextPane on a JScrollPane inside a JPanel. My text pane is using HTMLEditorKit.
    I set the scrolling policies of my JScrollPane to: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER.
    I did not find in JTextPane�s API any relevant property I can control word-wrapping with (similar to JTextArea�s setLineWrap) and I have tried a few things to force word-wrapping but nothing worked...
    What happens is my text is NOT being wrapped (even though there is no horizontal scrolling) and typed characters (it is an enabled editable text componenet) are being added to the same long line�
    I�d like to force word-wrapping (always) using the vertical scroll bar whenever the texts extends for more then one (wrapped) line.
    Any ideas?
    Thanks!!
    Message was edited by:
    io1

    Your suggestion of using the example only holds if it fits the requirements of the featureDid your questions state anywhere what your requirement was?
    You first questions said you had a problem, so I gave you a solution
    You next posting stated what your where currently doing, but it didn't say it was a requirement to do it that way. So again I suggested you change your code to match the working example.
    Finally on your third posting you state you have some server related issues causing the requirement which I did not know about in my first two postings.
    State your problem and special requirments up front so we don't waste time quessing.
    I've used code like this and it wraps fine:
    JTextPane textPane = new JTextPane();
    textPane.setContentType( "text/html" );
    HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
    HTMLDocument doc = (HTMLDocument)textPane.getDocument();
    textPane.setText( "<html><body>some long text ...</body></html>" );
    JScrollPane scrollPane = new JScrollPane( textPane );If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Center text in a text component with line wrapping

    I need to display dynamic text in a text component. I need line wrapping (on work boundaries) and also need horizontal and vertical center alignment.
    How do I do this? I saw a previous post on aligning text in a JTextArea that said to use a JTextPane but I don't see in JTextPane how to do word wrapping.
    Thanks,
    John

    //  File:          SystemInfoWindow.java.java
    //  Classes:     SystemInfoWindow
    //  Package:     utilities.msglib
    //  Purpose:     Implement the SystemInfoWindow class.
    //     Author:          JJB 
    //     Revision History:
    //     Date            By   Rel#  Description of change
    //     =============  ===  ====  ===============================================
    //     Jul 3, 2006   JJB  1.00  Original version
    //  Public Types / Classes          Type Description
    //  ========================     =============================================
    //     SystemInfoWindow
    package utilities.msglib;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    * TODO Enter description
    class SystemInfoWindow extends JDialog {
          * @param args
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        Test thisClass = new Test();
                        thisClass.setVisible(true);
                        SystemInfoWindow window = new SystemInfoWindow(thisClass);
                        window.setMessage("System shutdown in progress ... lot sof atatarte athis tis a sa logoint of tesxt it keeps going and going and going thsoreoiat afsjkjslakjs fshafhdskrjlkjsdfj");
                        window.setVisible(true);
         //     ------------------------  Inner Classes ---------------------
         static class Test extends JFrame {
              private JPanel jContentPane = null;
               * This is the default constructor
              public Test() {
                   super();
                   initialize();
               * This method initializes this
               * @return void
              private void initialize() {
                   this.setSize(300, 200);
                   this.setContentPane(getJContentPane());
                   this.setTitle("JFrame");
               * This method initializes jContentPane
               * @return javax.swing.JPanel
              private JPanel getJContentPane() {
                   if (jContentPane == null) {
                        jContentPane = new JPanel();
                        jContentPane.setLayout(new BorderLayout());
                   return jContentPane;
         //     ------------------------  Static Fields ---------------------
         private static final long serialVersionUID = -8602533190114692294L;
         //     ------------------------  Static Methods --------------------
         //     ------------------------  Public Fields ---------------------
         //     ------------------------  Non-Public Fields -----------------
         private JPanel jContentPane = null;
         private JTextPane textField = null;
         public SystemInfoWindow(JFrame frame) {
              super(frame);
              initialize();
              //setUndecorated(true);
              setLocationRelativeTo(frame);
              pack();
         //     ------------------------  Interface Implementations ---------
         //     ------------------------  Public Methods --------------------
         public void setMessage(String text){
              textField.setText(text);
              adjustSize();
         //     ------------------------  Non-Public Methods ----------------
         private void adjustSize(){
              Dimension oldSize = textField.getPreferredSize();
              textField.setPreferredSize(new Dimension(
                        oldSize.width, oldSize.height + 30));
              pack();
         //     ------------------------  Generated Code --------------------
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setModal(true);
              this.setContentPane(getJContentPane());
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowOpened(java.awt.event.WindowEvent e) {
                        //setLocationRelativeTo(MsgLibGlobals.parent);
                        pack();
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.setMaximumSize(new java.awt.Dimension(50,2147483647));
                   jContentPane.add(getTextField(), java.awt.BorderLayout.CENTER);
              return jContentPane;
          * This method initializes textField     
          * @return javax.swing.JTextPane     
         private JTextPane getTextField() {
              if (textField == null) {
                   textField = new JTextPane();
                   textField.setEditable(false);
                   textField.setMaximumSize(new java.awt.Dimension(20,2147483647));
              return textField;
    }Message was edited by:
    BaltimoreJohn

  • Line wrapping and font styles?

    Hi,
    If I have a piece of text which I would like to see line wrapped, and font styled, how should I do that?
    javax.swing.JTextArea has the capabilities to set line wrapping to on.
    javax.swing.JTextPane has the capabilities to set font styles like bold, italic and so on.
    But what if you have a piece of text you don't know the (possible) length of (so you would like to have line wrapping), AND to which you want to apply font styles to. JTextArea and JTextPane are siblings, not ancestors. So I can't use it. I have looked in the code to see if I could use pieces of code in my own program. But not luck.
    Do you have a suggestion for me?
    TIA,
    Abel

    camickr wrote:
    JTextPane wraps by default. I'm not sure what your problem is.I did not know that JTextPane did wrap. And I could not find it in the documentation.
    But thanks for the information!

  • Overide Line wrapping in JTextComponent

    Howdy !
    Anybody knows how can I achieve my own custom line wrap code for a JTextComponent/JTextPane. I see that these components use the white space as the bench mark to wrap a line. Now if I find and Replace a white space with say &n b s p; , how would I have the document of the JTextComponent identify it as the line break character. Parlay ! if I dont make any sense.
    Thanks Galore
    Dan

    Can BreakIterator be associated with a JTextPane for this. Somebody Please ?

  • How to prevent automatic line wrapping in a JEditorPane

    I have added a JEditorPane inside a JScrollPane which is inturn is added inside a JPanel with a GridLayout.
    While JEditorPane is loaded with an HTML page or a html file is read into it with an HTMLDocument the longer lines are geting wrapped automatically to the next line when the display area of the parent component of the JPanel where the original JScrollPane is held (like the JFrame or JSplitPane etc.)
    It doesn't help even after seeing a preferredsize/maximumSize or minimumSize
    of the JEditorPane (b'cos it defaults to some other size which i'ven't set at all).
    The horizontal scrollbar apperas only the when the the JEditorPanes size is reduced lesser than its defult size which has been set (probably by the layout manager).
    I want to get rid of this behaviour of the JEditorPane such that horizontal Scollbar should apper as soon as the user reduce the size of the window displaying the above component hierarchy (parent container->JScrollPane->JEditorPane) and no line wrapping occurs.
    Note : 1. JEditorPane doesn'y have linewrapping API like JTextArea
    2. Its default and automatic linewrapping behaviour is conforming
    with word line wrapping where lines are broken at the end of a
    word which can be fully accomodated.

    I have added a JEditorPane inside a JScrollPane which is inturn is added inside a JPanel with a GridLayout.
    While JEditorPane is loaded with an HTML page or a html file is read into it with an HTMLDocument the longer lines are geting wrapped automatically to the next line when the display area of the parent component of the JPanel where the original JScrollPane is held (like the JFrame or JSplitPane etc.)
    It doesn't help even after seeing a preferredsize/maximumSize or minimumSize
    of the JEditorPane (b'cos it defaults to some other size which i'ven't set at all).
    The horizontal scrollbar apperas only the when the the JEditorPanes size is reduced lesser than its defult size which has been set (probably by the layout manager).
    I want to get rid of this behaviour of the JEditorPane such that horizontal Scollbar should apper as soon as the user reduce the size of the window displaying the above component hierarchy (parent container->JScrollPane->JEditorPane) and no line wrapping occurs.
    Note : 1. JEditorPane doesn'y have linewrapping API like JTextArea
    2. Its default and automatic linewrapping behaviour is conforming
    with word line wrapping where lines are broken at the end of a
    word which can be fully accomodated.

  • Word Wrap in JTextPane

    I'm working with just a JTextPane, no JScrollPane around it or anything.
    I would like the JTextPane to use word wrap, but it looks like by default it does not. I looked through some API stuff and tutorials and found nothing on the subject.
    The code is trivial and pointless to post right now. All I dd was make a JTextPane via new JTextPane() (no arguments or anything) and type in it enough to see if it word wrapped and it didn't.
    Is there a way to enable word wrap on JTextPanes?

    no JScrollPane around it or anything.The scroll pane forces the wrapping because it enforces the width limit. Otherwise there is no limit.
    You can use setPreferredSize(...) to force the width, but then that also restricts the height.
    Reply 6 of this posting may give you some ideas.

  • How to add new line wrapping rule?

    Hi all,
    I have a question about line wrapping condition of Java editor of JDeveloper.
    JDev has some predefined rules for it and I can change them from preference.
    But can I add a new rule?
    I'd like to place conditional operators such as "&&" or "||" at head of line.
    For example, as below.
    if (values[0].length() > 2
    && values[1].length() == 3
    || values[2].length() < 10
    && values[3].length() == 0) {
    JDev doesn't seem to have the predefined rule about conditional operators.
    So I'd like to know if I can add new one.
    My Jdeveloper is 11.1.1.6.0.
    Thanks,
    Atsushi

    Atsushi,
    I don't think you can add a new rule there.
    However, how about setting Line Wrapping->Binary Operators and Assignments to Always? Your code would then look like
           if (values[0].length() >
                2 &&
                values [1].length() ==
                3 ||
                values [2].length() <
                10 &&
                values [3].length() ==
                0 ) {
            }-Arun

  • Line wrapping in Java??

    Hi,
    Can anyone tell me if there is a class to handle line wrapping in Java?
    I'm working on a Java Mail application that deals with fairly lengthy email message bodies. The problem is in the actual email, the message body appears in a lengthy horizontal single line which is rather inconvenient to read.
    I'd like to break the message body into convenient 80 character lines that takes word boundries into account so that there are no broken words at the end of a line.
    Thanks,
    Veena

    Well the easiest way would be to put line breaks when you want them.
    "\n" is the line break character.
    So String("aaaaa\naaaaa");
    Should appear as
    aaaaa
    aaaaa

  • HTML lines wrap around in the HTML report output

    I seem to have a problem with lines wrapping around in HTML format. If the report is ran using the report builder the output will fit in every line without wrapping the information.
    While if I run the same report -- to present the info using a browser -- using JSP in HTML format, the same lines will wrap around the info in two lines.
    Here is how I send this document to the server :
    pwrmpos_n: report=pwrmpos.rep destype=cache desformat=html server=rep60_wforms2 %*
    Any help will be appreciated

    Hello Hernando,
    I am a little confused, the command that you describe is only for paper layout...
    Anyway, let's try to help you:
    - on your paper layout you specified a width for each column (when you resize it in the Paper Design window). When you run the paper layout with HTML (ot HTMLCSS) as format the width is present in the <TD> tag.
    - for the JSP, by default the HTML does not contains any size for the table and cell so the browser size the table to fit in the screen.
    If you do not want any wrapping in the JSP just modify the HTML tags to specify a width, or wrap for the TD tag.
    Regards
    Tugdual

  • Creating Packages from BLOB field contents, line wrap problems

    Good afternoon,
    we use an in-house developed database-driven update system to update both our databases and filesystems, the system itself performs really well but there is still one problem I can't fix without some expert help:
    the code of to-be-updated Oracle packages is stored inside of a BLOB field, the BLOB field will contain both the package specification and package body and needs to be split into two parts to first execute the spec and then to execute the package body (I tried to execute both in a single step but this didn't work). This works for packages with less than 32767 characters and also works in some other cases but I found one case where the executed code contains an extra line wrap right in the middle of a word.
    To make it more clear (I hope it's comprehensible), imagine the following database content:
    CREATE OR REPLACE Package
    MyPack
    AS
    [... a lot procedure headers ...]
    END MyPack;
    CREATE OR REPLACE
    Package Body MyPack AS
    [... a lot more procedures ...]
    PROCEDURE myTest (intID OUT integer)
    AS
    BEGIN
      SELECT count (*) into intID FROM MyTa[--this is where the dbms_lob.substr() ends --]ble;
    END;
    END MyPack;My code searches for the second occurrence of the "Create or replace package", splits the code into spec and body, executes the specification and keeps on adding the rest of the code to a VARCHAR2A variable called "storedCode" from the BLOB. Now in the above example, after the specification has been removed from the string, the remaining characters (ending with the "MyTa" string) are added to the varchar2a variable, the next line is fetched from the BLOB via "dbms_lob.substr()" and added as long as dbms_lob.substr() does not return a NULL value (end of BLOB). When the code is executed after all has been fetched, the generated Package Body will contain an extra line wrap right in the middle of the "MyTable" word compiling the package invalid.
    This is the procedure code I use (definitely improvable, I'm better in MSSQL and MySQL dialects ...) to load, parse and execute the BLOB content:
       -- to run package code
      procedure runPackageCode (stepRef integer)
      AS
        numLines integer default 1;
        pos     integer default 1;
        storedCode    LOG_CHANGEDOBJECT.STOREDOBJECT%type;
        objectCursor  integer;
        lSqlOut     integer;
        sqlCommand  dbms_sql.varchar2a;
        emptyCommand dbms_sql.varchar2a;
        pIsError integer := 0;
        pErrorMsg varchar2(200) := '';
        updateRef integer := 0;
        currentUpdate integer := 0;
        schemaReference varchar2(20);
        -- required to do string cutting
        strLine varchar2(32767);
        strLeftFromSlash varchar2(32767);
        strRemaining varchar2(32767);
        intDelimiterPos integer := 0;
      begin
        -- retrieve update ID
        SELECT log_update_ref INTO currentUpdate FROM link_update_with_taskstep WHERE log_taskstep_ref = stepRef;
         begin
            select storedobject, change_area
            into storedCode, schemaReference
            from vw_storedobjects
            where step_id = stepRef;
         exception
          when no_data_found then
            pIsError := 1;
            pErrorMsg := 'Invalid SQL ID ' || stepRef;
            pkg_generic.LogError(updateRef, 'LocalUpdater', stepRef, 'Run package code failed: ' || pErrorMsg);
         end;
          if pIsError = 0 then     
            begin
              -- change schema
              execute immediate 'alter session set current_schema = ' || schemaReference;         
              objectCursor := dbms_sql.open_cursor;   
              loop
                strLine := UTL_RAW.CAST_TO_VARCHAR2(dbms_lob.substr(storedCode, 32767, pos));
                intDelimiterPos := regexp_instr(strLine, '\s*Create\s*or\s*Replace\s*Package', 2, 1, 0, 'i');
                while intDelimiterPos > 0
                loop
                  -- '/' found, execute currently stored statement
                  strLeftFromSlash := substr(strLine, 1, intDelimiterPos-1);
                  strLine := substr(strLine, intDelimiterPos);
                  -- execute the extracted part without any '/' in it
                  sqlCommand(numLines) := regexp_replace(strLeftFromSlash, '(^|\s+)/(\s+|$)', '', 1, 0, 'm');
                  if (sqlCommand(numLines) is not null) then
                    objectCursor := dbms_sql.open_cursor;   
                    dbms_sql.parse(objectCursor, sqlCommand, 1, numLines, true, dbms_sql.native);
                    lSqlOut := dbms_sql.execute(objectCursor);
                    dbms_sql.close_cursor(objectCursor);
                  end if;
                  -- reset sqlCommand
                  sqlCommand := emptyCommand;
                  -- reset line counter and store remaining string
                  numLines := 1;
                  -- check for further '/'s           
                  intDelimiterPos := regexp_instr(strLine, '\s*Create\s*or\s*Replace\s*Package', 2, 1, 0, 'i');
                end loop;
                -- add the remaining strLine to the sqlCommand
                strLine := regexp_replace(strLine, '(^|\s+)/(\s+|$)', '', 1, 0, 'm');
       --> I assume this line breaks the code, lpad()'ing the content to move it to the end of a varchar2a line didn't help
                sqlCommand(numLines) := strLine;
                exit when sqlCommand(numLines) is null;
                pos := pos+32767;
                numLines := numLines+1;
              end loop;
              objectCursor := dbms_sql.open_cursor;   
              dbms_sql.parse(objectCursor, sqlCommand, 1, numLines, true, dbms_sql.native);   
              lSqlOut := dbms_sql.execute(objectCursor);
              dbms_sql.close_cursor(objectCursor);
              commit;
              -- reset schema
              execute immediate 'alter session set current_schema = UPDATE_DB';
              -- set state to installed
              pkg_update.setstepstate(stepRef, 'Installed');
        exception
        when others then
              -- reset schema
              execute immediate 'alter session set current_schema = UPDATE_DB';
              -- set state to installFailed
              pkg_update.setstepstate(stepRef, 'InstallFailed');
              pkg_generic.LogError(updateRef, 'Database', stepRef, 'Run package code failed: ' || sqlerrm);
        end;
        end if;
      END;    Thanks if you kept on reading so far, I would really appreciate any feedback!
    Regards, Sascha

    Welcome to the forum!
    Whenever you post provide your 4 digit Oracle version (result of SELECT * FROM V$VERSION).
    Thanks for providing an easy-to-understand problem statement and for using code tags.
    >
    the code of to-be-updated Oracle packages is stored inside of a BLOB field
    >
    This should be stored in a CLOB since it is character data. Why are you using BLOB?
    >
    the BLOB field will contain both the package specification and package body and needs to be split into two parts to first execute the spec and then to execute the package body
    >
    Good, clear problem statement. So why doesn't your code do just what you said it should do: 1) split the code into two parts, 2) execute the spec and 3) execute the body.
    Instead of writing code that does these three relatively simple steps your code tries to combine splitting and executing and mushes/mashes it all together. The result, as you found, is code that is hard to understand, hard to debug, doesn't work and doesn't report on what it is doing.
    Code like this doesn't have a performance issue so the code should implement the simple step-by-step process that you so elegantly stated in your problem description:
    1. split the code into two parts
    2. execute the spec
    3. execute the body
    My advice is to refactor your code to perform the above steps in the proper order and to add proper exception handling and reporting for each step. Then when a step isn't working you will know exactly where and what the problem is.
    Here are my recommendations.
    1. Add two CLOB variables - one will hold the spec, the second will hold the body
    2. Add a comment (you have some good ones in the code now) for every step no matter how trivial it may be
    3. Add exception/error handling to EVERY STEP
    Your code for the first step has a comment but no exception handling. What should happen if you don't get any data? Why aren't you validating the data you get? Dynamic SQL using table-driven data is great, I love it, but you MUST validate that the data you get is what you expect to get.
        -- retrieve update ID
        SELECT log_update_ref INTO currentUpdate FROM link_update_with_taskstep WHERE log_taskstep_ref = stepRef;Recommended
        -- step 1 - retrieve update ID - This is the id that determines BLAH, BLAH, BLAH - add appropriate to tell a new developer what this ID is and what it means.
        BEGIN
            SELECT log_update_ref INTO currentUpdate FROM link_update_with_taskstep WHERE log_taskstep_ref = stepRef;
        EXCEPTION
            WHEN ??? THEN -- what should happen if step 1 fails? Do it here - don't default to an exception handler that is several pages away.
        END;Your code
         begin
            select storedobject, change_area
            into storedCode, schemaReference
            from vw_storedobjects
            where step_id = stepRef;
         exception
          when no_data_found then
            pIsError := 1;
            pErrorMsg := 'Invalid SQL ID ' || stepRef;
            pkg_generic.LogError(updateRef, 'LocalUpdater', stepRef, 'Run package code failed: ' || pErrorMsg);
         end;
    Good - except there is no comment that says what this does - I assume that the query above and this block are the 'retrieve update ID ' step?
    You log an error message and set the error flag to '1'. But since you don't want to continue why aren't you exiting the procedure and returning right here?
          if pIsError = 0 then     
            beginSo now you check the error flag and do several pages of code if there were no errors.
    I don't like that 'inverted' logic.
    If you don't want to continue then STOP right now! Don't make a developer scan through pages and pages of code to find out you really aren't doing anything else if there was an error.
    Either put a RETURN statement in the exception handler above or change your code to
          if pIsError = 1 then     
            RETURN;
          end if;Now the rest of the code doesn' t have to be indented; you will never get there if there is an error. Check for errors after every step and exit right then as appropriate.
              -- change schema
              execute immediate 'alter session set current_schema = ' || schemaReference;         
              objectCursor := dbms_sql.open_cursor;   
              loop
                strLine := UTL_RAW.CAST_TO_VARCHAR2(dbms_lob.substr(storedCode, 32767, pos));
                intDelimiterPos := regexp_instr(strLine, '\s*Create\s*or\s*Replace\s*Package', 2, 1, 0, 'i');
                while intDelimiterPos > 0
                loopThis code mixes all of the steps together into one giant mess. You open a cursor, try to split the BLOB into spec and body and try to parse and execute both all within a double nested loop.
    Even if that works correctly another developer will have a hard time understanding what the code is doing and fixing it if it goes wrong. And it will go wrong if you let me test if for you because I will put garbage into the BLOB for the spec, body or both to make sure it breaks and to see how your code handles it.
    I suggest you rewrite this double nested loop to perform the three steps separately.
    1. split the code into two parts
    a. put the spec into one new CLOB variable and the body into the other.
    b. use DBMS_OUTPUT (or a work table) to output the spec and body so you can see what the code is and make sure the 'split' process worked properly. You probably created that BLOB by manually concatenating the SPEC and BODY to begin with so now create a SPLIT process to split them again and give them back to you. This is such a fundamental component that I suggest creating a new SPLIT_MY_BLOB procedure. This procedure would take a BLOB and return two CLOBS as OUT parameters: one CLOB is the spec and one is the body. Then you can reuse this 'split' procedure in other code or more complex versions of code. Modular programming is the key.
    2. execute the spec - Now have a step that executes the spec and does something appropriate if the step succeeds or if it fails. I mean, do you really want to do execute the body if the spec execution fails? What do you want to do? Should you delete the body and spec? If you don't you might wind up with an INVALID body based on old code and an INVALID spec based on the new code you were trying to use. How will anyone, including you, know that the spec and body in the ALL_SOURCE view is really two different versions of things?
    This suggests that for your use case you may want to consider DROPPING the entire package, spec and body, before trying to recreate them both. At least if the package is totally missing anyone will know that the entire thing needs to be put back. Ahhhh - but to do that you need to know the package name so you can drop it. Than may require adding another step to get the package name from your data-driven table and adding a DROP PACKAGE step.
    3. execute the body - This step executes the body. Hmmmm - we have two nearly identical steps. So why don't you create a new function/procedure that takes a CLOB as input, uses dynamic sql to execute it and returns a result code. That would be useful. Then you could execute ANY sql stored in a CLOB and have a generic function that you can use for other things.
    Right now you are using the VARCHAR2 table version of DBMS_SQL.PARSE but you would change this to use the CLOB version.
    The end result of this refactoring is a main function/procedure that acts as the CONTROL - it decides what to do and what data (BLOB) to do it with. But it doesn't actually do ANY of the work. It just controls what is done.
    And you have a couple of generic, reuseable functions that actually do the work. One knows how to split a CLOB into spec and body. The other knows how to use dynamic SQL to execute a CLOB.
    Now you have a modular architecture that is easy to understand, easy to code and easy to test.

Maybe you are looking for

  • Problems of running java program by crontab in Linux

    I have a java application program which runs great when started in command line, or in shell script, or Perl. However, when it is started by crontab in Linux, it stops in the middle when images are to be generated. I guess there might be some setting

  • I bought an app and now it's gone from my purchased list. What do I do to get it back?

    I bought CHAOS RINGS Ω for iPad awhile back and I was able to download it to my iTunes but now it is not even my Purchased List. Order Number: MHGF979Q0D Receipt Date: 26/07/12

  • HT4522 what is the preferred disk erase mode for Time Capsule

    I've been wanting to re-format my Time capsule as I've bought a new Mac Book and currently have 2 backups loaded. Since I've merged data, I wanted to erase and re-use the TC. Can someone tell me what the preferred disk erase mode is for TC.

  • Long pauses during printing

    I have an HP C5550 all in one.  It workd fine for quite awhile, but now there are long pauses after it prints each line.  Tried unplugging the USB cable and doing a sef-test and got the same result

  • FCPX Update

    Is it going to be possible to download just the updates to FCPX (for free) to my existing version or are the improvements only going to be available on new versions?