ConcurrentModificationException when trying to replace XWPFHyperlink for XWPFRun









up vote
1
down vote

favorite












I am trying to replace a string pattern for another one with hyperlink, but I am getting java.util.ConcurrentModificationException. The lines of code which the error is pointing don't make sense, so I wasn't able to find out what happened.



 // Replace occurrences in all paragraphs
for (XWPFParagraph p : doc_buffer.getParagraphs())
List<XWPFRun> p_runs = p.getRuns();
if (p_runs != null)
for (XWPFRun r : p_runs)
String text = r.getText(0);
if ((text != null) && (text.contains(pattern)))
if (pattern.equals("LINK_TO_DOCS"))
//TODO
String h_url = "http://example.com/linktodocs/";
String h_text = replacement;

// Creates the link as an external relationship
XWPFParagraph temp_p = doc_buffer.createParagraph();
String id = temp_p.getDocument().getPackagePart().addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

// Binds the link to the relationship
CTHyperlink link = temp_p.getCTP().addNewHyperlink();
link.setId(id);

// Creates the linked text
CTText linked_text = CTText.Factory.newInstance();
linked_text.setStringValue(h_text);

// Creates a wordprocessing Run wrapper
CTR ctr = CTR.Factory.newInstance();
ctr.setTArray(new CTText linked_text);
link.setRArray(new CTR ctr);

r = new XWPFHyperlinkRun(link, r.getCTR(), r.getParent());

else
text = text.replaceAll(pattern, replacement);
r.setText(text, 0);








Console error:



Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)
at releasenotes.ReleaseNotesUpdater.replaceAllOccurrences(ReleaseNotesUpdater.java:263)
at releasenotes.ReleaseNotesUpdater.main(ReleaseNotesUpdater.java:85)


Also, besides this error, I also would like some advice about how can I replace a string pattern for another one with hyperlink. I have searched but I am a bit confused about how it works.




Edit.:
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)



 public Iterator<E> iterator() 
return new Iterator<E>()
private final Iterator<? extends E> i = c.iterator();

public boolean hasNext() return i.hasNext();
public E next() return i.next();
public void remove()
throw new UnsupportedOperationException();

@Override
public void forEachRemaining(Consumer<? super E> action)
// Use backing collection version
i.forEachRemaining(action);

;



at java.util.ArrayList$Itr.next(ArrayList.java:859)



 @SuppressWarnings("unchecked")
public E next()
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];



at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)



 final void checkForComodification() 
if (modCount != expectedModCount)
throw new ConcurrentModificationException();










share|improve this question



















  • 1




    Post more of your stacktrace and point out the line of code that is causing the error
    – Sedrick
    Nov 9 at 16:54










  • Have you used Arrays.asList(...) anywhere?
    – Sedrick
    Nov 9 at 16:56






  • 1




    How to create a Minimal, Complete, and Verifiable example.
    – Sedrick
    Nov 9 at 17:10






  • 1




    The size of the project has nothing to do with creating an MCVE. I have had plenty of large projects that I was able to create an MCVE from.
    – Sedrick
    Nov 9 at 17:14







  • 1




    Then I will just wait for someone else's opinion about the way I am doing what I am trying to, and while this I gotta research a bit more. Thanks for your time.
    – Leonardo
    Nov 9 at 17:16














up vote
1
down vote

favorite












I am trying to replace a string pattern for another one with hyperlink, but I am getting java.util.ConcurrentModificationException. The lines of code which the error is pointing don't make sense, so I wasn't able to find out what happened.



 // Replace occurrences in all paragraphs
for (XWPFParagraph p : doc_buffer.getParagraphs())
List<XWPFRun> p_runs = p.getRuns();
if (p_runs != null)
for (XWPFRun r : p_runs)
String text = r.getText(0);
if ((text != null) && (text.contains(pattern)))
if (pattern.equals("LINK_TO_DOCS"))
//TODO
String h_url = "http://example.com/linktodocs/";
String h_text = replacement;

// Creates the link as an external relationship
XWPFParagraph temp_p = doc_buffer.createParagraph();
String id = temp_p.getDocument().getPackagePart().addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

// Binds the link to the relationship
CTHyperlink link = temp_p.getCTP().addNewHyperlink();
link.setId(id);

// Creates the linked text
CTText linked_text = CTText.Factory.newInstance();
linked_text.setStringValue(h_text);

// Creates a wordprocessing Run wrapper
CTR ctr = CTR.Factory.newInstance();
ctr.setTArray(new CTText linked_text);
link.setRArray(new CTR ctr);

r = new XWPFHyperlinkRun(link, r.getCTR(), r.getParent());

else
text = text.replaceAll(pattern, replacement);
r.setText(text, 0);








Console error:



Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)
at releasenotes.ReleaseNotesUpdater.replaceAllOccurrences(ReleaseNotesUpdater.java:263)
at releasenotes.ReleaseNotesUpdater.main(ReleaseNotesUpdater.java:85)


Also, besides this error, I also would like some advice about how can I replace a string pattern for another one with hyperlink. I have searched but I am a bit confused about how it works.




Edit.:
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)



 public Iterator<E> iterator() 
return new Iterator<E>()
private final Iterator<? extends E> i = c.iterator();

public boolean hasNext() return i.hasNext();
public E next() return i.next();
public void remove()
throw new UnsupportedOperationException();

@Override
public void forEachRemaining(Consumer<? super E> action)
// Use backing collection version
i.forEachRemaining(action);

;



at java.util.ArrayList$Itr.next(ArrayList.java:859)



 @SuppressWarnings("unchecked")
public E next()
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];



at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)



 final void checkForComodification() 
if (modCount != expectedModCount)
throw new ConcurrentModificationException();










share|improve this question



















  • 1




    Post more of your stacktrace and point out the line of code that is causing the error
    – Sedrick
    Nov 9 at 16:54










  • Have you used Arrays.asList(...) anywhere?
    – Sedrick
    Nov 9 at 16:56






  • 1




    How to create a Minimal, Complete, and Verifiable example.
    – Sedrick
    Nov 9 at 17:10






  • 1




    The size of the project has nothing to do with creating an MCVE. I have had plenty of large projects that I was able to create an MCVE from.
    – Sedrick
    Nov 9 at 17:14







  • 1




    Then I will just wait for someone else's opinion about the way I am doing what I am trying to, and while this I gotta research a bit more. Thanks for your time.
    – Leonardo
    Nov 9 at 17:16












up vote
1
down vote

favorite









up vote
1
down vote

favorite











I am trying to replace a string pattern for another one with hyperlink, but I am getting java.util.ConcurrentModificationException. The lines of code which the error is pointing don't make sense, so I wasn't able to find out what happened.



 // Replace occurrences in all paragraphs
for (XWPFParagraph p : doc_buffer.getParagraphs())
List<XWPFRun> p_runs = p.getRuns();
if (p_runs != null)
for (XWPFRun r : p_runs)
String text = r.getText(0);
if ((text != null) && (text.contains(pattern)))
if (pattern.equals("LINK_TO_DOCS"))
//TODO
String h_url = "http://example.com/linktodocs/";
String h_text = replacement;

// Creates the link as an external relationship
XWPFParagraph temp_p = doc_buffer.createParagraph();
String id = temp_p.getDocument().getPackagePart().addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

// Binds the link to the relationship
CTHyperlink link = temp_p.getCTP().addNewHyperlink();
link.setId(id);

// Creates the linked text
CTText linked_text = CTText.Factory.newInstance();
linked_text.setStringValue(h_text);

// Creates a wordprocessing Run wrapper
CTR ctr = CTR.Factory.newInstance();
ctr.setTArray(new CTText linked_text);
link.setRArray(new CTR ctr);

r = new XWPFHyperlinkRun(link, r.getCTR(), r.getParent());

else
text = text.replaceAll(pattern, replacement);
r.setText(text, 0);








Console error:



Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)
at releasenotes.ReleaseNotesUpdater.replaceAllOccurrences(ReleaseNotesUpdater.java:263)
at releasenotes.ReleaseNotesUpdater.main(ReleaseNotesUpdater.java:85)


Also, besides this error, I also would like some advice about how can I replace a string pattern for another one with hyperlink. I have searched but I am a bit confused about how it works.




Edit.:
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)



 public Iterator<E> iterator() 
return new Iterator<E>()
private final Iterator<? extends E> i = c.iterator();

public boolean hasNext() return i.hasNext();
public E next() return i.next();
public void remove()
throw new UnsupportedOperationException();

@Override
public void forEachRemaining(Consumer<? super E> action)
// Use backing collection version
i.forEachRemaining(action);

;



at java.util.ArrayList$Itr.next(ArrayList.java:859)



 @SuppressWarnings("unchecked")
public E next()
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];



at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)



 final void checkForComodification() 
if (modCount != expectedModCount)
throw new ConcurrentModificationException();










share|improve this question















I am trying to replace a string pattern for another one with hyperlink, but I am getting java.util.ConcurrentModificationException. The lines of code which the error is pointing don't make sense, so I wasn't able to find out what happened.



 // Replace occurrences in all paragraphs
for (XWPFParagraph p : doc_buffer.getParagraphs())
List<XWPFRun> p_runs = p.getRuns();
if (p_runs != null)
for (XWPFRun r : p_runs)
String text = r.getText(0);
if ((text != null) && (text.contains(pattern)))
if (pattern.equals("LINK_TO_DOCS"))
//TODO
String h_url = "http://example.com/linktodocs/";
String h_text = replacement;

// Creates the link as an external relationship
XWPFParagraph temp_p = doc_buffer.createParagraph();
String id = temp_p.getDocument().getPackagePart().addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

// Binds the link to the relationship
CTHyperlink link = temp_p.getCTP().addNewHyperlink();
link.setId(id);

// Creates the linked text
CTText linked_text = CTText.Factory.newInstance();
linked_text.setStringValue(h_text);

// Creates a wordprocessing Run wrapper
CTR ctr = CTR.Factory.newInstance();
ctr.setTArray(new CTText linked_text);
link.setRArray(new CTR ctr);

r = new XWPFHyperlinkRun(link, r.getCTR(), r.getParent());

else
text = text.replaceAll(pattern, replacement);
r.setText(text, 0);








Console error:



Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)
at releasenotes.ReleaseNotesUpdater.replaceAllOccurrences(ReleaseNotesUpdater.java:263)
at releasenotes.ReleaseNotesUpdater.main(ReleaseNotesUpdater.java:85)


Also, besides this error, I also would like some advice about how can I replace a string pattern for another one with hyperlink. I have searched but I am a bit confused about how it works.




Edit.:
at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042)



 public Iterator<E> iterator() 
return new Iterator<E>()
private final Iterator<? extends E> i = c.iterator();

public boolean hasNext() return i.hasNext();
public E next() return i.next();
public void remove()
throw new UnsupportedOperationException();

@Override
public void forEachRemaining(Consumer<? super E> action)
// Use backing collection version
i.forEachRemaining(action);

;



at java.util.ArrayList$Itr.next(ArrayList.java:859)



 @SuppressWarnings("unchecked")
public E next()
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];



at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)



 final void checkForComodification() 
if (modCount != expectedModCount)
throw new ConcurrentModificationException();







java apache-poi xwpf






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 17:07

























asked Nov 9 at 16:37









Leonardo

388




388







  • 1




    Post more of your stacktrace and point out the line of code that is causing the error
    – Sedrick
    Nov 9 at 16:54










  • Have you used Arrays.asList(...) anywhere?
    – Sedrick
    Nov 9 at 16:56






  • 1




    How to create a Minimal, Complete, and Verifiable example.
    – Sedrick
    Nov 9 at 17:10






  • 1




    The size of the project has nothing to do with creating an MCVE. I have had plenty of large projects that I was able to create an MCVE from.
    – Sedrick
    Nov 9 at 17:14







  • 1




    Then I will just wait for someone else's opinion about the way I am doing what I am trying to, and while this I gotta research a bit more. Thanks for your time.
    – Leonardo
    Nov 9 at 17:16












  • 1




    Post more of your stacktrace and point out the line of code that is causing the error
    – Sedrick
    Nov 9 at 16:54










  • Have you used Arrays.asList(...) anywhere?
    – Sedrick
    Nov 9 at 16:56






  • 1




    How to create a Minimal, Complete, and Verifiable example.
    – Sedrick
    Nov 9 at 17:10






  • 1




    The size of the project has nothing to do with creating an MCVE. I have had plenty of large projects that I was able to create an MCVE from.
    – Sedrick
    Nov 9 at 17:14







  • 1




    Then I will just wait for someone else's opinion about the way I am doing what I am trying to, and while this I gotta research a bit more. Thanks for your time.
    – Leonardo
    Nov 9 at 17:16







1




1




Post more of your stacktrace and point out the line of code that is causing the error
– Sedrick
Nov 9 at 16:54




Post more of your stacktrace and point out the line of code that is causing the error
– Sedrick
Nov 9 at 16:54












Have you used Arrays.asList(...) anywhere?
– Sedrick
Nov 9 at 16:56




Have you used Arrays.asList(...) anywhere?
– Sedrick
Nov 9 at 16:56




1




1




How to create a Minimal, Complete, and Verifiable example.
– Sedrick
Nov 9 at 17:10




How to create a Minimal, Complete, and Verifiable example.
– Sedrick
Nov 9 at 17:10




1




1




The size of the project has nothing to do with creating an MCVE. I have had plenty of large projects that I was able to create an MCVE from.
– Sedrick
Nov 9 at 17:14





The size of the project has nothing to do with creating an MCVE. I have had plenty of large projects that I was able to create an MCVE from.
– Sedrick
Nov 9 at 17:14





1




1




Then I will just wait for someone else's opinion about the way I am doing what I am trying to, and while this I gotta research a bit more. Thanks for your time.
– Leonardo
Nov 9 at 17:16




Then I will just wait for someone else's opinion about the way I am doing what I am trying to, and while this I gotta research a bit more. Thanks for your time.
– Leonardo
Nov 9 at 17:16












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










I have found the solution so I am sharing if anyone has the same trouble.



To replace a common run with a Hyperlink run, simply do the following:



 String h_url = "http://example.com/index.html";
String h_text = replacement;

// Creates the link as an external relationship
String id = r.getDocument().getPackagePart()
.addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

// Binds the link to the relationship
CTHyperlink link = r.getParagraph().getCTP().addNewHyperlink();
link.setId(id);

// Creates the linked text
CTText linked_text = CTText.Factory.newInstance();
linked_text.setStringValue(h_text);

// Creates a XML wordprocessing wrapper for Run
// The magic is here
CTR ctr = r.getCTR();
ctr.setTArray(new CTText linked_text );

// Stylizing
CTRPr rpr_c = ctr.addNewRPr();
CTColor color = CTColor.Factory.newInstance();
color.setVal("0000FF");
rpr_c.setColor(color);

CTRPr rpr_u = ctr.addNewRPr();
rpr_u.addNewU().setVal(STUnderline.SINGLE);


The code above is inside a loop which is iterating over all runs in a paragraph (r is the current run). So you just have to call r.getCTR() to be able to edit the run.



The reason why the exception was happening, was because I was trying to modify the document structure while going through it in this line:



 XWPFParagraph temp_p = doc_buffer.createParagraph();


If anyone has questions, feel free to ask in the comments.






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229817%2fconcurrentmodificationexception-when-trying-to-replace-xwpfhyperlink-for-xwpfrun%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    I have found the solution so I am sharing if anyone has the same trouble.



    To replace a common run with a Hyperlink run, simply do the following:



     String h_url = "http://example.com/index.html";
    String h_text = replacement;

    // Creates the link as an external relationship
    String id = r.getDocument().getPackagePart()
    .addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

    // Binds the link to the relationship
    CTHyperlink link = r.getParagraph().getCTP().addNewHyperlink();
    link.setId(id);

    // Creates the linked text
    CTText linked_text = CTText.Factory.newInstance();
    linked_text.setStringValue(h_text);

    // Creates a XML wordprocessing wrapper for Run
    // The magic is here
    CTR ctr = r.getCTR();
    ctr.setTArray(new CTText linked_text );

    // Stylizing
    CTRPr rpr_c = ctr.addNewRPr();
    CTColor color = CTColor.Factory.newInstance();
    color.setVal("0000FF");
    rpr_c.setColor(color);

    CTRPr rpr_u = ctr.addNewRPr();
    rpr_u.addNewU().setVal(STUnderline.SINGLE);


    The code above is inside a loop which is iterating over all runs in a paragraph (r is the current run). So you just have to call r.getCTR() to be able to edit the run.



    The reason why the exception was happening, was because I was trying to modify the document structure while going through it in this line:



     XWPFParagraph temp_p = doc_buffer.createParagraph();


    If anyone has questions, feel free to ask in the comments.






    share|improve this answer
























      up vote
      0
      down vote



      accepted










      I have found the solution so I am sharing if anyone has the same trouble.



      To replace a common run with a Hyperlink run, simply do the following:



       String h_url = "http://example.com/index.html";
      String h_text = replacement;

      // Creates the link as an external relationship
      String id = r.getDocument().getPackagePart()
      .addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

      // Binds the link to the relationship
      CTHyperlink link = r.getParagraph().getCTP().addNewHyperlink();
      link.setId(id);

      // Creates the linked text
      CTText linked_text = CTText.Factory.newInstance();
      linked_text.setStringValue(h_text);

      // Creates a XML wordprocessing wrapper for Run
      // The magic is here
      CTR ctr = r.getCTR();
      ctr.setTArray(new CTText linked_text );

      // Stylizing
      CTRPr rpr_c = ctr.addNewRPr();
      CTColor color = CTColor.Factory.newInstance();
      color.setVal("0000FF");
      rpr_c.setColor(color);

      CTRPr rpr_u = ctr.addNewRPr();
      rpr_u.addNewU().setVal(STUnderline.SINGLE);


      The code above is inside a loop which is iterating over all runs in a paragraph (r is the current run). So you just have to call r.getCTR() to be able to edit the run.



      The reason why the exception was happening, was because I was trying to modify the document structure while going through it in this line:



       XWPFParagraph temp_p = doc_buffer.createParagraph();


      If anyone has questions, feel free to ask in the comments.






      share|improve this answer






















        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        I have found the solution so I am sharing if anyone has the same trouble.



        To replace a common run with a Hyperlink run, simply do the following:



         String h_url = "http://example.com/index.html";
        String h_text = replacement;

        // Creates the link as an external relationship
        String id = r.getDocument().getPackagePart()
        .addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

        // Binds the link to the relationship
        CTHyperlink link = r.getParagraph().getCTP().addNewHyperlink();
        link.setId(id);

        // Creates the linked text
        CTText linked_text = CTText.Factory.newInstance();
        linked_text.setStringValue(h_text);

        // Creates a XML wordprocessing wrapper for Run
        // The magic is here
        CTR ctr = r.getCTR();
        ctr.setTArray(new CTText linked_text );

        // Stylizing
        CTRPr rpr_c = ctr.addNewRPr();
        CTColor color = CTColor.Factory.newInstance();
        color.setVal("0000FF");
        rpr_c.setColor(color);

        CTRPr rpr_u = ctr.addNewRPr();
        rpr_u.addNewU().setVal(STUnderline.SINGLE);


        The code above is inside a loop which is iterating over all runs in a paragraph (r is the current run). So you just have to call r.getCTR() to be able to edit the run.



        The reason why the exception was happening, was because I was trying to modify the document structure while going through it in this line:



         XWPFParagraph temp_p = doc_buffer.createParagraph();


        If anyone has questions, feel free to ask in the comments.






        share|improve this answer












        I have found the solution so I am sharing if anyone has the same trouble.



        To replace a common run with a Hyperlink run, simply do the following:



         String h_url = "http://example.com/index.html";
        String h_text = replacement;

        // Creates the link as an external relationship
        String id = r.getDocument().getPackagePart()
        .addExternalRelationship(h_url, XWPFRelation.HYPERLINK.getRelation()).getId();

        // Binds the link to the relationship
        CTHyperlink link = r.getParagraph().getCTP().addNewHyperlink();
        link.setId(id);

        // Creates the linked text
        CTText linked_text = CTText.Factory.newInstance();
        linked_text.setStringValue(h_text);

        // Creates a XML wordprocessing wrapper for Run
        // The magic is here
        CTR ctr = r.getCTR();
        ctr.setTArray(new CTText linked_text );

        // Stylizing
        CTRPr rpr_c = ctr.addNewRPr();
        CTColor color = CTColor.Factory.newInstance();
        color.setVal("0000FF");
        rpr_c.setColor(color);

        CTRPr rpr_u = ctr.addNewRPr();
        rpr_u.addNewU().setVal(STUnderline.SINGLE);


        The code above is inside a loop which is iterating over all runs in a paragraph (r is the current run). So you just have to call r.getCTR() to be able to edit the run.



        The reason why the exception was happening, was because I was trying to modify the document structure while going through it in this line:



         XWPFParagraph temp_p = doc_buffer.createParagraph();


        If anyone has questions, feel free to ask in the comments.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 11:59









        Leonardo

        388




        388



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229817%2fconcurrentmodificationexception-when-trying-to-replace-xwpfhyperlink-for-xwpfrun%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

            Syphilis

            Darth Vader #20