001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.beans.propertyeditors; 018 019import java.beans.PropertyEditorSupport; 020import java.io.ByteArrayInputStream; 021import java.io.IOException; 022import java.nio.charset.StandardCharsets; 023import java.util.Map; 024import java.util.Properties; 025 026import org.springframework.lang.Nullable; 027 028/** 029 * Custom {@link java.beans.PropertyEditor} for {@link Properties} objects. 030 * 031 * <p>Handles conversion from content {@link String} to {@code Properties} object. 032 * Also handles {@link Map} to {@code Properties} conversion, for populating 033 * a {@code Properties} object via XML "map" entries. 034 * 035 * <p>The required format is defined in the standard {@code Properties} 036 * documentation. Each property must be on a new line. 037 * 038 * @author Rod Johnson 039 * @author Juergen Hoeller 040 * @see java.util.Properties#load 041 */ 042public class PropertiesEditor extends PropertyEditorSupport { 043 044 /** 045 * Convert {@link String} into {@link Properties}, considering it as 046 * properties content. 047 * @param text the text to be so converted 048 */ 049 @Override 050 public void setAsText(@Nullable String text) throws IllegalArgumentException { 051 Properties props = new Properties(); 052 if (text != null) { 053 try { 054 // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. 055 props.load(new ByteArrayInputStream(text.getBytes(StandardCharsets.ISO_8859_1))); 056 } 057 catch (IOException ex) { 058 // Should never happen. 059 throw new IllegalArgumentException( 060 "Failed to parse [" + text + "] into Properties", ex); 061 } 062 } 063 setValue(props); 064 } 065 066 /** 067 * Take {@link Properties} as-is; convert {@link Map} into {@code Properties}. 068 */ 069 @Override 070 public void setValue(Object value) { 071 if (!(value instanceof Properties) && value instanceof Map) { 072 Properties props = new Properties(); 073 props.putAll((Map<?, ?>) value); 074 super.setValue(props); 075 } 076 else { 077 super.setValue(value); 078 } 079 } 080 081}