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.jt400;
018    
019    import com.ibm.as400.access.AS400;
020    import com.ibm.as400.access.DataQueue;
021    
022    import org.apache.camel.Exchange;
023    import org.apache.camel.Producer;
024    import org.apache.camel.component.jt400.Jt400DataQueueEndpoint.Format;
025    import org.apache.camel.impl.DefaultProducer;
026    
027    /**
028     * {@link Producer} to send data to an AS/400 data queue.
029     */
030    public class Jt400DataQueueProducer extends DefaultProducer {
031    
032        private final Jt400DataQueueEndpoint endpoint;
033    
034        protected Jt400DataQueueProducer(Jt400DataQueueEndpoint endpoint) {
035            super(endpoint);
036            this.endpoint = endpoint;
037        }
038    
039        /**
040         * Sends the {@link Exchange}'s in body to the AS/400 data queue. If the
041         * endpoint's format is set to {@link Format#binary}, the data queue entry's
042         * data will be sent as a <code>byte[]</code>. If the endpoint's format is
043         * set to {@link Format#text}, the data queue entry's data will be sent as a
044         * <code>String</code>.
045         */
046        public void process(Exchange exchange) throws Exception {
047            DataQueue queue = endpoint.getDataQueue();
048            if (endpoint.getFormat() == Format.binary) {
049                queue.write(exchange.getIn().getBody(byte[].class));
050            } else {
051                queue.write(exchange.getIn().getBody(String.class));
052            }
053        }
054    
055        @Override
056        protected void doStart() throws Exception {
057            if (!endpoint.getSystem().isConnected()) {
058                endpoint.getSystem().connectService(AS400.DATAQUEUE);
059            }
060        }
061    
062        @Override
063        protected void doStop() throws Exception {
064            if (endpoint.getSystem().isConnected()) {
065                endpoint.getSystem().disconnectAllServices();
066            }
067        }
068    
069    }