/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openengsb.issues.common.endpoints;

import java.io.StringReader;
import java.io.StringWriter;

import javax.jbi.management.DeploymentException;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.namespace.QName;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.apache.servicemix.jbi.jaxp.StringSource;
import org.openengsb.contextcommon.ContextHelper;
import org.openengsb.core.OpenEngSBEndpoint;
import org.openengsb.drools.DroolsIssuesDomain;
import org.openengsb.issues.common.IssueDomain;
import org.openengsb.issues.common.exceptions.IssueDomainException;
import org.openengsb.issues.common.messages.CreateIssueMessage;
import org.openengsb.issues.common.messages.CreateIssueResponseMessage;
import org.openengsb.issues.common.messages.CreateIssueStatus;
import org.openengsb.util.serialization.JibxXmlSerializer;
import org.openengsb.util.serialization.SerializationException;
import org.openengsb.util.serialization.Serializer;

/**
 * @org.apache.xbean.XBean element="create-issue"
 */
public abstract class AbstractIssueEndpoint extends OpenEngSBEndpoint<DroolsIssuesDomain> {

    private Logger log = Logger.getLogger(AbstractIssueEndpoint.class);

    private Serializer serializer;

    protected abstract IssueDomain createIssueDomain() throws IssueDomainException;

    public AbstractIssueEndpoint() {
        // set defaults
        this.serializer = new JibxXmlSerializer();
    }

    @Override
    public void validate() throws DeploymentException {
    }

    @Override
    protected synchronized void inOut(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out,
            ContextHelper contextHelper) throws Exception {
        if (exchange.getStatus() != ExchangeStatus.ACTIVE) {
            return;
        }

        CreateIssueResponseMessage responseMessage = new CreateIssueResponseMessage();

        try {
            IssueDomain domain = createIssueDomain();

            // transform message to string
            Transformer messageTransformer = TransformerFactory.newInstance().newTransformer();
            StringWriter stringWriter = new StringWriter();
            messageTransformer.transform(in.getContent(), new StreamResult(stringWriter));

            String issueId = domain.createIssue(this.serializer.deserialize(CreateIssueMessage.class,
                    new StringReader(stringWriter.toString())).getIssue());
            responseMessage.setCreatedIssueId(issueId);
            responseMessage.setStatus(CreateIssueStatus.SUCCESS);
            responseMessage.setStatusMessage("Issue created successfully.");
        } catch (SerializationException e) {
            this.log.error("Error deserializing incoming message.", e);
            responseMessage.setStatus(CreateIssueStatus.ERROR);
            responseMessage.setStatusMessage(e.getMessage());
        } catch (IssueDomainException e) {
            this.log.error("Error creating issue.", e);
            responseMessage.setStatus(CreateIssueStatus.ERROR);
            responseMessage.setStatusMessage(e.getMessage());
        } catch (Exception e) {
            this.log.error("Unexpected error occurred.", e);
            responseMessage.setStatus(CreateIssueStatus.ERROR);
            responseMessage.setStatusMessage(e.getMessage());
        } finally {
            StringWriter sw = new StringWriter();
            this.serializer.serialize(responseMessage, sw);
            out.setContent(new StringSource(sw.toString()));
            getChannel().send(exchange);
        }
    }

    @Override
    protected QName getForwardTarget(ContextHelper contextHelper) {
        // not required in this use case
        return null;
    }

    public Serializer getSerializer() {
        return this.serializer;
    }

    public void setSerializer(Serializer serializer) {
        this.serializer = serializer;
    }

}

@@ -2379,37 +2379,32 @@
 efaults%0A        
-this.
 serializer = new
@@ -2421,24 +2421,24 @@
 rializer();%0A
+
     %7D%0A%0A    @
@@ -3280,21 +3280,16 @@
 teIssue(
-this.
 serializ
@@ -3653,37 +3653,32 @@
 ) %7B%0A            
-this.
 log.error(%22Error
@@ -3889,37 +3889,32 @@
 ) %7B%0A            
-this.
 log.error(%22Error
@@ -4106,21 +4106,16 @@
         
-this.
 log.erro
@@ -4350,37 +4350,32 @@
 ();%0A            
-this.
 serializer.seria
@@ -4466,49 +4466,8 @@
 ));%0A
-            getChannel().send(exchange);%0A
     
@@ -4666,24 +4666,24 @@
 ializer() %7B%0A
+
         retu
@@ -4685,21 +4685,16 @@
  return 
-this.
 serializ

remove explicit send() from endpoint (to avoid ComponentNotOwner-Exception)