Search in sources :

Example 1 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project che by eclipse.

the class FileStoreTextFileBuffer method commitFileBufferContent.

/*
	 * @see org.eclipse.core.internal.filebuffers.FileBuffer#commitFileBufferContent(org.eclipse.core.runtime.IProgressMonitor, boolean)
	 */
protected void commitFileBufferContent(IProgressMonitor monitor, boolean overwrite) throws CoreException {
    //		if (!isSynchronized() && !overwrite)
    //			throw new CoreException(new Status(IStatus.WARNING, FileBuffersPlugin.PLUGIN_ID, IResourceStatus.OUT_OF_SYNC_LOCAL, FileBuffersMessages.FileBuffer_error_outOfSync, 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);
        OutputStream out = fFileStore.openOutputStream(EFS.NONE, null);
        try {
            /*
				 * 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);
        } finally {
            try {
                out.close();
            } catch (IOException x) {
            }
        }
        // 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) 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 2 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project openhab1-addons by openhab.

the class CalDavLoaderImpl method updated.

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config == null) {
        log.debug("Update was called with a null configuration for CalDAV IO.");
        return;
    }
    log.debug("Update was called for CalDAV IO.");
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    Map<String, CalDavConfig> configMap = new HashMap<String, CalDavConfig>();
    Enumeration<String> iter = config.keys();
    while (iter.hasMoreElements()) {
        String key = iter.nextElement();
        if (key.equals("service.pid")) {
            continue;
        }
        log.trace("processing configuration parameter: {}", key);
        if (key.equals(PROP_TIMEZONE)) {
            String newTimeZoneStr = Objects.toString(config.get(key), null);
            if (StringUtils.isBlank(newTimeZoneStr)) {
                log.info("The {} setting was configured with an empty value. Default value '{}' will be used instead.", PROP_TIMEZONE, defaultTimeZone);
                continue;
            }
            DateTimeZone newTimeZone = DateTimeZone.forID(newTimeZoneStr);
            if (newTimeZone == null) {
                log.warn("Invalid timezone value: {}", newTimeZoneStr);
                throw new ConfigurationException(PROP_TIMEZONE, "Invalid timezone value: " + newTimeZoneStr);
            }
            log.debug("Overriding default timezone {} with {}", defaultTimeZone, newTimeZone);
            defaultTimeZone = newTimeZone;
            continue;
        }
        String[] keys = key.split(":");
        if (keys.length != 2) {
            log.warn("Unable to parse configuration parameter: {}", key);
            throw new ConfigurationException("CalDAV IO", "Unable to parse configuration parameter: " + key);
        }
        String id = keys[0];
        String paramKey = keys[1];
        CalDavConfig calDavConfig = configMap.get(id);
        if (calDavConfig == null) {
            calDavConfig = new CalDavConfig();
            configMap.put(id, calDavConfig);
        }
        String value = Objects.toString(config.get(key), null);
        calDavConfig.setKey(id);
        if (paramKey.equals(PROP_USERNAME)) {
            calDavConfig.setUsername(value);
        } else if (paramKey.equals(PROP_PASSWORD)) {
            calDavConfig.setPassword(value);
        } else if (paramKey.equals(PROP_URL)) {
            calDavConfig.setUrl(value);
        } else if (paramKey.equals(PROP_RELOAD_INTERVAL)) {
            calDavConfig.setReloadMinutes(Integer.parseInt(value));
        } else if (paramKey.equals(PROP_PRELOAD_TIME)) {
            calDavConfig.setPreloadMinutes(Integer.parseInt(value));
        } else if (paramKey.equals(PROP_HISTORIC_LOAD_TIME)) {
            calDavConfig.setHistoricLoadMinutes(Integer.parseInt(value));
        } else if (paramKey.equals(PROP_LAST_MODIFIED_TIMESTAMP_VALID)) {
            calDavConfig.setLastModifiedFileTimeStampValid(BooleanUtils.toBoolean(value));
        } else if (paramKey.equals(PROP_DISABLE_CERTIFICATE_VERIFICATION)) {
            calDavConfig.setDisableCertificateVerification(BooleanUtils.toBoolean(value));
        } else if (paramKey.equals(PROP_CHARSET)) {
            try {
                Charset.forName(value);
                calDavConfig.setCharset(value);
            } catch (UnsupportedCharsetException e) {
                log.warn("Character set not valid: {}", value);
            }
        }
    }
    // verify if all required parameters are set
    for (String id : configMap.keySet()) {
        if (StringUtils.isEmpty(configMap.get(id).getUrl())) {
            log.warn("A URL must be configured for calendar '{}'", id);
            throw new ConfigurationException("CalDAV IO", "A URL must be configured for calendar '" + id + "'");
        }
        log.trace("config for calendar '{}': {}", id, configMap.get(id));
    }
    // initialize event cache
    for (CalDavConfig calDavConfig : configMap.values()) {
        final CalendarRuntime eventRuntime = new CalendarRuntime();
        eventRuntime.setConfig(calDavConfig);
        File cachePath = Util.getCachePath(calDavConfig.getKey());
        if (!cachePath.exists() && !cachePath.mkdirs()) {
            log.warn("cannot create directory ({}) for calendar caching (missing rights?)", cachePath.getAbsoluteFile());
            continue;
        }
        EventStorage.getInstance().getEventCache().put(calDavConfig.getKey(), eventRuntime);
    }
    log.info("CalDAV IO is properly configured.");
    setProperlyConfigured(true);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConfigurationException(org.osgi.service.cm.ConfigurationException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) CalendarRuntime(org.openhab.io.caldav.internal.EventStorage.CalendarRuntime) File(java.io.File) DateTimeZone(org.joda.time.DateTimeZone)

Example 3 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project android by JetBrains.

the class EncodingValidationStrategy method validate.

@Override
void validate(@NotNull Module module, @NotNull AndroidModuleModel androidModel) {
    GradleVersion modelVersion = (androidModel.getModelVersion());
    if (modelVersion != null) {
        boolean isOneDotTwoOrNewer = modelVersion.compareIgnoringQualifiers(myOneDotTwoPluginVersion) >= 0;
        // Verify that the encoding in the model is the same as the encoding in the IDE's project settings.
        Charset modelEncoding = null;
        if (isOneDotTwoOrNewer) {
            try {
                AndroidProject androidProject = androidModel.getAndroidProject();
                modelEncoding = Charset.forName(androidProject.getJavaCompileOptions().getEncoding());
            } catch (UnsupportedCharsetException ignore) {
            // It's not going to happen.
            }
        }
        if (myMismatchingEncoding == null && modelEncoding != null && myProjectEncoding.compareTo(modelEncoding) != 0) {
            myMismatchingEncoding = modelEncoding.displayName();
        }
    }
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) Charset(java.nio.charset.Charset) AndroidProject(com.android.builder.model.AndroidProject) GradleVersion(com.android.ide.common.repository.GradleVersion)

Example 4 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project android by JetBrains.

the class GradleImport method getEncodingFromWorkspaceSetting.

@Nullable
private Charset getEncodingFromWorkspaceSetting() {
    if (myWorkspaceLocation != null && !myDefaultEncodingInitialized) {
        myDefaultEncodingInitialized = true;
        File settings = getEncodingSettingsFile();
        if (settings.exists()) {
            try {
                Properties properties = PropertiesFiles.getProperties(settings);
                if (properties != null) {
                    String encodingName = properties.getProperty("encoding");
                    if (encodingName != null) {
                        try {
                            myDefaultEncoding = Charset.forName(encodingName);
                        } catch (UnsupportedCharsetException uce) {
                            reportWarning((ImportModule) null, settings, "Unknown charset " + encodingName);
                        }
                    }
                }
            } catch (IOException e) {
            // ignore properties
            }
        }
    }
    return myDefaultEncoding;
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IOException(java.io.IOException) File(java.io.File) Nullable(com.android.annotations.Nullable)

Example 5 with UnsupportedCharsetException

use of java.nio.charset.UnsupportedCharsetException in project robovm by robovm.

the class UnsupportedCharsetExceptionTest method testConstructor.

public void testConstructor() {
    UnsupportedCharsetException ex = new UnsupportedCharsetException("impossible");
    assertTrue(ex instanceof IllegalArgumentException);
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "impossible");
    assertTrue(ex.getMessage().indexOf("impossible") != -1);
    ex = new UnsupportedCharsetException("ascii");
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "ascii");
    assertTrue(ex.getMessage().indexOf("ascii") != -1);
    ex = new UnsupportedCharsetException("");
    assertNull(ex.getCause());
    assertEquals(ex.getCharsetName(), "");
    ex.getMessage();
    ex = new UnsupportedCharsetException(null);
    assertNull(ex.getCause());
    assertNull(ex.getCharsetName());
    assertTrue(ex.getMessage().indexOf("null") != -1);
}
Also used : UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Aggregations

UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)114 Charset (java.nio.charset.Charset)55 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)42 IOException (java.io.IOException)34 ByteBuffer (java.nio.ByteBuffer)11 File (java.io.File)10 InputStream (java.io.InputStream)10 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 CoreException (org.eclipse.core.runtime.CoreException)10 CharacterCodingException (java.nio.charset.CharacterCodingException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 HashMap (java.util.HashMap)7 MediaType (okhttp3.MediaType)7 Request (okhttp3.Request)7 Response (okhttp3.Response)7 ResponseBody (okhttp3.ResponseBody)7 Buffer (okio.Buffer)7 BufferedSource (okio.BufferedSource)7 InputStreamReader (java.io.InputStreamReader)6 OutputStream (java.io.OutputStream)6