text:
package org.apache.camel.component.olingo4.api.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.camel.component.olingo4.api.Olingo4App;
import org.apache.camel.component.olingo4.api.Olingo4ResponseHandler;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchChangeRequest;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchQueryRequest;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchRequest;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchResponse;
import org.apache.camel.component.olingo4.api.batch.Operation;
import org.apache.camel.util.ObjectHelper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.DecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.config.MessageConstraints;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.io.SessionInputBufferImpl;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicLineParser;
import org.apache.olingo.client.api.ODataBatchConstants;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.communication.request.ODataStreamer;
import org.apache.olingo.client.api.communication.request.batch.ODataBatchLineIterator;
import org.apache.olingo.client.api.domain.ClientEntity;
import org.apache.olingo.client.api.domain.ClientPrimitiveValue;
import org.apache.olingo.client.api.domain.ClientProperty;
import org.apache.olingo.client.api.serialization.ODataReader;
import org.apache.olingo.client.api.serialization.ODataWriter;
import org.apache.olingo.client.api.uri.SegmentType;
import org.apache.olingo.client.core.ODataClientFactory;
import org.apache.olingo.client.core.communication.request.batch.ODataBatchController;
import org.apache.olingo.client.core.communication.request.batch.ODataBatchLineIteratorImpl;
import org.apache.olingo.client.core.communication.request.batch.ODataBatchUtilities;
import org.apache.olingo.client.core.http.HttpMerge;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoKind;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.core.uri.UriResourceFunctionImpl;
import org.apache.olingo.server.core.uri.parser.Parser;
import org.apache.olingo.server.core.uri.parser.UriParserException;
import org.apache.olingo.server.core.uri.validator.UriValidationException;

import static org.apache.camel.component.olingo4.api.impl.Olingo4Helper.getContentTypeHeader;

/**
 * Application API used by Olingo4 Component.
 */
public final class Olingo4AppImpl implements Olingo4App {

    private static final String SEPARATOR = "/";
    private static final String BOUNDARY_PREFIX = "batch_";
    private static final String BOUNDARY_PARAMETER = "; boundary=";
    private static final String BOUNDARY_DOUBLE_DASH = "--";
    private static final String MULTIPART_MIME_TYPE = "multipart/";
    private static final String CONTENT_ID_HEADER = "Content-ID";
    private static final String CLIENT_ENTITY_FAKE_MARKER = "('X')";

    private static final ContentType DEFAULT_CONTENT_TYPE = ContentType.create(ContentType.APPLICATION_JSON, ContentType.PARAMETER_CHARSET, Constants.UTF8);
    private static final ContentType METADATA_CONTENT_TYPE = ContentType.create(ContentType.APPLICATION_XML, ContentType.PARAMETER_CHARSET, Constants.UTF8);
    private static final ContentType TEXT_PLAIN_WITH_CS_UTF_8 = ContentType.create(ContentType.TEXT_PLAIN, ContentType.PARAMETER_CHARSET, Constants.UTF8);
    private static final ContentType SERVICE_DOCUMENT_CONTENT_TYPE = ContentType.APPLICATION_JSON;
    private static final ContentType BATCH_CONTENT_TYPE = ContentType.MULTIPART_MIXED;

    /**
     * Reference to CloseableHttpAsyncClient (default) or CloseableHttpClient
     */
    private final Closeable client;

    /**
     * Reference to ODataClient reader and writer
     */
    private final ODataClient odataClient = ODataClientFactory.getClient();
    private final ODataReader odataReader = odataClient.getReader();
    private final ODataWriter odataWriter = odataClient.getWriter();

    private String serviceUri;
    private ContentType contentType;
    private Map<String, String> httpHeaders;

    /**
     * Create Olingo4 Application with default HTTP configuration.
     */
    public Olingo4AppImpl(String serviceUri) {
        // By default create HTTP asynchronous client
        this(serviceUri, (HttpClientBuilder)null);
    }

    /**
     * Create Olingo4 Application with custom HTTP Asynchronous client builder.
     *
     * @param serviceUri Service Application base URI.
     * @param builder custom HTTP client builder.
     */
    public Olingo4AppImpl(String serviceUri, HttpAsyncClientBuilder builder) {
        setServiceUri(serviceUri);

        CloseableHttpAsyncClient asyncClient;
        if (builder == null) {
            asyncClient = HttpAsyncClients.createDefault();
        } else {
            asyncClient = builder.build();
        }
        asyncClient.start();
        this.client = asyncClient;
        this.contentType = DEFAULT_CONTENT_TYPE;
    }

    /**
     * Create Olingo4 Application with custom HTTP Synchronous client builder.
     *
     * @param serviceUri Service Application base URI.
     * @param builder Custom HTTP Synchronous client builder.
     */
    public Olingo4AppImpl(String serviceUri, HttpClientBuilder builder) {
        setServiceUri(serviceUri);

        if (builder == null) {
            this.client = HttpClients.createDefault();
        } else {
            this.client = builder.build();
        }
        this.contentType = DEFAULT_CONTENT_TYPE;
    }

    @Override
    public void setServiceUri(String serviceUri) {
        if (serviceUri == null || serviceUri.isEmpty()) {
            throw new IllegalArgumentException("serviceUri");
        }
        this.serviceUri = serviceUri.endsWith(SEPARATOR) ? serviceUri.substring(0, serviceUri.length() - 1) : serviceUri;
    }

    @Override
    public String getServiceUri() {
        return serviceUri;
    }

    @Override
    public Map<String, String> getHttpHeaders() {
        return httpHeaders;
    }

    @Override
    public void setHttpHeaders(Map<String, String> httpHeaders) {
        this.httpHeaders = httpHeaders;
    }

    @Override
    public String getContentType() {
        return contentType.toContentTypeString();
    }

    @Override
    public void setContentType(String contentType) {
        this.contentType = ContentType.parse(contentType);
    }

    @Override
    public void close() {

    }

    @Override
    public <T> void read(final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders,
                         final Olingo4ResponseHandler<T> responseHandler) {
        final String queryOptions = concatQueryParams(queryParams);
        final UriInfo uriInfo = parseUri(edm, resourcePath, queryOptions);

        execute(new HttpGet(createUri(resourcePath, queryOptions)), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) {

            @Override
            public void onCompleted(HttpResponse result) throws IOException {
                readContent(uriInfo, result.getEntity() != null ? result.getEntity().getContent() : null, headersToMap(result.getAllHeaders()), responseHandler);
            }

        });
    }

    @Override
    public void uread(final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders,
                      final Olingo4ResponseHandler<InputStream> responseHandler) {
        final String queryOptions = concatQueryParams(queryParams);
        final UriInfo uriInfo = parseUri(edm, resourcePath, queryOptions);

        execute(new HttpGet(createUri(resourcePath, queryOptions)), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<InputStream>(responseHandler) {

            @Override
            public void onCompleted(HttpResponse result) throws IOException {
                InputStream responseStream = result.getEntity() != null ? result.getEntity().getContent() : null;
                if (responseStream != null && result.getEntity() instanceof DecompressingEntity) {
                    // In case of GZIP compression it's necessary to create
                    // InputStream from the source byte array
                    responseHandler.onResponse(new ByteArrayInputStream(IOUtils.toByteArray(responseStream)), headersToMap(result.getAllHeaders()));
                } else {
                    responseHandler.onResponse(responseStream, headersToMap(result.getAllHeaders()));
                }
            }
        });
    }

    @Override
    public <T> void create(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) {
        final UriInfo uriInfo = parseUri(edm, resourcePath, null);

        writeContent(edm, new HttpPost(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler);
    }

    @Override
    public <T> void update(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) {
        final UriInfo uriInfo = parseUri(edm, resourcePath, null);

        writeContent(edm, new HttpPut(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler);
    }

    @Override
    public void delete(final String resourcePath, final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<HttpStatusCode> responseHandler) {
        execute(new HttpDelete(createUri(resourcePath)), contentType, endpointHttpHeaders, new AbstractFutureCallback<HttpStatusCode>(responseHandler) {
            @Override
            public void onCompleted(HttpResponse result) {
                final StatusLine statusLine = result.getStatusLine();
                responseHandler.onResponse(HttpStatusCode.fromStatusCode(statusLine.getStatusCode()), headersToMap(result.getAllHeaders()));
            }
        });
    }

    @Override
    public <T> void patch(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) {
        final UriInfo uriInfo = parseUri(edm, resourcePath, null);

        writeContent(edm, new HttpPatch(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler);
    }

    @Override
    public <T> void merge(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<T> responseHandler) {
        final UriInfo uriInfo = parseUri(edm, resourcePath, null);

        writeContent(edm, new HttpMerge(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler);
    }

    @Override
    public void batch(final Edm edm, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<List<Olingo4BatchResponse>> responseHandler) {
        final UriInfo uriInfo = parseUri(edm, SegmentType.BATCH.getValue(), null);

        writeContent(edm, new HttpPost(createUri(SegmentType.BATCH.getValue(), null)), uriInfo, data, endpointHttpHeaders, responseHandler);
    }

    private ContentType getResourceContentType(UriInfo uriInfo) {
        ContentType resourceContentType;
        switch (uriInfo.getKind()) {
        case service:
            // service document
            resourceContentType = SERVICE_DOCUMENT_CONTENT_TYPE;
            break;
        case metadata:
            // metadata
            resourceContentType = METADATA_CONTENT_TYPE;
            break;
        case resource:
            List<UriResource> listResource = uriInfo.getUriResourceParts();
            UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
            // is it a $value or $count URI??
            if (lastResourceKind == UriResourceKind.count || lastResourceKind == UriResourceKind.value) {
                resourceContentType = TEXT_PLAIN_WITH_CS_UTF_8;
            } else {
                resourceContentType = contentType;
            }
            break;
        default:
            resourceContentType = contentType;
        }
        return resourceContentType;
    }

    private <T> void readContent(UriInfo uriInfo, InputStream content, Map<String, String> endpointHttpHeaders, Olingo4ResponseHandler<T> responseHandler) {
        try {
            responseHandler.onResponse(this.<T> readContent(uriInfo, content), endpointHttpHeaders);
        } catch (Exception e) {
            responseHandler.onException(e);
        } catch (Error e) {
            responseHandler.onException(new ODataException("Runtime Error Occurred", e));
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T readContent(UriInfo uriInfo, InputStream content) throws ODataException {
        T response = null;
        switch (uriInfo.getKind()) {
        case service:
            // service document
            response = (T)odataReader.readServiceDocument(content, SERVICE_DOCUMENT_CONTENT_TYPE);
            break;

        case metadata:
            // $metadata
            response = (T)odataReader.readMetadata(content);
            break;
        case resource:
            // any resource entity
            List<UriResource> listResource = uriInfo.getUriResourceParts();
            UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
            switch (lastResourceKind) {
            case entitySet:
                UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet)listResource.get(listResource.size() - 1);
                List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
                // Check result type: single Entity or EntitySet based
                // on key predicate detection
                if (keyPredicates.size() == 1) {
                    response = (T)odataReader.readEntity(content, getResourceContentType(uriInfo));
                } else {
                    response = (T)odataReader.readEntitySet(content, getResourceContentType(uriInfo));
                }
                break;
            case count:
                String stringCount = null;
                try {
                    stringCount = IOUtils.toString(content, Consts.UTF_8);
                    response = (T)Long.valueOf(stringCount);
                } catch (IOException e) {
                    throw new ODataException("Error during $count value deserialization", e);
                } catch (NumberFormatException e) {
                    throw new ODataException("Error during $count value conversion: " + stringCount, e);
                }
                break;
            case value:
                try {
                    ClientPrimitiveValue value = odataClient.getObjectFactory().newPrimitiveValueBuilder().setType(EdmPrimitiveTypeKind.String)
                        .setValue(IOUtils.toString(content, Consts.UTF_8)).build();
                    response = (T)value;
                } catch (IOException e) {
                    throw new ODataException("Error during $value deserialization", e);
                }
                break;
            case primitiveProperty:
            case complexProperty:
                ClientProperty property = odataReader.readProperty(content, getResourceContentType(uriInfo));
                if (property.hasPrimitiveValue()) {
                    response = (T)property.getPrimitiveValue();
                } else if (property.hasComplexValue()) {
                    response = (T)property.getComplexValue();
                } else {
                    throw new ODataException("Unsupported property: " + property.getName());
                }
                break;
            case function:
                UriResourceFunctionImpl uriResourceFunction = (UriResourceFunctionImpl)listResource.get(listResource.size() - 1);
                EdmReturnType functionReturnType = uriResourceFunction.getFunction().getReturnType();

                switch (functionReturnType.getType().getKind()) {
                case ENTITY:
                    if (functionReturnType.isCollection()) {
                        response = (T)odataReader.readEntitySet(content, getResourceContentType(uriInfo));
                    } else {
                        response = (T)odataReader.readEntity(content, getResourceContentType(uriInfo));
                    }
                    break;
                case PRIMITIVE:
                case COMPLEX:
                    ClientProperty functionProperty = odataReader.readProperty(content, getResourceContentType(uriInfo));
                    if (functionProperty.hasPrimitiveValue()) {
                        response = (T)functionProperty.getPrimitiveValue();
                    } else if (functionProperty.hasComplexValue()) {
                        response = (T)functionProperty.getComplexValue();
                    } else {
                        throw new ODataException("Unsupported property: " + functionProperty.getName());
                    }
                    break;
                default:
                    throw new ODataException("Unsupported function return type " + uriInfo.getKind().name());
                }
                break;
            default:
                throw new ODataException("Unsupported resource type: " + lastResourceKind.name());
            }
            break;

        default:
            throw new ODataException("Unsupported resource type " + uriInfo.getKind().name());
        }

        return response;
    }

    private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfo uriInfo, final Object content,
                                  final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<T> responseHandler) {

        try {
            httpEntityRequest.setEntity(writeContent(edm, uriInfo, content));

            final Header requestContentTypeHeader = httpEntityRequest.getEntity().getContentType();
            final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType;

            execute(httpEntityRequest, requestContentType, endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) {
                @SuppressWarnings("unchecked")
                @Override
                public void onCompleted(HttpResponse result) throws IOException, ODataException {

                    // if a entity is created (via POST request) the response
                    // body contains the new created entity
                    HttpStatusCode statusCode = HttpStatusCode.fromStatusCode(result.getStatusLine().getStatusCode());

                    // look for no content, or no response body!!!
                    final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0;
                    if (statusCode == HttpStatusCode.NO_CONTENT || noEntity) {
                        responseHandler.onResponse((T)HttpStatusCode.fromStatusCode(result.getStatusLine().getStatusCode()), headersToMap(result.getAllHeaders()));
                    } else {
                        if (uriInfo.getKind() == UriInfoKind.resource) {
                            List<UriResource> listResource = uriInfo.getUriResourceParts();
                            UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
                            switch (lastResourceKind) {
                            case entitySet:
                                if (content instanceof ClientEntity) {
                                    ClientEntity entity = odataReader.readEntity(result.getEntity().getContent(),
                                                                                ContentType.parse(result.getEntity().getContentType().getValue()));
                                    responseHandler.onResponse((T)entity, headersToMap(result.getAllHeaders()));
                                } else {
                                    throw new ODataException("Unsupported content type: " + content);
                                }
                                break;
                            default:
                                break;
                            }
                        } else if (uriInfo.getKind() == UriInfoKind.batch) {
                            List<Olingo4BatchResponse> batchResponse = parseBatchResponse(edm, result, (List<Olingo4BatchRequest>)content);
                            responseHandler.onResponse((T)batchResponse, headersToMap(result.getAllHeaders()));
                        } else {
                            throw new ODataException("Unsupported resource type: " + uriInfo.getKind().name());
                        }
                    }
                }
            });

        } catch (Exception e) {
            responseHandler.onException(e);
        } catch (Error e) {
            responseHandler.onException(new ODataException("Runtime Error Occurred", e));
        }
    }

    private AbstractHttpEntity writeContent(final Edm edm, final UriInfo uriInfo, final Object content) throws ODataException {
        InputStream requestStream = null;
        AbstractHttpEntity httpEntity = null;
        if (uriInfo.getKind() == UriInfoKind.resource) {
            // any resource entity
            List<UriResource> listResource = uriInfo.getUriResourceParts();
            UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
            switch (lastResourceKind) {
            case entitySet:
                if (content instanceof ClientEntity) {
                    requestStream = odataWriter.writeEntity((ClientEntity)content, getResourceContentType(uriInfo));
                } else {
                    throw new ODataException("Unsupported content type: " + content);
                }
                break;
            default:
                throw new ODataException("Unsupported resource type: " + lastResourceKind);
            }
            try {
                httpEntity = new ByteArrayEntity(IOUtils.toByteArray(requestStream));
            } catch (IOException e) {
                throw new ODataException("Error during converting input stream to byte array", e);
            }
            httpEntity.setChunked(false);

        } else if (uriInfo.getKind() == UriInfoKind.batch) {
            final String boundary = BOUNDARY_PREFIX + UUID.randomUUID();
            final String contentHeader = BATCH_CONTENT_TYPE + BOUNDARY_PARAMETER + boundary;
            final List<Olingo4BatchRequest> batchParts = (List<Olingo4BatchRequest>)content;

            requestStream = serializeBatchRequest(edm, batchParts, BOUNDARY_DOUBLE_DASH + boundary);
            try {
                httpEntity = new ByteArrayEntity(IOUtils.toByteArray(requestStream));
            } catch (IOException e) {
                throw new ODataException("Error during converting input stream to byte array", e);
            }
            httpEntity.setChunked(false);
            httpEntity.setContentType(contentHeader);
        } else {
            throw new ODataException("Unsupported resource type: " + uriInfo.getKind().name());
        }

        return httpEntity;
    }

    private InputStream serializeBatchRequest(final Edm edm, final List<Olingo4BatchRequest> batchParts, String boundary) throws ODataException {
        final ByteArrayOutputStream batchRequestHeaderOutputStream = new ByteArrayOutputStream();

        try {
            batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8));
            batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);

            for (Olingo4BatchRequest batchPart : batchParts) {
                writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_HTTP.toContentTypeString());
                writeHttpHeader(batchRequestHeaderOutputStream, ODataBatchConstants.ITEM_TRANSFER_ENCODING_LINE, null);

                if (batchPart instanceof Olingo4BatchQueryRequest) {
                    final Olingo4BatchQueryRequest batchQueryPart = (Olingo4BatchQueryRequest)batchPart;
                    final String batchQueryUri = createUri(StringUtils.isBlank(batchQueryPart.getResourceUri()) ? serviceUri : batchQueryPart.getResourceUri(),
                                                           batchQueryPart.getResourcePath(), concatQueryParams(batchQueryPart.getQueryParams()));
                    final UriInfo uriInfo = parseUri(edm, batchQueryPart.getResourcePath(), concatQueryParams(batchQueryPart.getQueryParams()));
                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);

                    batchRequestHeaderOutputStream.write((HttpGet.METHOD_NAME + " " + batchQueryUri + " " + HttpVersion.HTTP_1_1).getBytes(Constants.UTF8));
                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                    final ContentType acceptType = getResourceContentType(uriInfo);
                    final String acceptCharset = acceptType.getParameter(ContentType.PARAMETER_CHARSET);
                    writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT,
                            contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase());
                    if (null != acceptCharset) {
                        writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase());
                    }

                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                    batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8));
                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                } else if (batchPart instanceof Olingo4BatchChangeRequest) {
                    final Olingo4BatchChangeRequest batchChangePart = (Olingo4BatchChangeRequest)batchPart;
                    final String batchChangeUri = createUri(StringUtils.isBlank(batchChangePart.getResourceUri()) ? serviceUri : batchChangePart.getResourceUri(),
                                                            batchChangePart.getResourcePath(), null);
                    final UriInfo uriInfo = parseUri(edm, batchChangePart.getResourcePath(), null);

                    if (batchChangePart.getOperation() != Operation.DELETE) {
                        writeHttpHeader(batchRequestHeaderOutputStream, CONTENT_ID_HEADER, batchChangePart.getContentId());
                    }

                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                    batchRequestHeaderOutputStream
                        .write((batchChangePart.getOperation().getHttpMethod() + " " + batchChangeUri + " " + HttpVersion.HTTP_1_1).getBytes(Constants.UTF8));
                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                    writeHttpHeader(batchRequestHeaderOutputStream, HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
                    final ContentType acceptType = getResourceContentType(uriInfo);
                    final String acceptCharset = acceptType.getParameter(ContentType.PARAMETER_CHARSET);
                    writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT,
                            contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase());
                    if (null != acceptCharset) {
                        writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase());
                    }
                    writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.CONTENT_TYPE, acceptType.toContentTypeString());

                    if (batchChangePart.getOperation() != Operation.DELETE) {
                        batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                        AbstractHttpEntity httpEnity = writeContent(edm, uriInfo, batchChangePart.getBody());

                        batchRequestHeaderOutputStream.write(IOUtils.toByteArray(httpEnity.getContent()));
                        batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                        batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                    } else {
                        batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                    }

                    batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8));
                    batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
                } else {
                    throw new ODataException("Unsupported batch part request object type: " + batchPart);
                }
            }
        } catch (Exception e) {
            throw new ODataException("Error during batch request serialization", e);
        }
        return new ByteArrayInputStream(batchRequestHeaderOutputStream.toByteArray());
    }

    private void writeHttpHeader(ByteArrayOutputStream headerOutputStream, String headerName, String headerValue) throws IOException {
        headerOutputStream.write(createHttpHeader(headerName, headerValue).getBytes(Constants.UTF8));
        headerOutputStream.write(ODataStreamer.CRLF);
    }

    private String createHttpHeader(String headerName, String headerValue) {
        return headerName + (StringUtils.isBlank(headerValue) ? "" : (": " + headerValue));
    }

    private List<Olingo4BatchResponse> parseBatchResponse(final Edm edm, HttpResponse response, List<Olingo4BatchRequest> batchRequest) throws ODataException {
        List<Olingo4BatchResponse> batchResponse = new <Olingo4BatchResponse> ArrayList();
        try {
            final Header[] contentHeaders = response.getHeaders(HttpHeader.CONTENT_TYPE);
            final ODataBatchLineIterator batchLineIterator = new ODataBatchLineIteratorImpl(IOUtils.lineIterator(response.getEntity().getContent(), Constants.UTF8));
            final String batchBoundary = ODataBatchUtilities.getBoundaryFromHeader(getHeadersCollection(contentHeaders));
            final ODataBatchController batchController = new ODataBatchController(batchLineIterator, batchBoundary);

            batchController.getBatchLineIterator().next();
            int batchRequestIndex = 0;
            while (batchController.getBatchLineIterator().hasNext()) {
                OutputStream os = new ByteArrayOutputStream();
                ODataBatchUtilities.readBatchPart(batchController, os, false);
                Object content = null;
                final Olingo4BatchRequest batchPartRequest = (Olingo4BatchRequest)batchRequest.get(batchRequestIndex);
                final HttpResponse batchPartHttpResponse = constructBatchPartHttpResponse(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()));
                final StatusLine batchPartStatusLine = batchPartHttpResponse.getStatusLine();
                final int batchPartLineStatusCode = batchPartStatusLine.getStatusCode();
                Map<String, String> batchPartHeaders = getHeadersValueMap(batchPartHttpResponse.getAllHeaders());
                if (batchPartRequest instanceof Olingo4BatchQueryRequest) {
                    Olingo4BatchQueryRequest batchPartQueryRequest = (Olingo4BatchQueryRequest)batchPartRequest;
                    final UriInfo uriInfo = parseUri(edm, batchPartQueryRequest.getResourcePath(), null);

                    if (HttpStatusCode.BAD_REQUEST.getStatusCode() <= batchPartLineStatusCode && batchPartLineStatusCode <= AbstractFutureCallback.NETWORK_CONNECT_TIMEOUT_ERROR) {
                        final ContentType responseContentType = getContentTypeHeader(batchPartHttpResponse);
                        content = odataReader.readError(batchPartHttpResponse.getEntity().getContent(), responseContentType);
                    } else if (batchPartLineStatusCode == HttpStatusCode.NO_CONTENT.getStatusCode()) {
                        // nothing to do if NO_CONTENT returning
                    } else {
                        content = readContent(uriInfo, batchPartHttpResponse.getEntity().getContent());
                    }

                    Olingo4BatchResponse batchPartResponse = new Olingo4BatchResponse(batchPartStatusLine.getStatusCode(), batchPartStatusLine.getReasonPhrase(), null,
                                                                                batchPartHeaders, content);
                    batchResponse.add(batchPartResponse);
                } else if (batchPartRequest instanceof Olingo4BatchChangeRequest) {
                    Olingo4BatchChangeRequest batchPartChangeRequest = (Olingo4BatchChangeRequest)batchPartRequest;

                    if (batchPartLineStatusCode != HttpStatusCode.NO_CONTENT.getStatusCode()) {
                        if (HttpStatusCode.BAD_REQUEST.getStatusCode() <= batchPartLineStatusCode
                            && batchPartLineStatusCode <= AbstractFutureCallback.NETWORK_CONNECT_TIMEOUT_ERROR) {
                            final ContentType responseContentType = ContentType.parse(batchPartHttpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                            content = odataReader.readError(response.getEntity().getContent(), responseContentType);
                        } else {
                            final UriInfo uriInfo = parseUri(edm, batchPartChangeRequest.getResourcePath()
                                                                  + (batchPartChangeRequest.getOperation() == Operation.CREATE ? CLIENT_ENTITY_FAKE_MARKER : ""),
                                                             null);
                            content = readContent(uriInfo, batchPartHttpResponse.getEntity().getContent());
                        }
                    }
                    Olingo4BatchResponse batchPartResponse = new Olingo4BatchResponse(batchPartStatusLine.getStatusCode(), batchPartStatusLine.getReasonPhrase(),
                                                                                batchPartChangeRequest.getContentId(), batchPartHeaders, content);
                    batchResponse.add(batchPartResponse);
                } else {
                    throw new ODataException("Unsupported batch part request object type: " + batchPartRequest);
                }
                batchRequestIndex++;
            }

        } catch (IOException | HttpException e) {
            throw new ODataException(e);
        }
        return batchResponse;
    }

    private HttpResponse constructBatchPartHttpResponse(InputStream batchPartStream) throws IOException, HttpException {
        final LineIterator lines = IOUtils.lineIterator(batchPartStream, Constants.UTF8);
        final ByteArrayOutputStream headerOutputStream = new ByteArrayOutputStream();
        final ByteArrayOutputStream bodyOutputStream = new ByteArrayOutputStream();

        boolean startBatchPartHeader = false;
        boolean startBatchPartBody = false;

        // Iterate through lines in the batch part
        while (lines.hasNext()) {
            String line = lines.nextLine().trim();
            // Ignore all lines below HTTP/1.1 line
            if (line.startsWith(HttpVersion.HTTP)) {
                // This is the first header line
                startBatchPartHeader = true;
            }
            // Body starts with empty string after header lines
            if (startBatchPartHeader && StringUtils.isBlank(line)) {
                startBatchPartHeader = false;
                startBatchPartBody = true;
            }
            if (startBatchPartHeader) {
                // Write header to the output stream
                headerOutputStream.write(line.getBytes(Constants.UTF8));
                headerOutputStream.write(ODataStreamer.CRLF);
            } else if (startBatchPartBody && StringUtils.isNotBlank(line)) {
                // Write body to the output stream
                bodyOutputStream.write(line.getBytes(Constants.UTF8));
                bodyOutputStream.write(ODataStreamer.CRLF);
            }
        }

        // Prepare for parsing headers in to the HttpResponse object
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl(metrics, 2048);
        HttpResponseFactory responseFactory = new DefaultHttpResponseFactory();

        sessionInputBuffer.bind(new ByteArrayInputStream(headerOutputStream.toByteArray()));
        DefaultHttpResponseParser responseParser = new DefaultHttpResponseParser(sessionInputBuffer, new BasicLineParser(), responseFactory, MessageConstraints.DEFAULT);

        // Parse HTTP response and headers
        HttpResponse response = responseParser.parse();
        // Set body inside entity
        response.setEntity(new ByteArrayEntity(bodyOutputStream.toByteArray()));

        return response;
    }

    private Collection<String> getHeadersCollection(Header[] headers) {
        Collection<String> headersCollection = new ArrayList();
        for (Header header : Arrays.asList(headers)) {
            headersCollection.add(header.getValue());
        }
        return headersCollection;
    }

    private Map<String, String> getHeadersValueMap(Header[] headers) {
        Map<String, String> headersValueMap = new HashMap();
        for (Header header : Arrays.asList(headers)) {
            headersValueMap.put(header.getName(), header.getValue());
        }
        return headersValueMap;
    }

    private String createUri(String resourcePath) {
        return createUri(serviceUri, resourcePath, null);
    }

    private String createUri(String resourcePath, String queryOptions) {
        return createUri(serviceUri, resourcePath, queryOptions);
    }

    private String createUri(String resourceUri, String resourcePath, String queryOptions) {

        final StringBuilder absolutUri = new StringBuilder(resourceUri).append(SEPARATOR).append(resourcePath);
        if (queryOptions != null && !queryOptions.isEmpty()) {
            absolutUri.append("/?" + queryOptions);
        }
        return absolutUri.toString();

    }

    private String concatQueryParams(final Map<String, String> queryParams) {
        final StringBuilder concatQuery = new StringBuilder("");
        if (queryParams != null && !queryParams.isEmpty()) {
            int nParams = queryParams.size();
            int index = 0;
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                concatQuery.append(entry.getKey()).append('=').append(entry.getValue());
                if (++index < nParams) {
                    concatQuery.append('&');
                }
            }
        }
        return concatQuery.toString().replaceAll("  *", "%20");
    }

    private static UriInfo parseUri(Edm edm, String resourcePath, String queryOptions) {
        Parser parser = new Parser(edm, OData.newInstance());
        UriInfo result;

        try {
            result = parser.parseUri(resourcePath, queryOptions, null);
        } catch (UriParserException | UriValidationException e) {
            throw new IllegalArgumentException("parseUri (" + resourcePath + "," + queryOptions + "): " + e.getMessage(), e);
        }
        return result;
    }

    private static Map<String, String> headersToMap(final Header[] headers) {
        final Map<String, String> responseHeaders = new HashMap<>();
        for (Header header : headers) {
            responseHeaders.put(header.getName(), header.getValue());
        }
        return responseHeaders;
    }

    public void execute(HttpUriRequest httpUriRequest, ContentType contentType, final Map<String, String> endpointHttpHeaders, FutureCallback<HttpResponse> callback) {
        // add accept header when its not a form or multipart
        if (!ContentType.APPLICATION_FORM_URLENCODED.equals(contentType) && !contentType.toContentTypeString().startsWith(MULTIPART_MIME_TYPE)) {
            // otherwise accept what is being sent
            httpUriRequest.addHeader(HttpHeaders.ACCEPT,
                    contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase());
            final String acceptCharset = contentType.getParameter(ContentType.PARAMETER_CHARSET);
            if (null != acceptCharset) {
                httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase());
            }
        }

        // is something being sent?
        if (httpUriRequest instanceof HttpEntityEnclosingRequestBase && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
            httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
        }

        // set user specified custom headers
        if (ObjectHelper.isNotEmpty(httpHeaders)) {
            for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
                httpUriRequest.setHeader(entry.getKey(), entry.getValue());
            }
        }

        // set user specified endpoint headers
        if (ObjectHelper.isNotEmpty(endpointHttpHeaders)) {
            for (Map.Entry<String, String> entry : endpointHttpHeaders.entrySet()) {
                httpUriRequest.setHeader(entry.getKey(), entry.getValue());
            }
        }

        // add 'Accept-Charset' header to avoid BOM marker presents inside
        // response stream
        if (!httpUriRequest.containsHeader(HttpHeaders.ACCEPT_CHARSET)) {
            httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, Constants.UTF8.toLowerCase());
        }

        // add client protocol version if not specified
        if (!httpUriRequest.containsHeader(HttpHeader.ODATA_VERSION)) {
            httpUriRequest.addHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
        }
        if (!httpUriRequest.containsHeader(HttpHeader.ODATA_MAX_VERSION)) {
            httpUriRequest.addHeader(HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString());
        }

        // execute request
        if (client instanceof CloseableHttpAsyncClient) {
            ((CloseableHttpAsyncClient)client).execute(httpUriRequest, callback);
        } else {
            // invoke the callback methods explicitly after executing the
            // request synchronously
            try {
                CloseableHttpResponse result = ((CloseableHttpClient)client).execute(httpUriRequest);
                callback.completed(result);
            } catch (IOException e) {
                callback.failed(e);
            }
        }
    }
}


text:
Q: Efficacy and Purpose of AntiForgery.Validate in AJAX calls The MVC4 SPA template has a ValidateHttpAntiForgeryTokenAttribute class with a ValidateRequestHeader function that parses out 2 halves of a RequestVerificationToken header constructed by the client when it assembles the data for an AJAX call. The client AJAX code gets its value from a field on the form that combines a form token and a cookie token. I feel like combining these into a single value loses sight of the purpose of an AntiForgery token; they were separate for a reason. Do we gain any security by using anti-forgery tokens in this way?
Server .vbhtml code (Razor-based):
Public Function GetAntiForgeryToken() As String
    Dim cookieToken As String = String.Empty
    Dim formToken As String = String.Empty

    AntiForgery.GetTokens(Nothing, cookieToken, formToken)
    Return cookieToken & ":" & formToken
End Function

...
@If User.Identity.IsAuthenticated Then
    @<input id="antiForgeryToken" type="hidden" value="@GetAntiForgeryToken()" />
End If

Client AJAX code:
function ajaxRequest(type, url, data, dataType) { // Ajax helper
    var options = {
        dataType: dataType || "json",
        contentType: "application/json",
        cache: false,
        type: type,
        data: data ? ko.toJSON(data) : null
    };
    var antiForgeryToken = $("#antiForgeryToken").val();
    if (antiForgeryToken) {
        options.headers = {
            'RequestVerificationToken': antiForgeryToken
        }
    }
    return $.ajax(url, options);
}

Server validation code:
Private Sub ValidateRequestHeader(request As HttpRequestMessage)
    Dim cookieToken As String = String.Empty
    Dim formToken As String = String.Empty

    Dim tokenHeaders As IEnumerable(Of String) = Nothing
    If request.Headers.TryGetValues("RequestVerificationToken", tokenHeaders) Then
        Dim tokenValue As String = tokenHeaders.FirstOrDefault()
        If Not String.IsNullOrEmpty(tokenValue) Then
            Dim tokens As String() = tokenValue.Split(":"c)
            If tokens.Length = 2 Then
                cookieToken = tokens(0).Trim()
                formToken = tokens(1).Trim()
            End If
        End If
    End If

    AntiForgery.Validate(cookieToken, formToken)
End Sub

What prevents a client from picking any arbitrary pair of cookieToken and formToken that was used in the past, and submitting them together in an AJAX call to get it to go through? Isn't that what anti-forgery functions are supposed to prevent? Is this just a lot of stupid overhead that doesn't improve security, or is there a piece of it that I'm missing?

A:
What prevents a client from picking any arbitrary pair of cookieToken and formToken that was used in the past, and submitting them together in an AJAX call to get it to go through? Isn't that what anti-forgery functions are supposed to prevent? Is this just a lot of stupid overhead that doesn't improve security, or is there a piece of it that I'm missing?

The anti-forgery token is not designed to prevent a Replay Attack. This is where old values are reused to create another request where the aim is to fool the target machine into accepting a valid instruction from the past.
The anti-forgery token is designed to prevent Cross Site Request Forgery attacks.
A simple example is as follows:

*

*You're logged into bank.com on one tab.

*You get an email to view a funny video by clicking on a link that redirects you to
evil.com

*The web page on evil.com contains a hidden form that is submited by JavaScript to bank.com/make_money_transfer
As you are logged into bank.com and your cookies are sent by the browser, bank.com thinks that you made the request and initiates the money transfer without your knowledge, because from the server's point of view, all is well.
The token is designed to prevent this by having something included in the request payload that cannot be auto submitted by a domain that is not the current domain. Due to the Same Origin Policy another domain cannot access the token value and therefore cannot send a legitimate request via a hidden form, or by any other means. The token is unique per log in session so the attacker could not get a valid combination of token and cookie which can be sent to the server.
Looking at the source code for TokenValidator.cs (albeit C# instead of VB.NET) we can see that the ValidateTokens method checks that the username encoded in the token matches the one of the current HTTP request:
if (!String.Equals(fieldToken.Username, currentUsername, (useCaseSensitiveUsernameComparison) ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
{
     throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, currentUsername);
}

This is what will stop an attacker grabbing an old version of the form field value and submitting that in their CSRF attack - their encoded username will not match the logged in user of their victim.

redpajama_set_name: RedPajamaStackExchange


text:
German Shipbuilding Restructured: UAE's Firm Buys Blohm+Voss
ADM naval deal unravels, new strategy for TKMS.
Sachsen, sending SM-2
In October 2009, ThyssenKrupp Marine Systems (TKMS) effectively sold most of its naval and commercial surface shipbuilding assets, via a "close strategic partnership" and Memorandum of Understanding with the Abu Dhabi MAR (ADM) group in the United Arab Emirates. The proposed sale followed related purchases in Germany by Abu Dhabi MAR, and other recent shipyard sales by TKMS. The net effect was a restructuring of Germany's naval shipbuilding industry.
The envisioned agreement involved a 50/50 joint venture to build naval surface ships, with TKMS retaining a lead role and know-how in all projects with the German Navy and NATO partners, while ADM was responsible for the Middle East and North Africa. At the same time, however, Abu Dhabi MAR would acquiring 80% of TKMS' key surface ship firms: Blohm + Voss Shipyards, Blohm + Voss Repair, and Blohm + Voss Industries. That deal has largely fallen through in 2011, leaving TKMS naval assets in play again.
TKMS: The Restructuring
TKMS Organization
TKMS' listing of its management companies in Germany makes the importance of the ADM transaction clearer. Howaldtswerke-Deutsche Werft (HDW) focuses on submarines, including construction, repairs, upgrades, and mid-life conversions. It will remain wholly in TKMS, though Hellenic Shipyards, which is building HDW U214 submarines in Greece, was sold to Abu Dhabi MAR in March 2010.
The Swedish submarine, surface vessel, and USV/UUV designers and builders at Kockums AB also add submarine expertise to TKMS as well, but they are not noted in the above graphic, and were not sold.
Subsidiaries TKMS Blohm + Voss and Nordseewerke GmbH are responsible for naval surface vessels, special purpose ships, and commercial ships. Nordseewerke GmbH was sold to SIAG Schaaf Industrie, and will now make wind farm equipment.
Blohm + Voss was to be majority (80%) owned by Abu Dhabi MAR under the new arrangements, but reverts now to TKMS. In 2011, Blohm + Voss was divided into Blohm + Voss Naval GmbH, which specializes in military shipbuilding, and its civil businesses.
Blohm + Voss Shipyards and Services GmbH handles yachts, ship repair and mid-life conversions, offshore work, ship components, and technical services. Both Blohm + Voss Repair and Blohm + Voss Industries fall under this group, and together they represented the effective sale of this group to Abu Dhabi MAR.
Under its current plan, confirmed in May 2011, TKMS will keep military shipbuilders HDW, Kockums AB, and Blohm + Voss Naval, while selling the HDW-Gaarden Kiel facility, and the Nobiskrug super-yacht builders and repair facility in Rendsburg, to Abu Dhabi MAR.
ThyssenKrupp are still looking to sell all other civil shipbuilding components, and external estimates say that their overall restructuring in and beyond their shipbuilding businesses will represent the sale of about EUR 10 billion ($14.5 billion) in assets, depending on final deal prices.
Opportunities Lost, and Gained
K130 corvette concept
These restructurings aimed to change the future for both sides of the deal.
Back in 2009, ThyssenKrupp put a positive face on things. Submarines remained a source of strength worth keeping, and the planned joint venture would improve export opportunities for its frigates and corvettes, especially in the middle east. TKMS' K130 Braunschweig class corvettes might have been quite suitable for the UAE, for instance; instead, Fincantieri will provide 1-2 corvettes based on its Commandanti class. This had been a frequent pattern for Blohm + Voss. The firm has fielded a string of fine ship designs, from its various MEKO OPV/ corvette/ frigate options, to the F124 Saschen class advanced air defense frigate and the new F125 expeditionary frigate. Of these, only the MEKO has enjoyed export success.
That history in the military market, and the difficulty of making any money in the heavily subsidized world of commercial shipbuilding, left German domestic politics on the sidelines for the sale. Germany had sovereign wealth funds, Russia, and middle eastern buyers in mind when it enacted the German Foreign Trade and Payments Act in 2007, and created obstacles to buyouts of important German firms. Yet political reactions across the spectrum in Germany believed that the government would approve the sale with little to no protest, given the lack of viable alternatives. That is exactly what happened.
TKMS continues to shop for a buyer to take Blohm + Voss off its hands, and has reiterated its future in military-only shipbuilding. The general sense is that their restructuring has been delayed, but not prevented.
The United Arab Emirates has significant oil revenues and sovereign wealth resources in Abu Dhabi, and Dubai has made great strides toward becoming a business and financial hub for the Arab and Islamic world. In 2009, it was hard not to see the TKMS deal as one data point within a larger global economic power shift toward resource and goods producer societies in the Middle East and Asia.
That has attenuated somewhat, but even without the naval shipbuilding component, Abu Dhabi MAR's acquisitions have created a very strong player in the mega-yacht sector. ADM will keep those additions, and orders may pick up in future, but the current period is one of consolidation and survival, following the twin blows of the 2008 global economic crisis, and then the 2011 "Arab Spring."
Abu Dhabi MAR Group had acquired about a 12% share of the mega-yacht market before the 2009 deal, which may yetleave them in a good position if they can manage to successfully integrate 4+ shipyards in 3 countries into a single, functioning entity. No mean feat, that, but this is where the firm placed its bets. Given the Middle East's status as a key order center for super-yachts, a local player may indeed be able to gain traction, and key intelligence, that others lack.
Meanwhile, the Nobiskrug yacht-building facility bought from TKMS also has a 60 meter patrol vessel design on the drawing board, the Nobis FAC60. Vessels of that type can be very useful in the Arabian/Persian Gulf region, and it remains to be seen if Abu Dhabi MAR will make use of that asset in future.
Contracts & Key Events
July 1/11: Hans-Joachim Otto, the German federal Minister for Economics & Technology, says the German government is willing to serve as a facilitator for negotiations over the sale of Blohm + Voss' civilian shipbuilding business.
"We have a strong interest in seeing that the Hamburg base is not only maintained but even extended," Otto told Reuters.
June 30/11: The Abu Dhabi MAR deal officially unravels. Blohm + Voss reverts to TKMS control, and the 50/50 JV for marketing naval surface ships in the Middle East and North Africa is also dead. From ThyssenKrupp:
"Following two years of amicable talks and negotiations exploring the joint-venture both ThyssenKrupp Marine Systems and Abu Dhabi MAR have agreed to cease their efforts… opportunities previously identified are no longer commercially viable. The scope of the originally envisaged transaction between the two parties will now relate exclusively to the civil activities of HDW-Gaarden in Kiel… only formal regulatory approval now needs to be obtained.
For the civil operations of Blohm+Voss we are working without delay [on selling them to] new owners… In line with the strategic development program resolved on May 13, ThyssenKrupp Marine Systems will concentrate in the future on military shipbuilding. This involves our high-tech capacities for submarine system integration at HDW in Kiel and Kockums in Sweden as well as our design, equipment and project management capabilities for military surface vessels at Blohm+Voss Naval in Hamburg."
The firm adds that a naval vessel export success is imminent – could this be Israel's interest in a version of their MEKO design its future frigate, after a much-modified version of Lockheed Martin's Freedom class Littoral Combat Ship proved to be too expensive? Emirates 24/7 | Qatar's Gulf Times || Bloomberg | Expatica Germany | Marine Log | The Motorship | Reuters.
Sept 15/10: A contract to sell off Hellenic Shipyards to Abu Dhabi MAR is signed with Greek government approval, but must be ratified by the Greek Parliament. Meanwhile, Greece will accept the U214 submarine Papanikolis. And instead of refurbishing 2 U209 boats, the Greek government wants to spend EUR 175 million more to convert that into a purchase of 2 more U214 submarines. The move would keep Hellenic Shipyards open and working for a while longer. Agence France Presse via Defense News | AFP via Expatica | BYM Marine & Martime News | Capital.GR | Reuters.
Sept 1/10: The Hellenic Shipyards sale isn't quite done yet, as setbacks have hit the deal. Greek Defence Minister Evangelos Venizelos has held a 2nd round of talks with Thyssenkrupp AG and Abu Dhabi MAR Group. Legal advisers are reportedly drafting a final agreement to submit to the Greek government. Bloomberg.
March 1/10: Greece approves the sale of Hellenic Shipyards to Abu Dhabi MAR. The new joint venture will be led by ADM with 75.1% of the share capital of Skaramanga shipyard (HSY), with ThyssenKrupp Marine Systems participating with 24.9%. The move gives ADM something its earlier arrangements with TKMS did not include: submarine construction capability.
ThyssenKrupp fully acquired HSY in 2005, as part of its contract to deliver 4 U214 submarines to the Greek Navy. The firm picked Abu Dhabi MAR in January 2010 as the preferred bidder for a majority stake; no details were disclosed, but TKMS had reportedly said in the past that the shipyards, which depend on Greek navy orders, would be sold at the price of one euro. The firm had already declared the Greek government to be in default on the U-214 contract. ThyssenKrupp reportedly received 5 bids for HSY, but found only Abu Dhabi MAR's to be acceptable. Khaleej Times | Reuters.
Oct 15/09: The Memorandum of Understanding between ThyssenKrupp Marine Systems and Abu Dhabi MAR is announced. All parties will now hold further talks and negotiations based on the MoU, with the transaction still subject to the approval of German supervisory bodies and the regulatory authorities. The business daily Handelsblatt is brutally frank:
"ThyssenKrupp's executive board has succeeded in accomplishing what few thought possible – a coup that liberates it from its shipbuilding division… It had no other choice. Thanks to the ongoing economic crisis, the company has its back against the wall. Its losses are piling up, and both politicians and unions are reducing any wiggle room the company's management might still have. In civil shipbuilding, the situation is hopeless… and things are hardly any better in the military branch. The only area in which Thyssen has remained competitive is in submarine construction, which will remain in German hands."
See also: ThyssenKrupp Marine Systems | Abu Dhabi MAR site | Der Spiegel's roundup | Al-Bawaba | AP, via Forbes | Bloomberg | Reuters, via Forbes | Synfo.
Oct 5/09: TKMS issues a statement to the superyacht coverage site Synfo. It includes this excerpt:
"The international market for shipbuilding activities is dominated by over-capacity and finds itself in a consolidation phase. In recent months in Germany and internationally a number of shipyards, including some with a long tradition in the industry, have become insolvent or have only been able to continue operating with state support.
Against this background, ThyssenKrupp Marine Systems – like its competitors – conducts discussions in both the national and the international context on ways of dealing with the structural and cyclical crisis which has affected shipbuilding particularly badly."
Sept 29/09: Germany's ThyssenKrupp Marine Systems (TKMS) sells its Nordseewerke shipyard in Emden to wind power plant manufacturer SIAG Schaaf Industrie. Nordseewerke will continue to launch and outfit ships already in process, but 2 frigates slated to be built there will now be built by Blohm + Voss in Hamburg, TKMS' remaining surface ship firm.
Following a transition period expected to last into 2011, Nordseewerke's Emden yard will become a production site for towers and main frames for offshore wind energy plants, as well as underwater foundation structures including monopiles, transition pieces and jackets. SIAG Schaaf will take control of the Emden facility on Oct 1/09. For the ramp-up phase, an annual capacity of 100 offshore towers, 60 main frames, 25 monopiles, 25 transition pieces and 25 jackets is being scheduled.
SIAG will take on 721 of the roughly 1,200 Nordseewerke employees. About 375 of the remaining employees will remain with TKMS, and 115 of those will remain in Emden. About 100 others will either resign or take retirement. MarineLog.
July 10/09: Abu Dhabi MAR's principals acquire a controlling interest in Nobiskrug, a German superyacht builder with a 173,000 square meter facility in Rendburg. The firm already had "common shareholding" with the French superyacht builder CMN in Cherbourg, and these shipyards have been consolidated under the Abu Dhabi MAR Group. They join a recently-built 200,000 square meter facility at Port Sayed, Abu Dhabi, UAE that is currently working on converting 2 Dutch Kortenaer class frigates from UAE Navy service to private superyachts.
Synfo's report adds that there are 83 known superyacht orders, of which the combined Abu Dhabi MAR group is contracted for 10, or about 12% of the global order book.
DID – Greece in Default on U-214 Submarine Order. Explains the background behind Hellenic Shipyards.
Der Spiegel (Aug 11/09) – The Container Crisis: Shipping Industry Fights for Survival
Categories: Europe - Other, Germany, Issues - International, Issues - Political, Mergers & Acquisitions, Middle East - Other, Other Corporation, Partnerships & Consortia, Surface Ships - Combat, Surface Ships - Other

redpajama_set_name: RedPajamaCommonCrawl


text:
Palonosetron: A novel approach to control postoperative nausea and vomiting in day care surgery
Sukhminderjit Singh Bajwa1, Sukhwinder Kaur Bajwa2, Jasbir Kaur1, Veenita Sharma1, Amarjit Singh1, Anita Singh2, SPS Goraya2, SS Parmar1, Kamaljit Singh3,
1 Department of Anaesthesiology and Intensive Care, Gian Sagar Medical College & Hospital, Ram Nagar, Banur, Punjab, India
2 Department of Obstetrics & Gynaecology, Gian Sagar Medical College & Hospital, Ram Nagar, Banur, Punjab, India
3 Department of Biochemistry and Central Laboratory Services, Gian Sagar Medical College & Hospital, Ram Nagar, Banur, Punjab, India
Sukhminderjit Singh Bajwa
Department of Anaesthesiology and Intensive Care, Gian Sagar Medical College & Hospital, Ram Nagar, Banur, Punjab
Background: Postoperative nausea and vomiting (PONV) is one of the complications which hamper the successful implementation of day care surgical procedure in spite of the availability of so many antiemetic drugs and regimens for its prevention. The aim was to compare the prophylactic effects of intravenously (IV) administered ondansetron and palonosetron on PONV prevention in patients undergoing laparoscopic gynecological surgery under general anesthesia. Methods: A prospective double-blind study comprised of 60 ASAI/II female patients between the age group of 25 and 40 years was carried out in the Departments of Anesthesiology and Obstetrics and Gynecology of our institute. Patients were randomly divided into two groups of 30 patients each in a double-blind manner. Group I received 8 mg of inj. ondansetron IV while group II received inj. palonosetron 0.075 mg IV 5 minutes before the induction of anesthesia. The need for rescue antiemetics, episodes of PONV and other side effects were observed for 6 hours in the postanesthesia care unit and thereafter complaints were received on phone after the discharge. At the end of study, results were compiled and statistical data was subjected to statistical analysis using Student two-tailed «SQ»t«SQ» and c2 test and value of P<0.05 was considered significant. Results: The demographical profile of the patients was comparable. Twenty and 13.33% of the patients in group I had nausea and vomiting episodes postoperatively as compared to 6.67% and 3.33%, respectively, in group II which was statistically significant (P<0.05). Twenty percent of the patients in group I experienced significant post-op headache as compared to 6.67% in group II. The mean rescue dose of antiemetic was significantly higher (10.6 mg) in the group I as compared to group II (6.4 mg) (P=0.036). The rest of parameters were comparable and statistically nonsignificant. Conclusions: Palonosetron is a comparatively better drug to prevent the PONV in patients undergoing day care surgical procedures as compared to ondansetron as it has got a prolonged duration of action and favorable side-effects profile.
Bajwa SS, Bajwa SK, Kaur J, Sharma V, Singh A, Singh A, Goraya S, Parmar S S, Singh K. Palonosetron: A novel approach to control postoperative nausea and vomiting in day care surgery.Saudi J Anaesth 2011;5:19-24
Bajwa SS, Bajwa SK, Kaur J, Sharma V, Singh A, Singh A, Goraya S, Parmar S S, Singh K. Palonosetron: A novel approach to control postoperative nausea and vomiting in day care surgery. Saudi J Anaesth [serial online] 2011 [cited 2021 Jan 21 ];5:19-24
Available from: https://www.saudija.org/text.asp?2011/5/1/19/76484
The popularity of day care surgery is on the rise since the last two decades. This has been made possible by a variety of factors including development of preanesthetic out-patient departments (OPDs), administration of lesser emetogenic anesthetic techniques, availability of modern monitoring devices for recovery period and advent of newer drugs for the prophylaxis of postoperative nausea and vomiting (PONV). The advantage of returning to the homely environment on the same day of surgery drive people of almost all the age groups to prefer surgery on outpatient basis. Lesser occupancy of hospital beds, lower incidence of infection, lower cost-benefit ratio and early resumption of professional and social activities are among the other possible benefits of day care procedures. [1],[2] Smooth delivery of day care surgical services requires a highly dedicated staff, appropriate health infrastructure, adequate resources, established procedural guidelines as well as fully co-operative patients and their attendants. [3] As a result of so many huge requirements for efficiently delivering the day care services, protocols and guidelines of developed nations cannot be uniformly applied to the patients of developing world. In spite of all the advancements in day care surgery, PONV still remains a 'big little problem'. [4] PONV is considered one of the most unpleasant postoperative discomforts in day care surgery which has got an incidence of 30-40% in normal population undergoing general anesthesia, while the incidence touches a peak of 75-80% in certain high-risk groups. [5],[6] The incidence of PONV in the beginning of 19th century was quite high and used to be around 70-80% with the use of ether. With the use of modern-day anesthesia practices, the incidence of PONV has come down by 50% especially with the use of nonopioid medications for pain relief. [7] There is a strong correlation between the amount of postoperative use of opioids for pain relief and incidence of PONV and in one clinical trial it was established that dose reduction of opioids to half in 24 hour period can reduce the incidence of PONV by 6%. The amount of opioid administration should be carefully titrated so as to have minimal effect on the effectiveness of antiemetic drugs. [8],[9] The risk and incidence of PONV with postoperative opioids use further increases if the opioids are delivered by patient-controlled analgesia. [10] The incidence of PONV is 5% in infants, 25% below 5 years, 40-50% in the 5-15 age group and 20-40% in adults. [11] The incidence of PONV is surprisingly less in the smokers as compared to nonsmokers but on the other hand the incidence of PONV is more in the patients who have history of sickness after consumption of alcohol. Most studies have found that incidence of PONV increases 1.5-2.5 times in patients with nonsmoking history and the incidence increases from 1.8 to 3.1 times in patients with prior history of motion sickness or PONV or both. [12],[13],[14]
The complete knowledge about the risk factors responsible for PONV helps in designing the treatment regimens and interventions for its control. PONV poses a great challenge to the surgeon as well as anesthesiologist as it causes a great discomfort, delay in discharge, increased readmissions to hospital, pulmonary complications and a delayed resumption of daily chores. Throughout the world, great amount of resources, time, capital and dedicated efforts are spent to find a better alternative for prevention of this irritating disturbance. [15],[16] There is hardly any antiemetic drug available, which is complete in itself in suppression of PONV and the present generation of drugs just projects the picture of a mirage as far as adequate control of PONV is concerned. Although numerous pharmacological agents, regimens and techniques have evolved from time to time, they have limited efficacy due to various side effects and cost considerations. Nonpharmacological techniques like acupressure, acupuncture, accustimulation, etc. have been given various trials but their success is limited. [17],[18]
The advent of 5-HT3 antagonists in medical practice has provided a great relief to the physicians, oncologists and anesthesiologists. [19] These pharmacological agents are as effective as any other antiemetic drug but with a more safety and favorable side-effects profile as they lack the sedative, dysphoric and extra-pyramidal side effects of other commonly used antiemetics. [20] All the 5-HT3 antagonists like ondansetron, dolasetron, granisetron, azasetron, tropisetron and palonosetron have a favorable drug profile and a long duration of antiemetic action (4-48 hours). Ondansetron is being routinely used throughout the world, either alone or in combination with other drugs, for the prophylaxis of PONV in day care surgery mainly because of its lower cost. Among these agents, palonosetron has got a far higher receptor affinity and a much longer half-life which confer a prolonged duration of action. [21] The long duration of antiemetic effect is quite beneficial in preventing the problem of PONV in day care procedures. The extensive research in the prevention of PONV has established 0.075 mg as the minimum effective dose of palonosetron and the same has been approved by FDA for PONV prophylaxis.[22],[23] Patient characteristics, type of surgical procedure, duration of anesthesia and surgery are few of the important determinants of day care surgery and the procedures lasting for more than an hour are considered unsuitable for such selection. Risk factors for PONV include younger age, female gender, history of PONV and motion sickness, anxiety, nonsmoking status, history of migraine, certain ethnicities, general anesthesia, nitrous oxide, decreased perioperative fluids administration, increased duration of surgery, type of surgery such as laparoscopy, ear surgery, strabismus surgery and certain postoperative factors like pain, opioid analgesics and hypotension. [24] Gynecological patients are usually young and healthy. Females in the poor and developing countries like India are committed to their domestic and professional work as well as to the care of their family members. As a result of these commitments and obligations, these patients like to resume their daily chores as soon as possible and for them day care procedures with minimal postoperative discomfort are the preferred choices. In patients undergoing bilateral laparoscopic tubal ligation, CO 2 levels as well as manipulation of visceral tissues during laparoscopy are potent emetogenic stimuli.[12],[25] The role of long acting 5-HT3 antagonist acquires a greater dimension in prevention of PONV when such patients are operated on day care basis.
Keeping in consideration, the benefits of day care procedures and the long duration of antiemetic effect of palonosetron, we carried out a study in our institute consisting of 60 female patients, selected randomly, who underwent bilateral laparoscopic tubal ligation to see the comparative efficacy of ondansetron and palonosetron in the prophylaxis of PONV.
The present study was approved by the ethical committee of the institution and a written consent was taken from the patients after explaining to them in detail about the implications of the anesthetic and the surgical procedure. The selection criteria comprised of 60 ASA I/II patients between the age of 25 and 40 years who underwent bilateral laparoscopic tubal ligation surgery. Only those patients were chosen for study that lived in vicinity of 10-15 km radii from the institute and having a communication (mobile and landline phones) and personal transportation modes. The patients with ASA III/IV status, psychiatric diseases, diabetes, history of drug abuse, duration of surgery more than 1 h, chronic obstructive pulmonary disease, previous history of motion sickness and PONV, patients in premenstrual phase and body mass index >35 were excluded from the study.
A consultant anesthesiologist assessed all the patients in the evening before the surgery for preanesthetic evaluation. Patients were given a written set of information and instructions on preoperative preparation and postoperative care by the gynecologist to be followed as well as side effects to be observed for during the next 3 days. Patients were admitted in the early morning on the day of surgery. They were prescribed premedication with tablet ranitidine 150 mg and alprazolam 0.25 mg a night before and 2 hours prior to the surgical procedure. After securing a good IV access in the pre-op room patients were shifted to operation theatre and monitoring devices for ECG, heart rate, oxygen saturation and end-tidal carbon dioxide were attached. Pre-loading was done with 10 ml/kg body weight of Ringer lactate solution. Patients were randomly divided into two groups in a double-blinded manner with the help of computer-generated codes. Group I received 8 mg ondansetron IV while group II received 0.075 mg inj. palonosetron IV 5 minutes before the anesthesia procedure. These syringes were prepared by an anesthesia technician who was given a written set of instructions and was unaware of the procedure in the operation room. Induction of anesthesia in both the groups was achieved with inj. propofol 2 mg/kg body weight, inj. fortwin 20 mg and inj. midazolam 1 mg. Inj. atracurium 0.5 mg/kg body weight was administered for muscle relaxation and to aid in intubation. Maintenance of anesthesia was done with Inj. propofol 2 mg/kg/hr and atracurium 0.1 mg/kg given as per requirement. Patients were mechanically ventilated and were given 50% oxygen in air and a low dose of halothane. Infusion of diclofenac sodium 75 mg was administered during the procedure along with injection ranitidine 40 mg. After the completion of laparoscopic procedure, patients were given inj. reversal (neostigmine 2.5 mg and 0.5 mg of glycopyrrolate) and after thoroughly doing the oral suction, patients were extubated in a fully awake state. Patients were assessed in the recovery room both by the anesthesiologist and the gynecologist at every 15 mins interval for the first hour and at 30 mins interval thereafter. Any other complications like pain, PONV, etc. was looked for and recorded. Patients were discharged from the recovery room only after they fulfilled the following criteria.
Tolerating oral plain fluidsPatients were able to go to toilet by themselvesAble to pass urine spontaneouslySubjective feeling of betterment and a feel that they can manage themselvesPresence of an adult person to accompany them.Instructions written on the paper were reminded to them again verbally. Patients of both the groups were prescribed tab ondansetron 4 mg with a maximum dose of 12 mg/day as rescue antiemetic in case of any episode of nausea and vomiting at home. Oral diclofenac sodium was prescribed two times a day as rescue analgesic along with tablet ranitidine three times daily for the next 2 days. During the follow-up most of these patients recalled the postsurgical period as satisfactory and pleasant barring few complaints by small number of patients. At the end of the study all the data was systematically compiled and was subjected to Student two-tailed 't' test and χ2 test. Value of P<0.05 was considered as significant.
From January 2010 to May 2010, a total of 60 patients were evaluated randomly for day care laparoscopic tubal ligation. Results were prepared after questioning the patients during follow-up of postoperative period.
The demographic profile of the patients for the present study revealed no significant comparative difference between the two groups with respect to age, body weight, ASA grading, parity status and family income (P>0.05). However, the mean dose of recue antiemetic consumption was higher in the ondansetron group (10.6 mg) in the first 24 hours as compared to palonosetron group (64 mg) which on statistical comparison proved to be a significant entity (P=0.036) [Table 1]. Mean duration of surgery as well as mean duration of anesthesia was comparable in both the groups and on statistical analysis revealed no significant difference (P>0.05) [Table 1]. The number of patients who had episodes of nausea in immediate postoperative period were one in first one hour, another one in 1-6 hour period, two patients in period between 6 and 12 hours, one new patient in 12-24 hours and only one patient had episode of nausea after 24 hours in group I. In comparison, group II had one patient who suffered form nausea in the 1-6-hour period and another one in 6-12-hour period. Similarly, it was observed that four patients from group I and only 1 patient from group II had vomiting episodes in the first 24-hour period. The statistical values were significant in comparison (P<0.05) especially in the 6-12-hour period between both the groups [Table 2].{Table 1}{Table 2}
It is very clearly evident that incidence of side effects are comparatively much lower in group II. The incidence of postoperative headache was significantly higher in the group I (P<0.05). The incidence of other side effects like pain, anxiety dizziness, constipation and myalgia were comparable and on statistical analysis revealed no significant difference (P>0.05) [Table 3]. {Table 3}
Day care surgery has proven over the years as the best method to reduce the burden on the health care resources as well as achievement of extreme patient satisfaction. [26] In developing countries like India, per capita income is much lower and most of the patients avoid bearing expenses of the prolonged hospital stay. In contrast to that, the health infrastructure in our country is not organized uniformly to smoothly deliver the day care procedures. Consequently the international guidelines formulated for such outpatient procedures are not easy to implement completely in poor and developing nations as compared to countries of developed world. In the present day scenario, PONV still remains a big headache and nuisance for the surgeons and anesthesiologists as well as an irritating discomfort for the patients almost equal in intensity to pain. [15],[27] The delayed convalescence, hospital readmission, delayed return to work of ambulatory patients; postoperative surgical morbidities such as pulmonary aspiration, wound dehiscence, bleeding from the wound and metabolic derangement due to excessive emetic episodes are few of the adverse consequences of the PONV. [24] To compound the problems further, the lack of reliable and efficient transport, poor education level, lack of awareness, poorly developed referral system; underdeveloped communication systems, partially functioning primary healthcare services, and absence of community nursing have prevented the successful introduction of major surgical operations as day care surgery.
It is very difficult to predict the outcome in an individual patient as various other causes, besides the established risk factors, can influence the incidence of PONV. Various drugs regimens and antiemetic interventions have been tried fro time-to-time for prevention of PONV but with a variable success rate. The present study was carried out mainly to see the comparative efficacy of the new and much promising long-acting 5-HT3 antagonist palonosetron against ondansetron in day care surgery. The duration of surgery and anesthesia, type of surgery, young female patients, increased postoperative opioid requirements, etc., are few of the extensively studied risk factors. [12],[25] The demographic profile of our patients was quite similar with majority of other research investigations and provided us the uniform platform to evenly compare the results obtained.[27],[28] The mean duration of anesthesia and surgery were almost comparable in both the groups with no significant statistical difference. A consultant of anesthesia and gynecology were always present during the performance of these studies so as to confer uniformity to the study design as well to shorten the time of procedure which is quite similar to the profile of other researches. [12],[25] The consumption of rescue antiemetics in our study was significantly higher in the ondansetron group particularly in the first 24 hours which can be due to the weaning of antiemetic effect of IV ondansetron as the effect lasts for 4-5 hour.
The prophylaxis for PONV is always on the mind whenever patients are selected for the surgery on day care basis. The purpose of day care surgery itself gets defeated if any such discomfort is faced by the patient after discharge from the hospital. The premenstrual phases in younger females who undergo laparoscopic surgery under general anesthesia for ambulatory gynecological surgery are very important risk factors for PONV. [12],[24] But recently the premenstrual phase as a risk factor for PONV has been disapproved by many studies. [29]
As total IV anesthesia reduces the risk of PONV to quite an extent, we attempted to minimize the possible incidence of emetic episodes by using a propofol-based IV anesthesia and IV hydration as well as avoiding nitrous oxide. [30]
The overall incidence of nausea and vomiting was significantly higher in the ondansetron group as 20% and 13.33% of the patients experienced the nausea and vomiting episodes as compared to 6.67% and 3.33% in the palonosetron group, respectively. There were some patients who had multiple episodes of nausea and vomiting especially in the first 24 hours in both the groups but for comparison sake we included only the number of patients and not the number of episodes. The values were significant in comparison during the 6-12-hour period which again goes in accordance with the shorter duration of action of ondansetron. Rescue antiemetics were used by these patients during every episode of nausea or vomiting. Our results in the first 24-hour period with palonosetron are quite comparable with many other studies but the comparative efficacy against ondansetron has not been demonstrated by any literary evidence and only placebo has been used for comparison in various clinical trials. [23],[31],[32],[33],[34]
On statistical analysis, the observed power of the study was estimated at 0.584. These results have proved the better effectiveness of long acting palonosetron in the control of PONV as compared to ondansetron, thus providing the patients with a smooth and uneventful postoperative convalescent period and a lesser need for rescue antiemetics. The 5-HT3 antagonists exerts their antiemetic action by blocking the binding of serotonin to 5-HT3 receptors in the gut and the CTZ of area postrema which has got projections to the vomiting centre of lateral reticular formation of medulla oblongata. [35],[36] The side-effect profile of palonosetron seems to be more favorable as only 6.67% of patients experienced post-op headache in our study as compared 20% of such incidence in ondansetron group. The established incidence of headache with palonosetron has been cited at approximately 9-12% in the literature. [34] The other side effects like dizziness, anxiety, constipation and myalgia have presented a nonsignificant picture and have shown a slightly higher incidence of these side effects in ondansetron group which is statistically insignificant. Ondansetron was the first member of this group to be marketed, [37] and the recommended IV dose (6-8 mg) is most effective when administered just after the completion of surgery because of its short duration of effect. Its antiemetic effect is stronger than its antinausea effect. [38] Both ondansetron and palonosetron have similar antiemetic efficacy but dose of palonosetron is much less than ondansetron. Intravenous dose of 0.075 mg of palonosetron is equivalent to 6-8 mg of IV ondansetron. [39] Moreover ondansetron has a shorter half-life of 3-5 hours, whereas palonosetron has a half-life of approximately 40 hours, which makes it more effective in preventing nausea and vomiting for day care surgery. [40] Majority of our results particularly the ones related to the incidence of nausea and vomiting may have been due to the difference in the duration of these two drugs. How the efficacy of different 5-HT3 receptor antagonists vary is still unclear but most probably these differences may involve multiple factors such as intrinsic differences in 5-HT3 receptor blocking activity, 5- HT3 receptor affinity and binding stability, and differences in autocrine activity of serotonin released from enterochromaffin cells to act on 5-HT3 or 5-HT4 receptors on EC cells. [41]
In conclusion, the results of the present study clearly conveys the facts that palonosetron has got a prolonged duration of antiemetic effect, a lesser need for rescue antiemetic postoperatively and a favorable side-effects profile as compared to ondansetron, thus providing the patients with smooth convalescent period with lesser nausea and emetic episodes who undergo laparoscopic gynecological surgery under general anesthesia.
1 Philip BK. Patients' assessment of ambulatory anaesthesia and surgery. J Clin Anesth 1992;4:355-62.
2 Warner MA, Shields SE, Chute CG. Major morbidity and mortality within 1 month of ambulatory surgery and anesthesia. JAMA 1993;270:1437-41.
3 Macaroon A, Weiner M, Carney S, Kim A. Which clinical anaesthesia outcomes are important to avoid? The perspective of patients. Anesth Analg 1999;89:652-8.
4 Kapur PA. The big "little problem". Anesth Analg 1991;73:243-5.
5 Sniadach MS, Alberts MS. A comparison of the prophylactic antiemetic effect of ondansetron and droperidol on patients undergoing gynaecologic laparoscopy. Anesth Analg 1997;85:797-800.
6 Apfel CC, Laara E, Koivuranta M, Greim CA, Roewer N. A simplified risk scores for predicting postoperative nausea and vomiting: conclusions from cross-validations between two centres. Anesthesiology 1999;91:693-700.
7 Rowbotham DJ. Current management of postoperative nausea and vomiting. Br J Anaesth 1992;69:46-59.
8 Polati E, Verlato G, Finco G, Mosaner W, Grosso S, Gottin L, et al. Dose response of opioids and PONV. Anesth Analg 1997;85:395-9.
9 Roberts GW, Bekker TB, Carlsen HH, Moffatt CH, Slattery PJ, McClure AF. Postoperative nausea and vomiting are strongly influenced by postoperative opioid use in a dose-related manner. Anesth Analg 2005;101:1343-8.
10 Woodhouse A, Mather L. The effect of duration of dose delivery with patient controlled analgesia on the incidence of nausea and vomiting after hysterectomy. Br J Clin Pharmacol 1998;45:57-62.
11 Lerman J. Surgical and patient factors involved in postoperative nausea and vomiting. Br J Anaesth 1992;69:24-32.
12 Sinclair DR, Chung F, Mezei G. Can postoperative nausea and vomiting be predicted? Anesthesiology 1999;91:109-18.
13 Palazzo M, Evans R. Logistic regression analysis of fixed patient factors for postoperative sickness: a model for risk assessment. Br J Anaesth 1993;70:135-40.
14 Van den Bosch JE, Moons KG, Bonsel GJ, Kalkman CJ. Does measurement of preoperative anxiety have added value for predicting postoperative nausea and vomiting? Anesth Analg 2005;100:1525-32.
15 Lee A, Gin T, Lau AS, Ng FF. A comparison of patients' and health care professionals' preferences for symptoms during immediate postoperative recovery and the management of postoperative nausea and vomiting. Anesth Analg 2005;100:87-93.
16 van den Bosch JE, Bonsel GJ, Moons KG, Kalkman CJ. Effect of postoperative experiences on willingness to pay to avoid postoperative pain, nausea, and vomiting. Anesthesiology 2006;104:1033-9.
17 White PF, Issioui T, Hu J, Jones SB, Coleman JE, Waddle JP, et al. Comparative efficacy of acustimulation (Relief Band) versus ondansetron (Zofran) in combination with droperidol for preventing nausea and vomiting. Anesthesiology 2002;97:1075-81.
18 Rowbotham DJ. Recent advances in the non-pharmacological management of postoperative nausea and vomiting. Br J Anaesth 2005;95:77-81.
19 Paxton DL, Mckay CA, Mirakin KR. Prevention of nausea and vomiting after day case gynaecological laparoscopy. A comparison of ondansetron, droperidol, metoclopramide and placebo. Anaesthesia 1995;50:403-6.
20 Loewen PS, Marra CA, Zed PJ. 5-HT3 receptor antagonists vs. traditional agents for the prophylaxis of postoperative nausea and vomiting. Can J Anaesth 2000;47:1008-18.
21 Wong EH, Clark R, Leung E, Loury D, Bonhaus DW, Jakeman L, et al. In vitro the interaction of RS 25259-197, a potent and selective antagonist, with 5-HT3 receptors. Br J Pharmacol 1995;114:851-9.
22 White PF, Scuderi PE. Prevention of postoperative nausea and vomiting (PONV): A dose-ranging study involving palonosetron, a potent 5-HT3 receptor antagonist. Anesthesiology 2005;103:703.
23 Candiotti KA, Kovac AL, Melson TI, Clerici G, Joo Gan T. A randomized, double-blind study to evaluate the efficacy and safety of three different doses of palonosetron versus placebo for preventing postoperative nausea and vomiting. Anesth Analg 2008;107:445-51.
24 Gan TJ. Risk factors for postoperative nausea and vomiting. Anesth Analg 2006;102:1884-98.
25 Stadler M, Bardiau F, Seidel L, Albert A, Boogaerts JG. Difference in risk factors for postoperative nausea and vomiting. Anesthesiology 2003;98:46-52.
26 Boothe P, Finegan BA. Changing the admission process for elective surgery: an economic analysis. Can J Anaesth 1998;42:391-4.
27 Myles PS, Williams DL, Hendrata M, Anderson H, Weeks AM. Patient satisfaction after anaesthesia and surgery: results of a prospective survey of 10,811 patients. Br J Anaesth 2000;84:6-10.
28 Apfel CC, Kranke P, Eberhart LH, Roos A, Roewer N. Comparison of predictive models for postoperative nausea and vomiting. Br J Anaesth 2000;88:234-40.
29 Kranke P, Apefel CC, Papenfuss T, Rauch S, Löbmann U, Rübsam B, et al. An increased body mass index is no risk factor for postoperative nausea and vomiting. A systematic review and results of original data. Acta Anaesthesiol Scand 2001;45:160-6.
30 Apfel CC, Korttila K, Abdalla M, Kerger H, Turan A, Vedder I, et al. A factorial trial of six interventions for the prevention of postoperative nausea and vomiting. N Engl J Med 2004;350:2441-51.
31 White PF, O'Hara JF, Roberson CR, Wender RH, Candiotti KA. The impact of current antiemetic practises on patient outcomes: a prospective study on high-risk patients. Anesth Analg 2008;107:452-8.
32 Kranke P, Schuster F, Eberhart LH. Recent advances, trends and economic considerations in the risk assessment, prevention and treatment of postoperative nausea and vomiting. Expert Opin Pharmacother 2007;8:3217-35.
33 Eisenberg P, Figueroa-Vadillo J, Zamora R, Charu V, Hajdenberg J, Cartmell A, et al. Improved prevention of moderately emetogenic chemotherapy-induced nausea and vomiting with palonosetron, a pharmacologically novel 5-HT3 receptor antagonist. Results of a phase III, single-dose trial versus dolasetron. Cancer 2003;98:2473-82.
34 Kovac AL, Eberhart L, Kotarski J, Clerici G, Apfel C. A randomized, double-blind study to evaluate the efficacy and safety of three different doses of palonosetron versus placebo in preventing postoperative nausea and vomiting over a 72-hour period. Anesth Analg 2008;107:439-44.
35 Gan TJ. Selective serotonin 5-HT3 receptor antagonists for postoperative nausea and vomiting: are they all the same? CNS Drugs 2005;19:225-38.
36 Ho KY, Gan TJ. Pharmacology, pharmacogenetics, and clinical efficacy of 5-hydroxytryptamine type 3 receptor antagonists for postoperative nausea and vomiting. Curr Opin Anaesthesiol 2006;19:606-11.
37 Habib AS, Gan TJ. Evidence-based management of postoperative nausea and vomiting: a review. Can J Anaesth 2004;51:326-41.
38 Tramér MR, Reynolds DJ, Moore RA. Efficacy, dose-response, and safety of ondansetron in prevention of postoperative nausea and vomiting: a quantitative systematic review of randomized placebo-controlled trials. Anesthesiology 1997;87:1277-89.
39 Eisenberg P, MacKintosh FR, Ritch P, Cornett PA, Macciocchi A. Efficacy, safety and pharmacokinetics of palonosetron in patients receiving highly emetogenic cisplatin-based chemotherapy: a dose-ranging clinical study. Ann Oncol 2004;15:330-7.
40 Stoltz R, Cyong JC, Shah A, Parisi S. Pharmacokinetic and safety evaluation of palonosetron, a 5-hydroxytryptamine-3 receptor antagonist, in US and Japanese healthy subjects. J Clin Pharmacol 2004;44:520-31.
41 Kovac AL. Prophylaxis of postoperative nausea and vomiting: controversies in the use of serotonin 5-hydroxytryptamine subtype 3 receptor antagonists. J Clin Anesth 2006;18:304-18.


You can't just sit about and do absolutely nothing when your mother and father are seeking a new location to live right here in Salt Lake City, UT. Purchasing a new house is a tedious procedure; and your mothers and fathers require all the assistance they can get. You can help your parents by persuading them that hearth protection is essential. Speak to them about the hearth drill you experienced at school–and why your mothers and fathers should bear in mind that when searching for a brand name-new home.
Finally, the village has the buying power to save taxpayers cash. Contracting for refuse assortment, for instance, at considerable savings over person contracts, would, for those who 'opt in,' this would make residing here much more inexpensive. Any and all affordable suggestions ought to be regarded as.
That may appear self-serving on this site, but the reality of the matter is that your gun assortment will keep increasing. When you purchase gun safes – whether a biometric gun secure or gun cupboards – you'll wind up utilizing it for a great deal more than your guns. That is, unless of course you want to buy other wall safes and this kind of, but most in the gun secure market tend to use the large gun cabinet for much more than firearms. You'll want to be sure that whatever kind of secure you buy, you don't maintain back again on the features, this kind of as Dumu aizkari, biometric locking system, and the like.
Lovejoy ought to have predicted these concerns and supplied explanations in her textual content accompanying the spreadsheet. But she didn't. Instead she took a inexpensive potshot at the Trustees.
Semi-rigid metal vent – Adaptable to each installation for duct will expand to a distance of 8 feet. It includes specifically crimped finishes to adapt to each four" dryer outlet and wall outlet. Consists of two metal clamps. Duct can be trimmed with ordinary kitchen area shears for a custom fit. Enhances drying times and minimizes overheating of dryer.
Cost financial savings are price savings. Spending much more than two times what you have to for a service is silly. We need to get intelligent about this problem, as soon as and for all. Consider the emotion out of this debate and appear at the cost savings!
There are numerous products available on the market that can help with fireproofing and provide hearth protection. From Xmas tree fire prevention goods to material remedies that make textiles hearth resistive, these products, with each other with good home hearth security methods, can conserve life and home.


text:
Q: VB manipulate lots of labels inside panel So i have like 100 labels inside a panel and i need to to change their texts.I Tried an for and i tried Tab Index like an array without success, any ideas how I can select and change properties of these labels?
Sub setCartela(ByVal numeros As Integer)
    For cont As Integer = 0 To numeros Step 1
//change labels text inside panel
    Next
End Sub

A: Try like this ...
Dim i as Integer = 1
For Each ctrl As Control In Panel1.Controls
        If ctrl.GetType.ToString = "System.Windows.Forms.Label" Then
            ctrl.Text = "Text" & format(i)
        End If
        i += 1
Next

A: try this code :
dim _countLbl as integer = 1
For each Lbl as Label in Panel1.Controls.Oftype(Of Label)()

Lbl.text="Label" & _countLbl
_countLbl += 1

Next