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.util;
018
019import java.io.Writer;
020
021import org.apache.commons.logging.Log;
022
023/**
024 * {@code java.io.Writer} adapter for a Commons Logging {@code Log}.
025 *
026 * @author Juergen Hoeller
027 * @since 2.5.1
028 */
029public class CommonsLogWriter extends Writer {
030
031        private final Log logger;
032
033        private final StringBuilder buffer = new StringBuilder();
034
035
036        /**
037         * Create a new CommonsLogWriter for the given Commons Logging logger.
038         * @param logger the Commons Logging logger to write to
039         */
040        public CommonsLogWriter(Log logger) {
041                Assert.notNull(logger, "Logger must not be null");
042                this.logger = logger;
043        }
044
045
046        public void write(char ch) {
047                if (ch == '\n' && this.buffer.length() > 0) {
048                        this.logger.debug(this.buffer.toString());
049                        this.buffer.setLength(0);
050                }
051                else {
052                        this.buffer.append(ch);
053                }
054        }
055
056        @Override
057        public void write(char[] buffer, int offset, int length) {
058                for (int i = 0; i < length; i++) {
059                        char ch = buffer[offset + i];
060                        if (ch == '\n' && this.buffer.length() > 0) {
061                                this.logger.debug(this.buffer.toString());
062                                this.buffer.setLength(0);
063                        }
064                        else {
065                                this.buffer.append(ch);
066                        }
067                }
068        }
069
070        @Override
071        public void flush() {
072        }
073
074        @Override
075        public void close() {
076        }
077
078}