001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.stringtemplate;
018
019 import java.io.StringWriter;
020 import java.util.Map;
021
022 import org.antlr.stringtemplate.AutoIndentWriter;
023 import org.antlr.stringtemplate.StringTemplate;
024 import org.apache.camel.Exchange;
025 import org.apache.camel.ExchangePattern;
026 import org.apache.camel.Message;
027 import org.apache.camel.Processor;
028 import org.apache.camel.component.ResourceBasedEndpoint;
029 import org.apache.camel.util.ExchangeHelper;
030
031 /**
032 * @version $Revision: 15729 $
033 */
034 public class StringTemplateEndpoint extends ResourceBasedEndpoint {
035
036 public StringTemplateEndpoint(String uri, StringTemplateComponent component, String resourceUri, Map parameters) {
037 super(uri, component, resourceUri, null);
038 }
039
040 public StringTemplateEndpoint(String endpointUri, Processor processor, String resourceUri) {
041 super(endpointUri, processor, resourceUri);
042 }
043
044 @Override
045 public boolean isSingleton() {
046 return true;
047 }
048
049 @Override
050 public ExchangePattern getExchangePattern() {
051 return ExchangePattern.InOut;
052 }
053
054 @Override
055 protected void onExchange(Exchange exchange) throws Exception {
056 StringWriter buffer = new StringWriter();
057 Map variableMap = ExchangeHelper.createVariableMap(exchange);
058
059 // getResourceAsInputStream also considers the content cache
060 String text = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, getResourceAsInputStream());
061 StringTemplate template = new StringTemplate(text);
062 template.setAttributes(variableMap);
063 if (log.isDebugEnabled()) {
064 log.debug("StringTemplate is writing using attributes: " + variableMap);
065 }
066 template.write(new AutoIndentWriter(buffer));
067
068 // now lets output the results to the exchange
069 Message out = exchange.getOut();
070 out.setBody(buffer.toString());
071 out.setHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE, getResource());
072 }
073
074 }