Search in sources :

Example 86 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project eclipse.platform.text by eclipse.

the class FileStoreTextFileBuffer method commitFileBufferContent.

@Override
protected void commitFileBufferContent(IProgressMonitor monitor, boolean overwrite) throws CoreException {
    if (!isSynchronized() && !overwrite) {
        String message = NLSUtility.format(FileBuffersMessages.FileBuffer_error_outOfSync, getFileStore().toURI());
        throw new CoreException(new Status(IStatus.WARNING, FileBuffersPlugin.PLUGIN_ID, IResourceStatus.OUT_OF_SYNC_LOCAL, message, null));
    }
    String encoding = computeEncoding();
    Charset charset;
    try {
        charset = Charset.forName(encoding);
    } catch (UnsupportedCharsetException ex) {
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_unsupported_encoding_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, message, ex);
        throw new CoreException(s);
    } catch (IllegalCharsetNameException ex) {
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_illegal_encoding_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, message, ex);
        throw new CoreException(s);
    }
    CharsetEncoder encoder = charset.newEncoder();
    encoder.onMalformedInput(CodingErrorAction.REPLACE);
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    byte[] bytes;
    int bytesLength;
    try {
        ByteBuffer byteBuffer = encoder.encode(CharBuffer.wrap(fDocument.get()));
        bytesLength = byteBuffer.limit();
        if (byteBuffer.hasArray())
            bytes = byteBuffer.array();
        else {
            bytes = new byte[bytesLength];
            byteBuffer.get(bytes);
        }
    } catch (CharacterCodingException ex) {
        Assert.isTrue(ex instanceof UnmappableCharacterException);
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_charset_mapping_failed_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IFileBufferStatusCodes.CHARSET_MAPPING_FAILED, message, null);
        throw new CoreException(s);
    }
    IFileInfo fileInfo = fFileStore.fetchInfo();
    if (fileInfo != null && fileInfo.exists()) {
        if (!overwrite)
            checkSynchronizationState();
        InputStream stream = new ByteArrayInputStream(bytes, 0, bytesLength);
        /*
			 * XXX:
			 * This is a workaround for a corresponding bug in Java readers and writer,
			 * see http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
			 */
        if (fHasBOM && CHARSET_UTF_8.equals(encoding))
            stream = new SequenceInputStream(new ByteArrayInputStream(IContentDescription.BOM_UTF_8), stream);
        // here the file synchronizer should actually be removed and afterwards added again. However,
        // we are already inside an operation, so the delta is sent AFTER we have added the listener
        setFileContents(stream, monitor);
        // set synchronization stamp to know whether the file synchronizer must become active
        fSynchronizationStamp = fFileStore.fetchInfo().getLastModified();
        if (fAnnotationModel instanceof IPersistableAnnotationModel) {
            IPersistableAnnotationModel persistableModel = (IPersistableAnnotationModel) fAnnotationModel;
            persistableModel.commit(fDocument);
        }
    } else {
        fFileStore.getParent().mkdir(EFS.NONE, null);
        try (OutputStream out = fFileStore.openOutputStream(EFS.NONE, null)) {
            /*
				 * XXX:
				 * This is a workaround for a corresponding bug in Java readers and writer,
				 * see http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
				 */
            if (fHasBOM && CHARSET_UTF_8.equals(encoding))
                out.write(IContentDescription.BOM_UTF_8);
            out.write(bytes, 0, bytesLength);
            out.flush();
            out.close();
        } catch (IOException x) {
            IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, x.getLocalizedMessage(), x);
            throw new CoreException(s);
        }
        // set synchronization stamp to know whether the file synchronizer must become active
        fSynchronizationStamp = fFileStore.fetchInfo().getLastModified();
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IResourceStatus(org.eclipse.core.resources.IResourceStatus) IPersistableAnnotationModel(org.eclipse.core.filebuffers.IPersistableAnnotationModel) IStatus(org.eclipse.core.runtime.IStatus) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) IOException(java.io.IOException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) IFileInfo(org.eclipse.core.filesystem.IFileInfo) CoreException(org.eclipse.core.runtime.CoreException) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnmappableCharacterException(java.nio.charset.UnmappableCharacterException)

Example 87 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project eclipse.platform.text by eclipse.

the class ResourceTextFileBuffer method commitFileBufferContent.

@Override
protected void commitFileBufferContent(IProgressMonitor monitor, boolean overwrite) throws CoreException {
    if (!isSynchronized() && !overwrite) {
        String message = NLSUtility.format(FileBuffersMessages.FileBuffer_error_outOfSync, getFileStore().toURI());
        throw new CoreException(new Status(IStatus.WARNING, FileBuffersPlugin.PLUGIN_ID, IResourceStatus.OUT_OF_SYNC_LOCAL, message, null));
    }
    String encoding = computeEncoding();
    if (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 = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_unsupported_encoding_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, message, ex);
        throw new CoreException(s);
    } catch (IllegalCharsetNameException ex) {
        String message = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_illegal_encoding_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.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(fDocument.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 = NLSUtility.format(FileBuffersMessages.ResourceTextFileBuffer_error_charset_mapping_failed_message_arg, encoding);
        IStatus s = new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IFileBufferStatusCodes.CHARSET_MAPPING_FAILED, message, ex);
        throw new CoreException(s);
    }
    /*
		 * XXX:
		 * This is a workaround for a corresponding bug in Java readers and writer,
		 * see http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
		 */
    if (fBOM == IContentDescription.BOM_UTF_8 && CHARSET_UTF_8.equals(encoding))
        stream = new SequenceInputStream(new ByteArrayInputStream(IContentDescription.BOM_UTF_8), stream);
    if (fBOM == IContentDescription.BOM_UTF_16LE && CHARSET_UTF_16LE.equals(encoding))
        stream = new SequenceInputStream(new ByteArrayInputStream(IContentDescription.BOM_UTF_16LE), stream);
    if (fFile.exists()) {
        // here the file synchronizer should actually be removed and afterwards added again. However,
        // we are already inside an operation, so the delta is sent AFTER we have added the listener
        fFile.setContents(stream, overwrite, true, monitor);
        if (fDocument instanceof IDocumentExtension4) {
            fSynchronizationStamp = ((IDocumentExtension4) fDocument).getModificationStamp();
            fFile.revertModificationStamp(fSynchronizationStamp);
        } else
            fSynchronizationStamp = fFile.getModificationStamp();
        if (fAnnotationModel instanceof IPersistableAnnotationModel) {
            IPersistableAnnotationModel persistableModel = (IPersistableAnnotationModel) fAnnotationModel;
            persistableModel.commit(fDocument);
        }
    } else {
        SubMonitor subMonitor = SubMonitor.convert(monitor, FileBuffersMessages.ResourceTextFileBuffer_task_saving, 2);
        ContainerCreator creator = new ContainerCreator(fFile.getWorkspace(), fFile.getParent().getFullPath());
        creator.createContainer(subMonitor.split(1));
        fFile.create(stream, false, subMonitor.split(1));
        // set synchronization stamp to know whether the file synchronizer must become active
        fSynchronizationStamp = fFile.getModificationStamp();
        subMonitor.split(1);
    // TODO commit persistable annotation model
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IResourceStatus(org.eclipse.core.resources.IResourceStatus) IPersistableAnnotationModel(org.eclipse.core.filebuffers.IPersistableAnnotationModel) IStatus(org.eclipse.core.runtime.IStatus) IDocumentExtension4(org.eclipse.jface.text.IDocumentExtension4) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) CoreException(org.eclipse.core.runtime.CoreException) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) UnmappableCharacterException(java.nio.charset.UnmappableCharacterException) ContainerCreator(org.eclipse.core.filebuffers.manipulation.ContainerCreator)

Example 88 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project linuxtools by eclipse.

the class DockerDocumentProvider method doSaveDocument.

@Override
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
    if (element instanceof FileStoreEditorInput) {
        String encoding = null;
        ElementInfo info = getElementInfo(element);
        Path filePath = Paths.get(((FileStoreEditorInput) element).getURI());
        encoding = getEncoding(element);
        Charset charset;
        try {
            charset = Charset.forName(encoding);
        } catch (UnsupportedCharsetException ex) {
            String message = NLS.bind(Messages.DockerDocumentProvider_encoding_not_supported, encoding);
            IStatus s = new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, IStatus.OK, message, ex);
            throw new CoreException(s);
        } catch (IllegalCharsetNameException ex) {
            String message = NLS.bind(Messages.DockerDocumentProvider_encoding_not_legal, encoding);
            IStatus s = new Status(IStatus.ERROR, EditorsUI.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 = NLS.bind(Messages.DockerDocumentProvider_cannot_be_mapped + Messages.DockerDocumentProvider_chars_not_supported, encoding);
            IStatus s = new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, EditorsUI.CHARSET_MAPPING_FAILED, message, null);
            throw new CoreException(s);
        }
        if (Files.exists(filePath)) {
            // inform about the upcoming content change
            fireElementStateChanging(element);
            try (FileWriter fw = new FileWriter(filePath.toFile());
                InputStreamReader istream = new InputStreamReader(stream)) {
                char[] bb = new char[1024];
                int nRead = istream.read(bb);
                while (nRead > 0) {
                    fw.write(bb, 0, nRead);
                    nRead = istream.read(bb);
                }
            } catch (RuntimeException | IOException x) {
                // inform about failure
                fireElementStateChangeFailed(element);
                throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, x.getMessage()));
            }
            if (info != null) {
                ResourceMarkerAnnotationModel model = (ResourceMarkerAnnotationModel) info.fModel;
                if (model != null)
                    model.updateMarkers(info.fDocument);
            }
        } else {
            try {
                Files.createFile(filePath);
                try (FileWriter fw = new FileWriter(filePath.toFile());
                    InputStreamReader istream = new InputStreamReader(stream)) {
                    char[] bb = new char[1024];
                    int nRead = istream.read(bb);
                    while (nRead > 0) {
                        fw.write(bb, 0, nRead);
                        nRead = istream.read(bb);
                    }
                } catch (IOException x) {
                    throw x;
                }
            } catch (IOException e) {
                throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage()));
            } finally {
                monitor.done();
            }
        }
    } else {
        super.doSaveDocument(monitor, element, document, overwrite);
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) FileWriter(java.io.FileWriter) CharsetEncoder(java.nio.charset.CharsetEncoder) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnmappableCharacterException(java.nio.charset.UnmappableCharacterException) Path(java.nio.file.Path) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ResourceMarkerAnnotationModel(org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) CoreException(org.eclipse.core.runtime.CoreException) ByteArrayInputStream(java.io.ByteArrayInputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) FileStoreEditorInput(org.eclipse.ui.ide.FileStoreEditorInput)

Example 89 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project Payara by payara.

the class Utility method convertCharArrayToByteArray.

/**
 * Convert the char array to byte array with respect to given charset.
 *
 * @param charArray
 * @param strCharset  null or "" means default charset
 * @exception CharacterCodingException
 */
public static byte[] convertCharArrayToByteArray(char[] charArray, String strCharset) throws CharacterCodingException {
    if (charArray == null) {
        return null;
    }
    char[] cArray = (char[]) charArray.clone();
    CharBuffer charBuffer = CharBuffer.wrap(cArray);
    Charset charSet;
    if (strCharset == null || "".equals(strCharset)) {
        charSet = Charset.defaultCharset();
    } else if (Charset.isSupported(strCharset)) {
        charSet = Charset.forName(strCharset);
    } else {
        CharacterCodingException e = new CharacterCodingException();
        e.initCause(new UnsupportedCharsetException(strCharset));
        throw e;
    }
    CharsetEncoder encoder = charSet.newEncoder();
    ByteBuffer byteBuffer = null;
    try {
        byteBuffer = encoder.encode(charBuffer);
    } catch (CharacterCodingException cce) {
        throw cce;
    } catch (Throwable t) {
        CharacterCodingException e = new CharacterCodingException();
        e.initCause(t);
        throw e;
    }
    byte[] result = new byte[byteBuffer.remaining()];
    byteBuffer.get(result);
    clear(byteBuffer);
    clear(charBuffer);
    return result.clone();
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) CharBuffer(java.nio.CharBuffer) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer)

Example 90 with CharacterCodingException

use of java.nio.charset.CharacterCodingException in project Payara by payara.

the class Utility method convertByteArrayToCharArray.

/**
 * Convert the byte array to char array with respect to given charset.
 *
 * @param byteArray
 * @param charset  null or "" means default charset
 * @exception CharacterCodingException
 */
public static char[] convertByteArrayToCharArray(byte[] byteArray, String charset) throws CharacterCodingException {
    if (byteArray == null) {
        return null;
    }
    byte[] bArray = (byte[]) byteArray.clone();
    ByteBuffer byteBuffer = ByteBuffer.wrap(bArray);
    Charset charSet;
    if (charset == null || "".equals(charset)) {
        charSet = Charset.defaultCharset();
    } else if (Charset.isSupported(charset)) {
        charSet = Charset.forName(charset);
    } else {
        CharacterCodingException e = new CharacterCodingException();
        e.initCause(new UnsupportedCharsetException(charset));
        throw e;
    }
    CharsetDecoder decoder = charSet.newDecoder();
    CharBuffer charBuffer = null;
    try {
        charBuffer = decoder.decode(byteBuffer);
    } catch (CharacterCodingException cce) {
        throw cce;
    } catch (Throwable t) {
        CharacterCodingException e = new CharacterCodingException();
        e.initCause(t);
        throw e;
    }
    char[] result = toCharArray(charBuffer);
    clear(byteBuffer);
    clear(charBuffer);
    return result;
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) CharBuffer(java.nio.CharBuffer) Charset(java.nio.charset.Charset) CharacterCodingException(java.nio.charset.CharacterCodingException) ByteBuffer(java.nio.ByteBuffer)

Aggregations

CharacterCodingException (java.nio.charset.CharacterCodingException)90 ByteBuffer (java.nio.ByteBuffer)46 CharsetEncoder (java.nio.charset.CharsetEncoder)16 CharBuffer (java.nio.CharBuffer)15 IOException (java.io.IOException)14 CoderResult (java.nio.charset.CoderResult)13 CharsetDecoder (java.nio.charset.CharsetDecoder)11 Charset (java.nio.charset.Charset)10 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)8 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)6 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 InputStream (java.io.InputStream)5 CoreException (org.eclipse.core.runtime.CoreException)5 IStatus (org.eclipse.core.runtime.IStatus)5 Status (org.eclipse.core.runtime.Status)5 HumanReadableException (com.facebook.buck.util.HumanReadableException)4 SequenceInputStream (java.io.SequenceInputStream)4 Path (java.nio.file.Path)4 Date (java.util.Date)4