IFileEditorInput input= (IFileEditorInput) element;
String encoding= null;
FileInfo info= (FileInfo) getElementInfo(element);
IFile file= input.getFile();
encoding= retrieveCharsetForNewFile(file, document, info);
/*
if (info != null && info.fBOM == IContentDescription.BOM_UTF_16LE && CHARSET_UTF_16.equals(encoding))
encoding= CHARSET_UTF_16LE;*/
Charset charset;
try {
charset= Charset.forName(encoding);
} catch (UnsupportedCharsetException ex) {
String message= "Unsupported encoding '" + encoding + "'.";
IStatus s= new Status(IStatus.ERROR, Plugin.PLUGIN_ID, IStatus.OK, message, ex);
throw new CoreException(s);
} catch (IllegalCharsetNameException ex) {
String message= "Unsupported encoding '" + encoding + "'.";
IStatus s= new Status(IStatus.ERROR, Plugin.PLUGIN_ID, IStatus.OK, message, ex);
throw new CoreException(s);
}
CharsetEncoder encoder= charset.newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
InputStream stream;
try {
byte[] bytes;
ByteBuffer byteBuffer= encoder.encode(CharBuffer.wrap(document.get()));
if (byteBuffer.hasArray())
bytes= byteBuffer.array();
else {
bytes= new byte[byteBuffer.limit()];
byteBuffer.get(bytes);
}
stream= new ByteArrayInputStream(bytes, 0, byteBuffer.limit());
} catch (CharacterCodingException ex) {
Assert.isTrue(ex instanceof UnmappableCharacterException);
String message= "Charset mapping failed.";
IStatus s= new Status(IStatus.ERROR, Plugin.PLUGIN_ID, EditorsUI.CHARSET_MAPPING_FAILED, message, null);
throw new CoreException(s);
}
if (file.exists()) {
if (info != null && !overwrite)
checkSynchronizationState(info.fModificationStamp, file);
// inform about the upcoming content change
fireElementStateChanging(element);
try {
file.setContents(stream, overwrite, true, monitor);
} catch (CoreException x) {
// inform about failure
fireElementStateChangeFailed(element);
throw x;
} catch (RuntimeException x) {
// inform about failure
fireElementStateChangeFailed(element);
throw x;
}
// If here, the editor state will be flipped to "not dirty".
// Thus, the state changing flag will be reset.
if (info != null) {
ResourceMarkerAnnotationModel model= (ResourceMarkerAnnotationModel) info.fModel;
if (model != null)
model.updateMarkers(info.fDocument);
info.fModificationStamp= computeModificationStamp(file);
}
} else {
try {
monitor.beginTask("Saving document", 2000);
ContainerCreator creator = new ContainerCreator(file.getWorkspace(), file.getParent().getFullPath());
creator.createContainer(new SubProgressMonitor(monitor, 1000));
file.create(stream, false, new SubProgressMonitor(monitor, 1000));
}
finally {
monitor.done();
}
}