001/* 002 * Copyright 2002-2012 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.util.Map; 023import java.util.Properties; 024 025/** 026 * Custom {@link java.beans.PropertyEditor} for {@link Properties} objects. 027 * 028 * <p>Handles conversion from content {@link String} to {@code Properties} object. 029 * Also handles {@link Map} to {@code Properties} conversion, for populating 030 * a {@code Properties} object via XML "map" entries. 031 * 032 * <p>The required format is defined in the standard {@code Properties} 033 * documentation. Each property must be on a new line. 034 * 035 * @author Rod Johnson 036 * @author Juergen Hoeller 037 * @see java.util.Properties#load 038 */ 039public class PropertiesEditor extends PropertyEditorSupport { 040 041 /** 042 * Convert {@link String} into {@link Properties}, considering it as 043 * properties content. 044 * @param text the text to be so converted 045 */ 046 @Override 047 public void setAsText(String text) throws IllegalArgumentException { 048 Properties props = new Properties(); 049 if (text != null) { 050 try { 051 // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. 052 props.load(new ByteArrayInputStream(text.getBytes("ISO-8859-1"))); 053 } 054 catch (IOException ex) { 055 // Should never happen. 056 throw new IllegalArgumentException( 057 "Failed to parse [" + text + "] into Properties", ex); 058 } 059 } 060 setValue(props); 061 } 062 063 /** 064 * Take {@link Properties} as-is; convert {@link Map} into {@code Properties}. 065 */ 066 @Override 067 public void setValue(Object value) { 068 if (!(value instanceof Properties) && value instanceof Map) { 069 Properties props = new Properties(); 070 props.putAll((Map<?, ?>) value); 071 super.setValue(props); 072 } 073 else { 074 super.setValue(value); 075 } 076 } 077 078}