@Override
 protected void saveFromKitToStream(StyledDocument doc, EditorKit kit, OutputStream out)
     throws IOException, BadLocationException {
   // Detect the encoding, using UTF8 if the encoding is not set.
   String enc = EncodingUtil.detectEncoding(doc);
   if (enc == null) {
     enc = "UTF8"; // NOI18N
   }
   try {
     // Test the encoding on a dummy stream.
     new OutputStreamWriter(new ByteArrayOutputStream(1), enc);
     // If that worked, we can go ahead with the encoding.
     Writer writer = new OutputStreamWriter(out, enc);
     kit.write(writer, doc, 0, doc.getLength());
   } catch (UnsupportedEncodingException uee) {
     // Safest option is to write nothing, preserving the original file.
     IOException ioex = new IOException("Unsupported encoding " + enc); // NOI18N
     ErrorManager.getDefault()
         .annotate(
             ioex,
             NbBundle.getMessage(
                 WadlEditorSupport.class, "MSG_WadlEditorSupport_Unsupported_Encoding", enc));
     throw ioex;
   }
 }
 @Override
 protected void loadFromStreamToKit(StyledDocument doc, InputStream in, EditorKit kit)
     throws IOException, BadLocationException {
   // Detect the encoding to get optimized reader if UTF-8.
   String enc = EncodingUtil.detectEncoding(in);
   if (enc == null) {
     enc = "UTF8"; // NOI18N
   }
   try {
     Reader reader = new InputStreamReader(in, enc);
     kit.read(reader, doc, 0);
   } catch (CharConversionException cce) {
   } catch (UnsupportedEncodingException uee) {
   }
 }
  /*
   * Save document using encoding declared in XML prolog if possible otherwise
   * at UTF-8 (in such case it updates the prolog).
   */
  public void saveDocument() throws java.io.IOException {
    final javax.swing.text.StyledDocument doc = getDocument();
    String defaultEncoding = "UTF-8"; // NOI18N
    // dependency on xml/core
    String enc = EncodingUtil.detectEncoding(doc);
    boolean changeEncodingToDefault = false;
    if (enc == null) enc = defaultEncoding;

    // test encoding
    if (!isSupportedEncoding(enc)) {
      NotifyDescriptor nd =
          new NotifyDescriptor.Confirmation(
              NbBundle.getMessage(
                  StrutsConfigEditorSupport.class,
                  "MSG_BadEncodingDuringSave", // NOI18N
                  new Object[] {
                    getDataObject().getPrimaryFile().getNameExt(), enc, defaultEncoding
                  }),
              NotifyDescriptor.YES_NO_OPTION,
              NotifyDescriptor.WARNING_MESSAGE);
      nd.setValue(NotifyDescriptor.NO_OPTION);
      DialogDisplayer.getDefault().notify(nd);
      if (nd.getValue() != NotifyDescriptor.YES_OPTION) return;
      changeEncodingToDefault = true;
    }

    if (!changeEncodingToDefault) {
      // is it possible to save the document in the encoding?
      try {
        java.nio.charset.CharsetEncoder coder = java.nio.charset.Charset.forName(enc).newEncoder();
        if (!coder.canEncode(doc.getText(0, doc.getLength()))) {
          NotifyDescriptor nd =
              new NotifyDescriptor.Confirmation(
                  NbBundle.getMessage(
                      StrutsConfigEditorSupport.class,
                      "MSG_BadCharConversion", // NOI18N
                      new Object[] {getDataObject().getPrimaryFile().getNameExt(), enc}),
                  NotifyDescriptor.YES_NO_OPTION,
                  NotifyDescriptor.WARNING_MESSAGE);
          nd.setValue(NotifyDescriptor.NO_OPTION);
          DialogDisplayer.getDefault().notify(nd);
          if (nd.getValue() != NotifyDescriptor.YES_OPTION) return;
        }
      } catch (javax.swing.text.BadLocationException e) {
        Logger.getLogger("global").log(Level.INFO, null, e);
      }
      super.saveDocument();
      // moved from Env.save()
      getDataObject().setModified(false);
    } else {
      // update prolog to new valid encoding

      try {
        final int MAX_PROLOG = 1000;
        int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());
        final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
        int prologLen = 0; // actual prolog length

        // parse prolog and get prolog end
        if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {

          // look for delimitting ?>
          for (int i = 3; i < maxPrologLen; i++) {
            if (prolog[i] == '?' && prolog[i + 1] == '>') {
              prologLen = i + 1;
              break;
            }
          }
        }

        final int passPrologLen = prologLen;

        Runnable edit =
            new Runnable() {
              public void run() {
                try {

                  doc.remove(0, passPrologLen + 1); // +1 it removes exclusive
                  doc.insertString(
                      0,
                      "<?xml version='1.0' encoding='UTF-8' ?> \n<!-- was: "
                          + new String(prolog, 0, passPrologLen + 1)
                          + " -->",
                      null); // NOI18N

                } catch (BadLocationException e) {
                  if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                  e.printStackTrace();
                }
              }
            };

        NbDocument.runAtomic(doc, edit);

        super.saveDocument();
        // moved from Env.save()
        getDataObject().setModified(false);
      } catch (javax.swing.text.BadLocationException e) {
        Logger.getLogger("global").log(Level.INFO, null, e);
      }
    }
  }
  @Override
  public void saveDocument() throws IOException {
    final StyledDocument doc = getDocument();
    // Save document using encoding declared in XML prolog if possible,
    // otherwise use UTF-8 (in such case it updates the prolog).
    String enc = EncodingUtil.detectEncoding(doc);
    if (enc == null) {
      enc = "UTF8"; // NOI18N
    }
    try {
      // Test the encoding on a dummy stream.
      new OutputStreamWriter(new ByteArrayOutputStream(1), enc);
      if (!checkCharsetConversion(Convertors.java2iana(enc))) {
        return;
      }
      super.saveDocument();
      getDataObject().setModified(false);

    } catch (UnsupportedEncodingException uee) {
      NotifyDescriptor descriptor =
          new NotifyDescriptor.Confirmation(
              java.text.MessageFormat.format(
                  NbBundle.getMessage(WadlEditorSupport.class, "MSG_WadlEditorSupport_Use_UTF8"),
                  new Object[] {enc}));
      Object res = DialogDisplayer.getDefault().notify(descriptor);

      if (res.equals(NotifyDescriptor.YES_OPTION)) {
        // Update prolog to new valid encoding.
        try {
          final int MAX_PROLOG = 1000;
          int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());
          final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
          int prologLen = 0;
          if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {
            for (int i = 3; i < maxPrologLen; i++) {
              if (prolog[i] == '?' && prolog[i + 1] == '>') {
                prologLen = i + 1;
                break;
              }
            }
          }

          final int passPrologLen = prologLen;
          Runnable edit =
              new Runnable() {
                public void run() {
                  try {
                    doc.remove(0, passPrologLen + 1);
                    doc.insertString(
                        0,
                        "<?xml version='1.0' encoding='UTF-8' ?>\n<!-- was: "
                            + new String(prolog, 0, passPrologLen + 1)
                            + " -->",
                        null); // NOI18N
                  } catch (BadLocationException ble) {
                    if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                    ble.printStackTrace();
                  }
                }
              };
          NbDocument.runAtomic(doc, edit);

          super.saveDocument();
          getDataObject().setModified(false);

        } catch (BadLocationException lex) {
          ErrorManager.getDefault().notify(lex);
        }
      }
    }
  }