/*
 * 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.apache.hyracks.control.nc.dataset;

import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataset.IDatasetPartitionManager;
import org.apache.hyracks.api.dataset.ResultSetId;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.HyracksException;
import org.apache.hyracks.api.io.IWorkspaceFileFactory;
import org.apache.hyracks.api.job.JobId;
import org.apache.hyracks.api.partitions.ResultSetPartitionId;

public class DatasetPartitionWriter implements IFrameWriter {
    private static final Logger LOGGER = Logger.getLogger(DatasetPartitionWriter.class.getName());

    private final IDatasetPartitionManager manager;

    private final JobId jobId;

    private final ResultSetId resultSetId;

    private final boolean orderedResult;

    private final int partition;

    private final int nPartitions;

    private final DatasetMemoryManager datasetMemoryManager;

    private final ResultSetPartitionId resultSetPartitionId;

    private final ResultState resultState;

    private boolean partitionRegistered;

    private boolean failed = false;

    public DatasetPartitionWriter(IHyracksTaskContext ctx, IDatasetPartitionManager manager, JobId jobId,
            ResultSetId rsId, boolean asyncMode, boolean orderedResult, int partition, int nPartitions,
            DatasetMemoryManager datasetMemoryManager, IWorkspaceFileFactory fileFactory) {
        this.manager = manager;
        this.jobId = jobId;
        this.resultSetId = rsId;
        this.orderedResult = orderedResult;
        this.partition = partition;
        this.nPartitions = nPartitions;
        this.datasetMemoryManager = datasetMemoryManager;

        resultSetPartitionId = new ResultSetPartitionId(jobId, rsId, partition);
        resultState = new ResultState(resultSetPartitionId, asyncMode, ctx.getIoManager(), fileFactory,
                ctx.getInitialFrameSize());
    }

    public ResultState getResultState() {
        return resultState;
    }

    @Override
    public void open() {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("open(" + partition + ")");
        }
        partitionRegistered = false;
        resultState.open();
    }

    @Override
    public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
        registerResultPartitionLocation(false);
        if (datasetMemoryManager == null) {
            resultState.write(buffer);
        } else {
            resultState.write(datasetMemoryManager, buffer);
        }
    }

    @Override
    public void fail() throws HyracksDataException {
        try {
            failed = true;
            resultState.closeAndDelete();
            resultState.abort();
            registerResultPartitionLocation(false);
        } catch (HyracksException e) {
            throw new HyracksDataException(e);
        }
    }

    @Override
    public void close() throws HyracksDataException {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("close(" + partition + ")");
        }
        try {
            if (!failed) {
                registerResultPartitionLocation(true);
            }
        } finally {
            resultState.close();
        }
        try {
            manager.reportPartitionWriteCompletion(jobId, resultSetId, partition);
        } catch (HyracksException e) {
            throw new HyracksDataException(e);
        }
    }

    void registerResultPartitionLocation(boolean empty) throws HyracksDataException {
        try {
            if (!partitionRegistered) {
                manager.registerResultPartitionLocation(jobId, resultSetId, partition, nPartitions, orderedResult,
                        empty);
                partitionRegistered = true;
            }
        } catch (HyracksException e) {
            if (e instanceof HyracksDataException) {
                throw (HyracksDataException) e;
            } else {
                throw new HyracksDataException(e);
            }
        }
    }
}

@@ -3586,34 +3586,16 @@
 ption %7B%0A
-        try %7B%0A    
         
@@ -3601,36 +3601,32 @@
  failed = true;%0A
-    
         resultSt
@@ -3647,36 +3647,32 @@
 lete();%0A        
-    
 resultState.abor
@@ -3680,156 +3680,8 @@
 ();%0A
-            registerResultPartitionLocation(false);%0A        %7D catch (HyracksException e) %7B%0A            throw new HyracksDataException(e);%0A        %7D%0A
     
@@ -4038,32 +4038,75 @@
 %7D%0A        try %7B%0A
+            if (partitionRegistered) %7B%0A    
             mana
@@ -4164,32 +4164,46 @@
 Id, partition);%0A
+            %7D%0A
         %7D catch 

Fix DatasetPartitionWriter fail behavior