use of java.nio.charset.UnsupportedCharsetException in project netty by netty.
the class HttpPostRequestDecoderTest method testMultipartRequestWithFileInvalidCharset.
@Test
public void testMultipartRequestWithFileInvalidCharset() throws Exception {
final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost");
req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
// Force to use memory-based data.
final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);
final String data = "asdf";
final String filename = "tmp;0.txt";
final String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n" + "Content-Type: image/gif; charset=ABCD\r\n" + "\r\n" + data + "\r\n" + "--" + boundary + "--\r\n";
req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8));
// Create decoder instance to test.
try {
new HttpPostRequestDecoder(inMemoryFactory, req);
fail("Was expecting an ErrorDataDecoderException");
} catch (HttpPostRequestDecoder.ErrorDataDecoderException e) {
assertTrue(e.getCause() instanceof UnsupportedCharsetException);
} finally {
req.release();
}
}
use of java.nio.charset.UnsupportedCharsetException in project netty by netty.
the class HttpPostMultipartRequestDecoder method getFileUpload.
/**
* Get the FileUpload (new one or current one)
*
* @param delimiter
* the delimiter to use
* @return the InterfaceHttpData if any
* @throws ErrorDataDecoderException
*/
protected InterfaceHttpData getFileUpload(String delimiter) {
// eventually restart from existing FileUpload
// Now get value according to Content-Type and Charset
Attribute encoding = currentFieldAttributes.get(HttpHeaderNames.CONTENT_TRANSFER_ENCODING);
Charset localCharset = charset;
// Default
TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7;
if (encoding != null) {
String code;
try {
code = encoding.getValue().toLowerCase();
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value())) {
localCharset = CharsetUtil.US_ASCII;
} else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value())) {
localCharset = CharsetUtil.ISO_8859_1;
mechanism = TransferEncodingMechanism.BIT8;
} else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) {
// no real charset, so let the default
mechanism = TransferEncodingMechanism.BINARY;
} else {
throw new ErrorDataDecoderException("TransferEncoding Unknown: " + code);
}
}
Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaderValues.CHARSET);
if (charsetAttribute != null) {
try {
localCharset = Charset.forName(charsetAttribute.getValue());
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
} catch (UnsupportedCharsetException e) {
throw new ErrorDataDecoderException(e);
}
}
if (currentFileUpload == null) {
Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
Attribute nameAttribute = currentFieldAttributes.get(HttpHeaderValues.NAME);
Attribute contentTypeAttribute = currentFieldAttributes.get(HttpHeaderNames.CONTENT_TYPE);
Attribute lengthAttribute = currentFieldAttributes.get(HttpHeaderNames.CONTENT_LENGTH);
long size;
try {
size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L;
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
} catch (NumberFormatException ignored) {
size = 0;
}
try {
String contentType;
if (contentTypeAttribute != null) {
contentType = contentTypeAttribute.getValue();
} else {
contentType = HttpPostBodyUtil.DEFAULT_BINARY_CONTENT_TYPE;
}
currentFileUpload = factory.createFileUpload(request, cleanString(nameAttribute.getValue()), cleanString(filenameAttribute.getValue()), contentType, mechanism.value(), localCharset, size);
} catch (NullPointerException e) {
throw new ErrorDataDecoderException(e);
} catch (IllegalArgumentException e) {
throw new ErrorDataDecoderException(e);
} catch (IOException e) {
throw new ErrorDataDecoderException(e);
}
}
// load data as much as possible
try {
readFileUploadByteMultipart(delimiter);
} catch (NotEnoughDataDecoderException e) {
// So do not change the currentStatus
return null;
}
if (currentFileUpload.isCompleted()) {
// ready to load the next one
if (currentStatus == MultiPartStatus.FILEUPLOAD) {
currentStatus = MultiPartStatus.HEADERDELIMITER;
currentFieldAttributes = null;
} else {
currentStatus = MultiPartStatus.MIXEDDELIMITER;
cleanMixedAttributes();
}
FileUpload fileUpload = currentFileUpload;
currentFileUpload = null;
return fileUpload;
}
// So do not change the currentStatus
return null;
}
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);
}
use of java.nio.charset.UnsupportedCharsetException in project robovm by robovm.
the class ChannelsTest method testnewWriterCharsetError.
public void testnewWriterCharsetError() throws Exception {
this.fouts = new FileOutputStream(tmpFile);
WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
try {
Channels.newWriter(wbChannel, Charset.forName(BAD_CODE_SET).newEncoder(), -1);
fail();
} catch (UnsupportedCharsetException e) {
// correct
}
}
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);
}
Aggregations