Iterative assignments to varray elements

I have a problem with assigning values to varray elements in a FOR LOOP, I get the message ORA 06533 SUBSCRIPT_BEYOND_COUNT error, says that I need to initialize the elements first, but this what I am trying to do with the FOR LOOP.
given the following:
CREATE OR REPLACE PACKAGE CATS_P_REPORTDATA AS.......
TYPE DateRecTyp IS RECORD (TRXNDATE DATE);
TYPE DateTabTyp IS TABLE OF DateRecTyp INDEX BY BINARY_INTEGER;
TYPE Calendar IS VARRAY(366) OF DATE;
CREATE OR REPLACE PROCEDURE CATS_SP_PARTAVAILABILITY
(dataset IN OUT CATS_P_REPORTDATA.InvCurTyp, begindate IN CHAR, enddate IN CHAR)
AS........
dteEndDate DATE;
dteBeginDate DATE;
numDays INT;
--tabDate CATS_P_REPORTDATA.DateTabTyp;
tabDate CATS_P_REPORTDATA.Calendar;
i BINARY_INTEGER;
dteEndDate := to_date(enddate);
dteBeginDate := to_date(begindate);
numDays := (dteEndDate - dteBeginDate) + 1;
tabDate := CATS_P_REPORTDATA.Calendar(); tried this prior to FOR LOOP, but no help
--tabDate := CATS_P_REPORTDATA.Calendar(dteBeginDate,dteBeginDate + 1, dteBeginDate + 2); this works but is useless since we never know the delta between enddate and begindate to know how many assignments to do.
FOR i IN 1..numDays LOOP
tabDate(i) := dteBeginDate + i; this is what I want to do but I keep getting the SUBSCRIPT_BEYOND_COUNT error, meaning the elements have not been initialized.......this is what am trying to do.
END LOOP;
Thanks in advance for any suggestions,
Scott

Because you did not **Initialize** the VArray, it is throwing ORA-6533 error.
Consider the following test, which is quite self explanatory.SQL> DECLARE
  2     TYPE VArray_String_Typ IS VARRAY(5) OF VARCHAR2(15);
  3     vListNames VArray_String_Typ := VArray_String_Typ('','','',''); -- only initializing 4 elements
  4  BEGIN
  5     vListNames(1) := 'SriDHAR';
  6     vListNames(2) := 'Scott';
  7     FOR i IN 1..4 -- Printing only 4 elements
  8     LOOP
  9        DBMS_OUTPUT.PUT_LINE(NVL(vListNames(i), 'NULL'));
10     END LOOP;
11  END;
12  /
SriDHAR
Scott
NULL
NULL
PL/SQL procedure successfully completed.
-- Let us try to assign to 5th element which should throw the error
SQL> DECLARE
  2     TYPE VArray_String_Typ IS VARRAY(5) OF VARCHAR2(15);
  3     vListNames VArray_String_Typ := VArray_String_Typ('','','',''); -- Still 4 elements here
  4  BEGIN
  5     vListNames(1) := 'SriDHAR';
  6     vListNames(2) := 'Scott';
  7     -- generate error ORA-6533 here
  8     vListNames(5) := '*****'; -- trying to assign into 5th element here, which does not exist
  9     FOR i IN 1..4
10     LOOP
11        DBMS_OUTPUT.PUT_LINE(NVL(vListNames(i), 'NULL'));
12     END LOOP;
13  END;
14  /
DECLARE
ERROR at line 1:
ORA-06533: Subscript beyond count
ORA-06512: at line 8
-- Let us go back in the program and initialize the 5th element
SQL> DECLARE
  2     TYPE VArray_String_Typ IS VARRAY(5) OF VARCHAR2(15);
  3     vListNames VArray_String_Typ := VArray_String_Typ('','','','', ''); -- initialize 5th element here
  4  BEGIN
  5     vListNames(1) := 'SriDHAR';
  6     vListNames(2) := 'Scott';
  7     -- error ORA-6533 should go away
  8     vListNames(5) := '*****';
  9     FOR i IN 1..5 -- include 5th element for printing here
10     LOOP
11        DBMS_OUTPUT.PUT_LINE(NVL(vListNames(i), 'NULL'));
12     END LOOP;
13  END;
14  /
SriDHAR
Scott
NULL
NULL
PL/SQL procedure successfully completed.Good luck,
Sri

Similar Messages

  • How to split a  comma seperated varray element ..

    Hi ,
    If I have varray with elements in the below fashion.
    first element -- 'var1=v1'
    Second element -- 'var2=v2'
    third element --' var3=v3'
    fourth element -- 'var4=v4'
    fifth element -- 'var5=v5'
    Is there a way I can split them to get as the following
    var1
    v1
    var2
    v2
    var3
    v3
    var4
    v4
    var5
    v5
    Basically each varray element is seperated by a equal to sign '='.
    Thanks & Regards

    this query may help you to get your output.
    with t as (
    select 1 rn,'var1=v1'  ccc  from dual
    union all
    select 2,'var2=v2' from dual
    union all
    select 3,'var3=v3' from dual
    union all
    select 4,'var4=v4' from dual
    union all
    select 5,'var5=v5' from dual)
    select * from (
    select rn,substr(ccc,1,instr(ccc,'=')-1) from t
    union all
    select rn,substr(ccc,instr(ccc,'=')+1) from t) order by 1

  • How to change the Element structure of a DefaultSyledDocument

    Hello,
    I'm trying to override the insertUpdate method of DefaultStyledDocument so that I could build my own Element structure by adding my own BranchElement- and LeafElement-s. If I examine the Element hierarchy everything seems OK. But when I use my document in a JTextPane. I get the error Exception in thread "AWT-EventQueue-0" javax.swing.text.StateInvariantError: GlyphView: Stale view: javax.swing.text.BadLocationException: Invalid location (I add the whole dump at the end of this message), whenever I add a new line to the document (to test this compile and run the included code and press then newline after the 'He' in 'Hello'. I suspect that the error is caused by the fact that the view hierarchy is not updated correctly but I'm not sure. To be honest I have searched for a while for some example code, explaning how you can make your own element hierarchy in a DefaultStyledDocument (without using ElementBuffer), but to no avail.
    Can any of the Text gurus here shed some lights on my code and see what is wrong with it or point me to some example code.
    Thanks a lot in advance.
    Marc Mertens
    Full Stack Dump
    Exception in thread "AWT-EventQueue-0" javax.swing.text.StateInvariantError: GlyphView: Stale view: javax.swing.text.BadLocationException: Invalid location
    at javax.swing.text.GlyphView.getText(GlyphView.java:117)
    at javax.swing.text.GlyphPainter1.getSpan(GlyphPainter1.java:43)
    at javax.swing.text.GlyphView.getPreferredSpan(GlyphView.java:537)
    at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:689)
    at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:216)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:911)
    at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:542)
    at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:879)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:911)
    at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:325)
    at javax.swing.text.BoxView.layout(BoxView.java:682)
    at javax.swing.text.BoxView.setSize(BoxView.java:379)
    at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1618)
    at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:812)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.JEditorPane.getPreferredSize(JEditorPane.java:1227)
    at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" javax.swing.text.StateInvariantError: GlyphView: Stale view: javax.swing.text.BadLocationException: Invalid location
    at javax.swing.text.GlyphView.getText(GlyphView.java:117)
    at javax.swing.text.GlyphPainter1.getSpan(GlyphPainter1.java:43)
    at javax.swing.text.GlyphView.getPreferredSpan(GlyphView.java:537)
    at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:689)
    at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:216)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:911)
    at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:542)
    at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:879)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:911)
    at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:325)
    at javax.swing.text.BoxView.layout(BoxView.java:682)
    at javax.swing.text.BoxView.setSize(BoxView.java:379)
    at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1618)
    at javax.swing.plaf.basic.BasicTextUI.modelToView(BasicTextUI.java:946)
    at javax.swing.text.DefaultCaret.repaintNewCaret(DefaultCaret.java:1246)
    at javax.swing.text.DefaultCaret$1.run(DefaultCaret.java:1225)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" javax.swing.text.StateInvariantError: GlyphView: Stale view: javax.swing.text.BadLocationException: Invalid location
    at javax.swing.text.GlyphView.getText(GlyphView.java:117)
    at javax.swing.text.GlyphPainter1.getSpan(GlyphPainter1.java:43)
    at javax.swing.text.GlyphView.getPreferredSpan(GlyphView.java:537)
    at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:689)
    at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:216)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:911)
    at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:542)
    at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:879)
    at javax.swing.text.BoxView.checkRequests(BoxView.java:911)
    at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:325)
    at javax.swing.text.BoxView.layout(BoxView.java:682)
    at javax.swing.text.BoxView.setSize(BoxView.java:379)
    at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1618)
    at javax.swing.plaf.basic.BasicTextUI.modelToView(BasicTextUI.java:946)
    at javax.swing.text.DefaultCaret.setVisible(DefaultCaret.java:952)
    at javax.swing.text.DefaultCaret.focusLost(DefaultCaret.java:347)
    at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:172)
    at java.awt.Component.processFocusEvent(Component.java:5380)
    at java.awt.Component.processEvent(Component.java:5244)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3955)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1810)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:840)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:530)
    at java.awt.Component.dispatchEventImpl(Component.java:3841)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.SentEvent.dispatch(SentEvent.java:50)
    at java.awt.DefaultKeyboardFocusManager$DefaultKeyboardFocusManagerSentEvent.dispatch(DefaultKeyboardFocusManager.java:161)
    at java.awt.DefaultKeyboardFocusManager.sendMessage(DefaultKeyboardFocusManager.java:188)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:595)
    at java.awt.Component.dispatchEventImpl(Component.java:3841)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Window.dispatchEventImpl(Window.java:1778)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.SequencedEvent.dispatch(SequencedEvent.java:93)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    java.lang.ThreadDeath
    at java.lang.Thread.stop(Thread.java:698)
    at java.lang.ThreadGroup.stopOrSuspend(ThreadGroup.java:671)
    at java.lang.ThreadGroup.stop(ThreadGroup.java:584)
    at org.netbeans.core.execution.DefaultSysProcess.stop(DefaultSysProcess.java:54)
    at org.netbeans.core.execution.ProcessNodeItem$1.stop(ProcessNodeItem.java:41)
    at org.netbeans.core.execution.ProcessNodeItem$TerminateProcessAction.performAction(ProcessNodeItem.java:69)
    at org.openide.util.actions.NodeAction$3.run(NodeAction.java:531)
    at org.netbeans.modules.openide.util.ActionsBridge.doPerformAction(ActionsBridge.java:47)
    at org.openide.util.actions.NodeAction$DelegateAction.actionPerformed(NodeAction.java:527)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
    at java.awt.Component.processMouseEvent(Component.java:5488)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
    at java.awt.Component.processEvent(Component.java:5253)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3955)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
    at java.awt.Container.dispatchEventImpl(Container.java:2010)
    at java.awt.Window.dispatchEventImpl(Window.java:1778)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    package Document;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.AbstractDocument.*;
    * EditorDocument.java
    * Created on September 10, 2006, 3:58 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * Document to represent the content of a syntax highlighting editor
    * @author marc
    public class EditorDocument extends DefaultStyledDocument {
        /** List of the white space characters */
        private char[] _whiteSpaceChars;
        /** List of the delimiter characters */
        private char[] _delimiterChars;
        /** Creates a new instance of EditorDocument */
        public EditorDocument(char[] whiteSpaceChars,char[] delimiterChars) {
            _whiteSpaceChars=whiteSpaceChars;
            _delimiterChars=delimiterChars;
         * Updates document structure as a result of text insertion.  This
         * will happen within a write lock.  Since this document simply
         * maps out lines, we refresh the line map.
         * @param chng the change event describing the dit
         * @param attr the set of attributes for the inserted text
        protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng, AttributeSet attr) {
            int begin=Math.max(0,chng.getOffset()-1);
            int end=begin+chng.getLength()+1;
            Element rootElement=getDefaultRootElement();
            int index;
            int m=rootElement.getElementCount();
            AbstractDocument.BranchElement line;
            super.insertUpdate(chng,attr);
            // Add the tokens
            index=rootElement.getElementIndex(begin);
            m=rootElement.getElementCount();
            if (index>=0)
                for (;index<m && (line=(AbstractDocument.BranchElement) rootElement.getElement(index)).getStartOffset()<=end;index++) {
                chng.addEdit(addTokens(line,attr));
            //fireChangedUpdate(chng);
        protected void insertUpdate(AbstractDocument.DefaultDocumentEvent chng,AttributeSet attr) {
            int begin=chng.getOffset();
            int end=begin+chng.getLength();
            BranchElement root=(BranchElement) getDefaultRootElement();
            // Find the lines that must be removed
            int indexFirstLine=root.getElementIndex(begin);
            int indexLastLine=root.getElementIndex(end);
            BranchElement[] removeLines=new BranchElement[indexLastLine-indexFirstLine+1];
            for (int i=indexFirstLine;i<=indexLastLine;i++)
                removeLines=(BranchElement) root.getElement(i);
    // Add the lines must replace the removed lines
    int beginFirstLine=removeLines[0].getStartOffset();
    int endLastLine=removeLines[removeLines.length-1].getEndOffset();
    Segment segment=new Segment();
    ArrayList<BranchElement> newLines=new ArrayList<BranchElement>(removeLines.length); // Guess the length of the new lines
    try {
    getText(beginFirstLine,endLastLine,segment);
    char c=segment.current();
    BranchElement line;
    while (c!=Segment.DONE) {
    if (c=='\n') {
    line=new BranchElement(root,attr);
    newLines.add(line);
    addTokens(line,attr,beginFirstLine,segment.getIndex()+1);
    beginFirstLine=segment.getIndex()+1;
    c=segment.next();
    if (beginFirstLine<endLastLine) {
    line=new BranchElement(root,attr);
    newLines.add(line);
    addTokens(line,attr,beginFirstLine,endLastLine);
    // Add the lines to the Root element
    BranchElement[] linesAdded=newLines.toArray(new BranchElement[newLines.size()]);
    root.replace(indexFirstLine,indexLastLine-indexFirstLine+1,linesAdded);
    // Notify listeners
    DefaultDocumentEvent edit=new DefaultDocumentEvent(begin,end-begin,DefaultDocumentEvent.EventType.CHANGE);
    edit.addEdit(new ElementEdit(root,indexFirstLine,removeLines,linesAdded));
    fireChangedUpdate(edit);
    } catch (Exception e) {
    throw new EditorException("Error in insertUpdate, message was "+e.getMessage(),e);
    //super.insertUpdate(chng,attr);
    private void addTokens(AbstractDocument.BranchElement line,AttributeSet attr,int begin,int end) {
    try {
    ArrayList<TokenElement> childTokens=new ArrayList<TokenElement>();
    int strLength=end-begin;
    // Create the new tokens
    Segment segment=new Segment();
    getText(begin,end-begin,segment);
    char c;
    int b=0;
    TokenElement token;
    //System.out.println(str);
    c=segment.current();
    while (c!=Segment.DONE) {
    if (isWhite(c)) {
    // Whitespace character
    if (b<segment.getIndex()) {
    token=new TokenElement(line,attr,begin+b,begin+segment.getIndex(),false);
    childTokens.add(token);
    b=segment.getIndex();
    // Find all the white spaces
    while ((c=segment.next())!=Segment.DONE && isWhite(c));
    token=new TokenElement(line,attr,begin+b,begin+segment.getIndex(),true);
    childTokens.add(token);
    b=segment.getIndex(); // Begin of next token
    } else if (isDelimiter(c)) {
    // Delimiter
    if (b<segment.getIndex()) {
    token=new TokenElement(line,attr,begin+b,begin+segment.getIndex(),false);
    childTokens.add(token);
    token=new TokenElement(line,attr,begin+segment.getIndex(),begin+segment.getIndex(),c);
    childTokens.add(token);
    b=segment.getIndex();
    c=segment.next();
    } else {
    c=segment.next();
    if (b<segment.getIndex()) {
    token=new TokenElement(line,attr,begin+b,begin+segment.getIndex(),false);
    childTokens.add(token);
    Element[] removed=new Element[line.getElementCount()];
    for (int i=0;i<removed.length;i++)
    removed[i]=line.getElement(i);
    TokenElement[] newElements=childTokens.toArray(new TokenElement[childTokens.size()]);
    line.replace(0,line.getElementCount(),newElements);
    } catch (Exception e) {
    throw new EditorException("Unexpected BadlocationException ");
    * Returns a iterator of the tokens starting from the given position
    * @param The position that is covered by the first token returned by this iterator
    * @return A iterator of all the tokens starting at the given position
    public Iterator<IToken> getTokensFrom(int position) {
    return new TokenIterator(position);
    private String getText(Element element) {
    int begin=element.getStartOffset();
    int end=Math.min(element.getEndOffset(),getLength());
    try {
    return getText(begin,end-begin);
    } catch (BadLocationException e) {
    throw new EditorException("Unexpected BadLocationException (this should not happen at all)");
    * Check if a character is a white space
    * @return True if a character is a white space
    private boolean isWhite(char c) {
    if (c=='\n') // End of line is always a white space
    return true;
    for (char whiteChar : _whiteSpaceChars)
    if (whiteChar==c)
    return true;
    return false;
    * Check if a character is a delimiter character (different from a white space character)
    * @return True if a character is a delimiter character
    private boolean isDelimiter(char c) {
    for (char delimiterChar : _delimiterChars)
    if (delimiterChar==c)
    return true;
    return c=='\0';
    * Test code
    public static void main(String[] args) {
    // Display a test frame containing a test document
    try {
    JFrame frm=new JFrame();
    EditorDocument doc=new EditorDocument(new char[] {' ','\n','\t','\r'},new char[0]);
    doc.insertString(0,"Hello",null);
    JTextPane pane=new JTextPane(doc);
    JScrollPane scroll=new JScrollPane(pane);
    frm.getContentPane().add(scroll);
    frm.setSize(200,300);
    frm.setVisible(true);
    } catch (Exception e) {
    * Class that is a iterator over the tokens in the document
    private class TokenIterator implements Iterator<IToken> {
    private int _lineIndex=-1;
    private int _tokenIndex=-1;
    public TokenIterator(int position) {
    AbstractDocument.BranchElement root=(AbstractDocument.BranchElement) getDefaultRootElement();
    _lineIndex=root.getElementIndex(position);
    AbstractDocument.BranchElement line=(AbstractDocument.BranchElement) root.getElement(_lineIndex);
    _tokenIndex=line.getElementIndex(position)-1;
    * Removes from the underlying collection the last element returned by the
    * iterator (optional operation). This method can be called only once per
    * call to <tt>next</tt>. The behavior of an iterator is unspecified if
    * the underlying collection is modified while the iteration is in
    * progress in any way other than by calling this method.
    * @exception UnsupportedOperationException if the <tt>remove</tt>
    *           operation is not supported by this Iterator.
    * @exception IllegalStateException if the <tt>next</tt> method has not
    *           yet been called, or the <tt>remove</tt> method has already
    *           been called after the last call to the <tt>next</tt>
    *           method.
    public void remove() {
    // Do nothing
    * Returns the next element in the iteration. Calling this method
    * repeatedly until the {@link #hasNext()} method returns false will
    * return each element in the underlying collection exactly once.
    * @return the next element in the iteration.
    * @exception NoSuchElementException iteration has no more elements.
    public IToken next() {
    Element root=getDefaultRootElement();
    if (_lineIndex>=root.getElementCount())
    return null;
    Element line=root.getElement(_lineIndex);
    _tokenIndex++;
    if (_tokenIndex>=line.getElementCount()) {
    _lineIndex++;
    if (_lineIndex>=root.getElementCount())
    return null;
    line=root.getElement(_lineIndex);
    if (line.getElementCount()==0)
    return null;
    _tokenIndex=0;
    return (IToken) line.getElement(_tokenIndex);
    * Returns <tt>true</tt> if the iteration has more elements. (In other
    * words, returns <tt>true</tt> if <tt>next</tt> would return an element
    * rather than throwing an exception.)
    * @return <tt>true</tt> if the iterator has more elements.
    public boolean hasNext() {
    int lineIndex=_lineIndex;
    int tokenIndex=_tokenIndex;
    Element root=getDefaultRootElement();
    if (lineIndex>=root.getElementCount())
    return false;
    Element line=root.getElement(lineIndex);
    tokenIndex++;
    if (tokenIndex>=line.getElementCount()) {
    lineIndex++;
    if (lineIndex>=root.getElementCount())
    return false;
    line=root.getElement(lineIndex);
    if (line.getElementCount()==0)
    return false;
    return true;
    * Represents a token in the document
    private class TokenElement extends AbstractDocument.LeafElement implements IToken, Comparable<TokenElement> {
    private boolean _isWhiteSpace;
    private char _separatorChar='\0';
    public TokenElement(Element parent,AttributeSet attributeSet,int offs0,int offs1,boolean whiteSpace) {
    super(parent,attributeSet,offs0,offs1);
    _isWhiteSpace=whiteSpace;
    public TokenElement(Element parent,AttributeSet attributeSet,int offs0,int offs1,char separatorChar) {
    super(parent,attributeSet,offs0,offs1);
    _separatorChar=separatorChar;
    * Returns the separator character if this token is a separator, returns '\0' otherwise
    * @return The separator charactor or null otherwise
    public char getSeparatorChar() {
    return _separatorChar;
    * Compares this object with the specified object for order. Returns a
    * negative integer, zero, or a positive integer as this object is less
    * than, equal to, or greater than the specified object.<p>
    * In the foregoing description, the notation
    * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
    * <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
    * <tt>0</tt>, or <tt>1</tt> according to whether the value of <i>expression</i>
    * is negative, zero or positive.
    * The implementor must ensure <tt>sgn(x.compareTo(y)) ==
    * -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
    * implies that <tt>x.compareTo(y)</tt> must throw an exception iff
    * <tt>y.compareTo(x)</tt> throws an exception.)<p>
    * The implementor must also ensure that the relation is transitive:
    * <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies
    * <tt>x.compareTo(z)>0</tt>.<p>
    * Finally, the implementer must ensure that <tt>x.compareTo(y)==0</tt>
    * implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
    * all <tt>z</tt>.<p>
    * It is strongly recommended, but <i>not</i> strictly required that
    * <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any
    * class that implements the <tt>Comparable</tt> interface and violates
    * this condition should clearly indicate this fact. The recommended
    * language is "Note: this class has a natural ordering that is
    * inconsistent with equals."
    * @param o the Object to be compared.
    * @return a negative integer, zero, or a positive integer as this object
    *           is less than, equal to, or greater than the specified object.
    * @throws ClassCastException if the specified object's type prevents it
    * from being compared to this Object.
    public int compareTo(TokenElement o) {
    return getStartOffset()-o.getStartOffset();
    * Indicates this is a white space token
    * @return true if this is a white space token false otherwise
    public boolean isWhiteSpace() {
    return _isWhiteSpace;
    * Returns the string this token is representing
    * @return The string behind this token
    public String getText() {
    return EditorDocument.this.getText(this);
    class SearchToken implements IToken {
    private int _offset;
    public SearchToken(int offset) {
    _offset=offset;
    * @return The start of the token used in comparisation operations
    public int getEndOffset() {
    return _offset;
    public int getStartOffset() {
    return _offset;
    public boolean isWhiteSpace() {
    throw new EditorException("May not be called");
    public String getText() {
    throw new EditorException("May not be called");
    public char getSeparatorChar() {
    throw new EditorException("May not be called");

    I am trying to add primitive syntax highlighting to my JTextPane and have serious problems which I already stated in this forum. Now I read from uncle_alice that the text package from swing is not ment for that and that I need to write my own JTextPane and my own document and view.
    Can you explain what you mean by "writing my own JTextPane and View and Dcoument".
    My own Document I already have in order to provide SQL-highlighting.
    But what exactly do you mean by suggesting to write my own View! Whoever uses JTextPane doesnt really have much to do with its view. Can you give me a hint as I am completely stuck with an Exception : "javax.swing.text.StateInvariantError: GlyphView: Stale view: javax.swing.text.BadLocationException: Length must be positive"
    can you pinpoint the standard text-package's deficiency? it lacks what? what is the best work around?
    cheers
    ioannis

  • How to update/change the value of elements in an xml file?

    Hi Everyone,
    Could any one of u tell me how to update the value of elements in an XML file, using java? The reason is i want to use an XML file as a data source (i.e. more or less like a database), without using any RDBMS, for simple applications such as to read a record and update the record. By the way, my XML file will have only one record, such as the current weather information, with fields such as temperature, humdity etc. for 1 city only.
    Thanks in advance.

    Here is a solution how to check a particular value or element name in an xml and update the changes e to an xml.
    Sample.xml
    <URLConstructor>
    <application name="cp_outage">
    <resource>hello</resource>
    <value>val</value>
    </application>
    <application name="cp_outage">
    <resource>hello</resource>
    <value>val</value>
    </application>
    </URLConstructor>
    XMLWriter.java
    package com;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.DOMBuilder;
    import org.jdom.output.XMLOutputter;
    // used for printing
    import org.apache.xml.serialize.XMLSerializer;
    import org.jdom.output.XMLOutputter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Iterator;
    import java.util.List;
    class XMLWriter{
    public void update(File fileName)
    try {
              DOMBuilder domBuilder=new DOMBuilder();
              Document doc=domBuilder.build(fileName);
              Element element=doc.getRootElement();
              getChildren(element);
              writeToXML(doc,fileName);
              getChildren(element);
    } catch (Exception e) {
    e.printStackTrace();
         * @param doc
         private void writeToXML(Document document,File filePath)
                   XMLOutputter xmloutputter = new XMLOutputter();
                        try
                             FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                             xmloutputter.output(document, fileOutputStream);
                             fileOutputStream.close();
                        catch (FileNotFoundException e)
                             e.printStackTrace();
                        catch (IOException e)
                             e.printStackTrace();
         public void getChildren(Element element)
                        if(!element.hasChildren())
                             return;
                        List childrenList = element.getChildren();
                        Iterator itr=childrenList.iterator();
                        while(itr.hasNext())
                             Element childElement=(Element) itr.next();
                             if(childElement.hasChildren())
                                       getChildren(childElement);
    //                                   System.out.println("Name "+childElement.getName());
    //                                   System.out.println("Value "+childElement.getText());
                                       if(childElement.getText().equals("hello") || (childElement.getName().equals("resource")))
                                            updateInfo(childElement,"New_Resource","AddedText");
         * @param childElement
         * @param string
         * @param string2
         private void updateInfo(Element element, String elementName, String value)
              element.setName(elementName);
              element.setText(value);          
    static public void main(String[] args)
    XMLWriter xmlWriter=new XMLWriter();
    xmlWriter.update(new File("c:/sample.xml"));
    After execution the file will be changed to
    <URLConstructor>
    <application name="cp_outage">
    <New_Resource>AddedText</New_Resource>
    <value>val</value>
    </application>
    <application name="cp_outage">
    <New_Resource>AddedText</New_Resource>
    <value>val</value>
    </application>
    </URLConstructor>
    Regards,
    Maheswar

  • How do you determine the index of a List Iterator?

    I understand where the indices of a List Iterator in relation to the elements.
    Element(0) Element(1) Element(2) ... Element(n)
    ^ ^ ^ ^ ^
    Index: 0 1 2 3 n+1
    But I don't know how to return an index of a List Iterator.
    I'm trying to build a nextIndex and previousIndex method, which would return the index of the particular List Iterator of either the next() or previous() functions had been performed.
    Here is the rest of the code:
    public class List<E>
          Constructs an empty linked list.
       public List()
          first = null;
          last = null;
          size = 0;
          Returns the first element in the linked list.
          @return the first element in the linked list
       public E getFirst()
          if (first == null)
             throw new ListException("getFirst() called on empty list");
          return first.data;
          Removes the first element in the linked list.
          @return the removed element
       public E removeFirst()
          if (first == null)
             throw new ListException("removeFirst called on an empty list");
          E element = first.data;
          Node tmp = first;
          if (last == first)
              last = null;
          first = first.next;
          if (first != null)
              tmp.next = null;
              first.previous = null;
          size--;     
          return element;
          Adds an element to the front of the linked list.
          @param element the element to add
       public void addFirst(E element)
          Node newNode = new Node();
          newNode.data = element;
          newNode.next = first;
          if (first != null)
              first.previous = newNode;
          else
              last = newNode;
          first = newNode;
          size++;
          Returns an iterator for iterating through this list.
          @return an iterator for iterating through this list
       public ListIterator listIterator()
          return new ListIterator();
       public int size()
           return size;
       private Node first;
       private Node last;
       private int size;
       private class Node
          public E data;
          public Node next;
          public Node previous;
       private class ListIterator implements ListIteratorAPI<E>
             Constructs an iterator that points to the front
             of the linked list.
          public ListIterator()
             position = null;
             previous = null;
             Moves the iterator past the next element.
             @return the traversed element
          public E next()
             if (!hasNext())
                throw new ListException("Next() called at the end of the list");
             previous = position; // Remember for remove
             if (position == null)
                position = first;
             else
                position = position.next;
             return position.data;
             Moves the iterator before the element.
             @return the traversed element
          public E previous()
             if (!hasPrevious())
                throw new ListException("previous() called at the beginning of the list");
             previous = position; // Remember for remove
             if (position == null)
                position = last;
             else
                position = position.previous;
             return position.data;
             Tests if there is an element after the iterator
             position.
             @return true if there is an element after the iterator
             position
          public boolean hasNext()
             if (position == null)
                return first != null;
             else
                return position.next != null;
             Tests if there is an element before the iterator
             position.
             @return true if there is an element before the iterator
             position
          public boolean hasPrevious()
             if (position == null)
                return last != null;
             else
                return position.previous != null;
             Adds an element before the iterator position
             and moves the iterator past the inserted element.
             @param element the element to add
          public void add(E element)
             if (position == null)
                addFirst(element);
                position = first;
             else
                Node newNode = new Node();
                newNode.data = element;
                newNode.next = position.next;
                newNode.next.previous = newNode;
                position.next = newNode;
                newNode.previous = position;
                position = newNode;
                size++;
             previous = position;        
             Removes the last traversed element. This method may
             only be called after a call to the next() method.
          public void remove()
             if (previous == position)
                throw new IllegalStateException();
             if (position == first)
                removeFirst();
             else
                Node tmp = position;
                previous.next = position.next;
                if (position.next != null)
                    position.next.previous = previous;
                tmp.next = tmp.previous = null;
                position.previous = previous;
                size--;
             position = previous;
             Sets the last traversed element to a different
             value.
             @param element the element to set
          public void set(E element)
             if (position == null)
                throw new ListException("set calls on a null node");
             position.data = element;
          private Node position;
          private Node previous;
    }All I have for nextIndex() is this:
    public int nextIndex(){
          if (this.hasNext() == false)
               return size;
               else
                  this.next();
                  //what goes after this?
          }What am I missing? How do I return an index of a List Iterator?

    I wouldn't have a clue how to get the array-index from the current element of an iterator... and I don't think it is possible simply because not all implementations of list have a useful index... and certainly an index would be meaningless when iteratring a hashmap... so iterator doesn't support indexes.
    Isn't nextIndex an optional operation? ... And one which makes frag all sense for a linked list?[java.util.ListIterator|http://java.sun.com/javase/6/docs/api/java/util/ListIterator.html]
    ~

  • Mapping elements of VRA to a number

    hi,
    My project involves maintaining the database for a bus company.
    Each bus_route is divided into regions. Each bus-stop on a route maps to a region.
    eg. bus-stop numbers 1,2,4,5,6,8 map to Region 2.
    I was thinking of having a table regions with the following structure:
    create table regions
    Region_id NUMBER,
    route_id VARCHAR2(20),
    bus_stops stops_va
    INSERT INTO regions VALUES(2, '459UP', STOPS_VA(1,2,4,5, 6, 8));
    However, given a route_id and bus-stop number determining the region is a little tedious involving
    looping through the varray elements of all rows with given route_id.
    Is there an easier and more efficient way of doing this?
    Amina

    Amina
    You may find it easier to stick to a relational model if you want to be able to query rapidly:
    Region ---< Stop ----<Route-Stop>----- Route
    Route-Stop represents the M:M relationship between Route and Stop. I'm assuming that a Stop is always in the same Region (for all the bus routes that use the stop). Assuming your bus company works like the London Underground (stop = station) then for example
    Stop "Victoria Station" is in region 1;
    It is on 3 lines (District, Circle, Victoria Line)
    It is stop #4 on Victoria Line; (counting from Brixton)
    It is stop #12 on District Line; (counting from Ealing Broadway)
    It is stop #8 on Circle Line (counting anti-clockwise from Edgeware Road)
    (see map at http://www.tfl.gov.uk/tfl/pdfdocs/colourmap.pdf). Actually, for timetabling purposes its on at least 10 lines (Circle line both ways, Victoria line both ways, District Line both ways to each of Wimbledon, Richmond, Ealing ...)
    I'm presuming that the Route-Stop would have a stop_number (start to finish of route).
    So if you want to list out a bus route from beginning to end:
    select rt.route_id, rt.route_desc,
    st.stop_id, st.stop_desc,
    rs.stop_number,
    rg.region_id, rg.region
    from routes rt
    inner join route_stops rs on rs.route_id = rt.route_id
    inner join stops st on st.stop_id = rs.stop_id
    inner join regions rg on rg.region_id = st.region_id
    where rt.route_id = :my_route
    order by rs.stop_number
    route_stops has columns (route_id, stop_id, stop_number); the PK is all the rows together; you could make this an index organised table.
    Having a relational structure makes it easy to query from any viewpoint; eg if you want to print timetables for a specific bus stop, you easily could...
    Failing that, if you really want to pack the route into a nested table (and you've realised that it can be inconvenient) then it's the M:M relationship that wants to be nested. The 'route-stop' table should be nested into the routes table, not the regions table. Essentially, the stop is a more or less permanent fixture; routes may change; you can regard the sequence of stops as a (list) attribute of the route (if the route is axed, the sequence of stops is axed too). When you change a route, you change the list of stops. You'd want to edit one row in routes, not every combination of region/route. Your proposed table means that a route crossing regions would have several rows in the 'regions' table - not very well normalised :-)
    HTH, but let me know if you want more information on manipulating nested tables in a relational way
    Regards Nigel

  • Problem in printing elements of a Set element

    I am using iterator to print the elements of a set as below:
    Set<String> set = new HashSet<String>();
    set.add("element");
    Iterator it = set.iterator();
    while (it.hasNext()) {
                     System.out.println(it.next() + "\n");
    }The above code perfectly prints all the elements in the set.
    I am facing problem when I am trying to store the value of set element in a string and print as below:
    while (it.hasNext()) {
                     System.out.println(it.next() + "\n");
                     String e = (String)it.next();
    System.out.println(e);
    }All the elements in the set are not printed. Why is it behaving like so?

    while (it.hasNext()) {
                     System.out.println(it.next() + "\n");
                     String e = (String)it.next();
    System.out.println(e);
    }You are calling it.next() method twice so it is printing alternate values.
    try this:-
    while (it.hasNext()) {
                     String e = (String)it.next();
                     System.out.println(e + "\n");
    System.out.println(e);
    }

  • WBS elements to Po

    hello gurus
    I want to know if we can have account assignment to purchase orders with wbs elements
    mike

    Hi
    Yes you can have acct assignments of WBS elements to the Purchase orders. Please gothorugh the SAP online documentation to understand the pre-requisites and procedures.
    If you still have any questions please let us know. Also please note that this question should be posted in MM or PS area so that you can get more responses and solutions.
    Thanks

  • Collection of Elements and JDOM

    Hello,
    I got a Collection form a session      and this Collection contains many Elements.
    I need these elements for construction an xml.
    Below is a piece of code and it works for the first time.
              Collection fieldList = selectedIndex.getFieldsList();
                   Iterator fieldListIte = fieldList.iterator();
                   while (fieldListIte.hasNext()) {               
                          Element element = (Element)fieldListIte.next();
                          fieldListIte.remove();
                          //take it away from the iterator
                          root.addContent(element.detach());
                                                                      // root.addContent(element);
                                                                      //without detach(), it works too
                   }For the second time the Collection will be empty as I used fieldListIte.remove().
    Therefore I took "fieldListIte.remove()" away. Then there was exception.
    Why should I use "fieldListIte.remove()"? How can I avoid this?
    By the way, I have another question:
    Is element.detach() really necessary?
    Thanks for any idea.
    Pengyou

    I solved the problem by
                          Element newElement = (Element)element.clone();
                          root.addContent(newElement.detach());Now the only question is
    what is the use of "detach()"?

  • Can we create a cost element for a Balance Sheet account?

    Hi folks,
    Is it possible to create a cost element for a balance sheet account? If yes, what are the scenerios we would need it and how is it done?
    thanks in advance

    Hello
    Please review the below information regarding cost elements category 90 : Financial Accounting Balance Sheet Accounts                                                                               
    Category 90  is automatically assigned when you create cost elements in CO whose   general ledger accounts in FI are asset reconciliation accounts            
    (special balance sheet accounts), not income statement accounts. You       
    cannot change this category in CO master data maintenance.                                                                               
    FI does not require CO account assignments to cost elements of             
    category 90. However, if you enter an account assignment, it is only       
    recorded statistically for real objects.                                                                               
    Category 90 allows you to check order or project budgets for fixed         
    asset procurement. To do so, enter the investment order or WBS element     
    in the corresponding field in the asset master. The Asset Management       
    component ensures that the order or element automatically appears in       
    the document when you access the asset procurement.                        
    The R/3 System debits the order/WBS element statistically in the           
    Controlling component, which you can then monitor with availability        
    control.                                                                   
    You can treat cost elements of category 90 as activity-independent as      
    part of cost center planning. 
    Also see note 75980  for further information.  From the note:
      The use of cost element category 90 is only provided in the standard        
      system in the following two cases:                                                                               
    1.  As of Release 3.0G, asset acquisitions and down payments which are      
          assigned directly to a fixed asset or asset under construction can      
          be assigned to an account on internal orders or WBS elements            
          statistically. In this manner, for example, an availability check       
          can be triggered on the order or the WBS element for asset posting.                                                                               
    2.  As of Release 4.0, cost elements of category 90 can also be created     
          for material stock accounts to display material make-to-order stocks    
          on sales orders or customer projects.                                   
    Regards
    Javier Reviriego

  • JSF Iterator Component

    I was looking for a quick solution for a JSF iterator, because i dont want to use the h:dataTable i have to write my own component, and here is what i came up with.
    public class JSFUIDataIterator extends UIData{
        public void encodeChildren(FacesContext oContext) throws IOException {
          if (oContext == null){
            throw new NullPointerException();
          int iProcessed = 0;
          int iRowIndex = getFirst() - 1;
          int iRows = getRows();
          Iterator oKids = getChildren(this);
          do{
            if(iRows > 0 && ++iProcessed > iRows)
              break;
            setRowIndex(++iRowIndex);
            if (!isRowAvailable())
              break;
            for(; oKids.hasNext();){
              UIComponent oKid = (UIComponent)oKids.next(); 
              encodeRecursive(oContext,oKid);
          } while(true);
        protected Iterator getChildren(UIComponent oComponent){
            List oResults = new ArrayList();
            for(Iterator oKids = oComponent.getChildren().iterator(); oKids.hasNext();){
              UIComponent oKid = (UIComponent)oKids.next();
              if(oKid.isRendered())
                 oResults.add(oKid);
            return oResults.iterator();
        private void encodeRecursive(FacesContext oContext,UIComponent oComponent) throws IOException{
           if (!oComponent.isRendered()){
             return; 
           oComponent.encodeBegin(oContext);
           if (oComponent.getRendersChildren()){
             oComponent.encodeChildren(oContext);
           else{
             Iterator oChildren = getChildren(oComponent);
             for(;oChildren.hasNext();){
               UIComponent oChildComponent = (UIComponent)oChildren.next();
               encodeRecursive(oContext,oChildComponent);
           oComponent.encodeEnd(oContext);
    }not want to be bothered by creating a renderer this component will render itself, but there is a problem, even though its iterating all the data elements its displaying the first data item. i missed something minor that i cant figure out. can anyone help?

    I haven't got a reply so i went to look at my code again, and i managed to identify the problem.
    I hope this code will help all those who want to use the iterator tag in JSF.
    this simple custom component will give you more control over your data elements
    here is the code for the custom component.
      public class DataIterator extends UIData{
        public void encodeChildren(FacesContext oContext) throws IOException {
          if (oContext == null){
            throw new NullPointerException();
          int iProcessed = 0;
          int iRowIndex = getFirst() - 1;
          int iRows = getRows();
          do{
            if(iRows > 0 && ++iProcessed > iRows)
              break;
            setRowIndex(++iRowIndex);
            if (!isRowAvailable())
              break;
            Iterator oKids = getChildren(this);
            for(; oKids.hasNext();){
              UIComponent oKid = (UIComponent)oKids.next(); 
              encodeRecursive(oContext,oKid);
          } while(true);
        protected Iterator getChildren(UIComponent oComponent){
            List oResults = new ArrayList();
            for(Iterator oKids = oComponent.getChildren().iterator(); oKids.hasNext();){
              UIComponent oKid = (UIComponent)oKids.next();
              if(oKid.isRendered())
                 oResults.add(oKid);
            return oResults.iterator();
        private void encodeRecursive(FacesContext oContext,UIComponent oComponent) throws IOException{
           if (!oComponent.isRendered()){
             return; 
           oComponent.encodeBegin(oContext);
           if (oComponent.getRendersChildren()){
             oComponent.encodeChildren(oContext);
           else{
             Iterator oChildren = getChildren(oComponent);
             for(;oChildren.hasNext();){
               UIComponent oChildComponent = (UIComponent)oChildren.next();
               encodeRecursive(oContext,oChildComponent);
           oComponent.encodeEnd(oContext);
      }you only need these three methods in your component, i have stripped out logging and comments to keep the size of this post smaller, the rest is pretty straight forward.
    you need a CustomTag class for the component and it should at least take two attributes : items and var.
    your tag library should look something like this:
        <name>forEach</name>
        <tag-class>myjsf.DataIteratorTag</tag-class>
        <body-content>JSP</body-content>
        <attribute>
          <name>items</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
          <type>java.lang.String</type>
        </attribute>
        <attribute>
          <name>var</name>
          <required>true</required>
          <rtexprvalue>false</rtexprvalue>
          <type>java.lang.String</type>
        </attribute>in the jsp page here is my sample file:
    <%@taglib uri="/WEB-INF/data-iterator.tld" prefix="tbc" %>
       <faces:view>
         <faces:verbatim>
           <table>
         </faces:verbatim>
         <tbc:forEach items="#{myCollection.musicTitles}" var="oRow">
          <faces:verbatim>
            <tr style="background-color:#EEEEEE;">
              <td>
          </faces:verbatim>
          <html:outputText value="#{oRow}"/>
         <faces:verbatim>
              </td>
            </tr>
         </faces:verbatim>
         </tbc:forEach>
         <faces:verbatim>
           </table>
         </faces:verbatim>

  • Move xml elements

    Hi,
       I need to create parent element and need to move selected elements into tat.  when doing this, paragraph style getting changed.  Dono wats my mistake there.
    Code :
    AddParentTag(app.selection,"row", elm)
    function AddParentTag(mySel, tagName, parentTg)
            mySel   -   Selection of multiple tags
            tagName -   Name of the parent tag
        var parnt = null;
        if(mySel.length > 0)
             parnt = parentTg.xmlElements.add({markupTag:tagName}).move(LocationOptions.before, mySel[0]);    
            var i = mySel.length;
            if(parnt != null)
                while(i--){    
                    var resTg = mySel[i].move(LocationOptions.AT_END, parnt);                                  
    I want to move the elements without changing style(pstyle) of the contents. Can anyone help me?
    - Sudha K

    I've done some thing like below:
    var Doc = app.activeDocument;
    var Root = Doc.xmlElements.item(0);
    var startElement = [];
    var listElements = ElementsArray()
    var Body = Root.xmlElements.add("body")
    var che = Body.xmlElements.add("ref")
    for(var k=0; k<listElements.length; k++){
            Root.xmlElements.item(listElements[k]).move(LocationOptions.after, )
    function ElementsArray()
        for(var i=1; i<Root.xmlElements.length; i++)
           if(Root.xmlElements[i].markupTag.name =="start")
               var myStartElement = Root.xmlElements[i].markupTag.name
                for(var j=i; j<Root.xmlElements.length; j++){
                    startElement.push (Root.xmlElements[j].markupTag.name)
                     if(Root.xmlElements[j].markupTag.name == "end")
                     return startElement;               
    But here I am getting couple of issue.
    when I use loop to move xml elements it moves all the emements with item name in single iteration So I loose element position while I need to preserve the element position also.
    For reference purpose I have to create an element "ref". since without reference xmlElement can not be moved inside the other elements. Please suggest if there any other way to move the elements.
    Also it throughs an error while moving elements since listElement array contains a number of elements which are already moved

  • Best Way To transfer screen elements to ABAP variables

    Hi all,
    whats the best way to attach the abap elements to screen elements
    normally earlier versions before 4.7C i always used TABLES : MARC in abap program
    and in screen design i used to click "GET from DICTIONARY" to design the screen in Screen painter
    The advantage with this approach is all data base elements are attached to our screens like search helps
    atomatic checks etc and more over all the information valid for a particular plant are retrived by the system search helps themselves like
    for example on the screen we have screen elements/ fields  Plant , MRP controller.
    in the plant i typed  "X110'.
    now in the mrp controller i pressed F4 to search for valid mrp controller . Since we associated the screen elements with database elements with TABLES statement all the MRP controller relevent to that plant X110 are displayed. this is quite valid.
    But i read usage of tables : in Object Oriented abap is Obsolete is this still the correct way of programming.
    I can also use Some thing like this Data : st_marc type type MARC.
    and in Screen design i can click "Get from program" This approach will loose all the database assignments to screen elements.
    Now i can no longer retrieve the MRP controller relevent for plant 'X110'. F4 will show me all the MRP controllers in all plants.
    Is there any other approach to do this. Thanks.
    Edited by: Kavitha on Mar 13, 2008 2:37 PM

    Please read the following two links. These experts explain it better than I could put in words!:
    /people/thomas.jung3/blog/2005/09/08/oo-abap-dynpro-programming
    /people/horst.keller/blog/2007/04/24/from-abap-ipo-to-abap-objects-and-the-separation-of-concerns
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/4fbafc9e-0e01-0010-dea9-9d23d1b269fb  (Under section Modularizing your programs)

  • Enumeration vs Iterator

    Please,
    what is the difference between iterator and enumeration? Iterator should be more better designed, but I don't note that difference.

    Iterator vs. Enumeration
    Round 1: Typing
    "Iterator" has fewer letters than "Enumeration" (Point to Iterator)
    Iterator's methods have fewer letters than Enumeration's methods (Point to Iterator)
    Round 2: Power
    Iterator advertises the ability to remove from the iterated collection the last element that has been returned. Enumeration has no facility to do that. (Point to Iterator)
    Iterator has been extended within the Java platform (see ListIterator) to advertise the ability to move forward or backward through the iterated collection. (Point to Iterator)
    This extension can also add an element to the collection and change the value of the last element returned within the collection. (Point to Iterator)
    Iterator is integrated into the Collections framework. Enumeration is peripheral to the framework and has been awkwardly inserted to provide backwards compatability to Dinosaur-aged programs. (Point to Iterator)
    Lexographically speaking, Enumeration comes before Iterator. (Point to Enumeration).
    Tally up the score. You be the judge :-)

  • My implementation of an iterator class

    I implement my own iterator class, which provides a few methods for the user to get data, and once the end of the iterator is reached, I can release the memory. How does it look?
    import java.util.LinkedList;
    public class MyIterator {
        private Object[] list;
        private int size;
        private int cursor;
        public MyIterator(LinkedList inList) {
            size = inList.size();
            list = Object[size];
            for(int i=0;i<size;i++){
                list[i] = (Object) inList.removeFirst();
            cursor = 0;
    //check how many more items are available
        public int max_left() {
            return size - cursor;
    //get the next n
        public Object[] next_n(int how_many) {
            if( cursor == size ){
                return null;
            Object[] newList = Object[how_many];
            int temp = cursor;
            for(int i=0;i<how_many;i++){
                if( cursor < size ){
                    newList[i] = list[cursor++];
            checkCursor();
            return newList;
    //get the next one
        public boolean next_one() {
            if( cursor < size ){
                next.value = list[cursor++];
                checkCursor();
                return true;
            return false;
        //  if the cursor has already reached the end of the list, release the list memory
        public void checkCursor(){
            if( cursor == size ){
                list = null;
    }

    Hi,
    It looks very strange. I didn't look at the whole code, but why do you want an iterator that removes all elements from the original list when you create the iterator?
    list[i] = (Object) inList.removeFirst();/Kaj

Maybe you are looking for