Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * See the COPYRIGHT.txt file distributed with this work for information
   * regarding copyright ownership.  Some portions may be licensed
   * to Red Hat, Inc. under one or more contributor license agreements.
   *
   * This library is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  * 02110-1301 USA.
  */
 package org.teiid.olingo.service;
 
 import java.net.URI;
 import java.sql.Blob;
 import java.sql.Clob;
 import java.util.List;
 
 
 public class TeiidServiceHandler implements ServiceHandler {
     private static final String PREFERENCE_APPLIED = "Preference-Applied";
     private static final String ODATA_MAXPAGESIZE = "odata.maxpagesize";
     private boolean prepared = true;
     private OData odata;
     private ServiceMetadata serviceMetadata;
    private String schemaName;
    
    private static ThreadLocal<ClientCLIENT = new ThreadLocal<Client>() {
        @Override
        protected Client initialValue() {
            return null;
        }
    };
    public static Client getClient() {
        return .get();
    }
    public static void setClient(Client client) {
        .set(client);
    }    
    
    public TeiidServiceHandler(String schemaName) {
        this. = schemaName;
    }
    
    @Override
    public void init(OData odataServiceMetadata serviceMetadata) {
        this. = odata;
        this. = serviceMetadata;
    }
    
    public void setPrepared(boolean flag) {
        this. = flag;
    }
    @Override
    public void readMetadata(MetadataRequest requestMetadataResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        response.writeMetadata();
    }
    @Override
    public void readServiceDocument(ServiceDocumentRequest request,
            ServiceDocumentResponse responsethrows ODataTranslatedException,
            ODataApplicationException {
        response.writeServiceDocument(request.getODataRequest().getRawBaseUri());
    }
    class UniqueNameGenerator {
        private final AtomicInteger groupCount = new AtomicInteger(0);
        public String getNextGroup() {
            String aliasGroup = "g"+this..getAndIncrement(); //$NON-NLS-1$
            return aliasGroup;
        }
    }    
    
    @Override
    public <T extends ServiceResponsevoid read(final DataRequest request, T response)
            throws ODataTranslatedExceptionODataApplicationException {
        
        final ODataSQLBuilder visitor = new ODataSQLBuilder(
                getClient().getMetadataStore(), this.true
                request.getODataRequest().getRawBaseUri(), this.this.);
        visitor.visit(request.getUriInfo());
        
        final BaseResponse queryResponse;
        try {
            Query query = visitor.selectQuery();
            if (request.isCountRequest()) {
                queryResponse = getClient().executeCount(queryvisitor.getParameters());
            }
            else {
                String pageSize = request.getPreference();
                if (pageSize == null) {
                    if (getClient().getProperty(.) == null) {
                        pageSize = String.valueOf(.);
                    }
                    else {
                        pageSize = getClient().getProperty(.);
                    }
                }
                EntityList result = new EntityList(getClient().getProperty(.),
                        visitor.getContext());
                getClient().executeSQL(queryvisitor.getParameters(),
                        visitor.includeTotalSize(), visitor.getSkip(),
                        visitor.getTop(), visitor.getNextToken(), Integer.parseInt(pageSize), result);
                
                queryResponse = result;
            }
        } catch (Exception e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        } 
        response.accepts(new ServiceResponseVisior() {
            public void visit(CountResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                org.teiid.olingo.api.CountResponse cr = (org.teiid.olingo.api.CountResponsequeryResponse;
                response.writeCount(cr.getCount());
            }
            public void visit(PrimitiveValueResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                EntityCollection entitySet = (EntityCollection)queryResponse;
                Entity entity = entitySet.getEntities().get(0);
                
                EdmProperty edmProperty = request.getUriResourceProperty().getProperty();
                Property property = entity.getProperty(edmProperty.getName());
                if (property == null) {
                    response.writeNotFound(true);
                }
                else if (property.getValue() == null) {
                    response.writeNoContent(true);
                }
                response.write(property.getValue());            
            }
            public void visit(PropertyResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                EntityCollection entitySet = (EntityCollection)queryResponse;
                if (!entitySet.getEntities().isEmpty()) {
                    Entity entity = entitySet.getEntities().get(0);
                    
                    EdmProperty edmProperty = request.getUriResourceProperty().getProperty();
                    Property property = entity.getProperty(edmProperty.getName());
                    response.writeProperty(edmProperty.getType(), property);
                }
                else {
                    response.writeNotFound(true);
                }
            }
            public void visit(StreamResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                EntityCollection entitySet = (EntityCollection)queryResponse;
                Entity entity = entitySet.getEntities().get(0);
                
                EdmProperty edmProperty = request.getUriResourceProperty().getProperty();
                Property property = entity.getProperty(edmProperty.getName());
                Object value = property.getValue();
                if (value == null) {
                    response.writeNoContent(true);
                }
                else {
                    try {
                        handleLobResult(getClient().getProperty(.), valueresponse);
                    } catch (SQLException e) {
                        LogManager.logDetail(.e);
                        response.writeServerError(true);
                    }
                }
            }
            public void visit(EntityResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                EntityCollection entitySet = (EntityCollection)queryResponse;
                if (entitySet.getEntities().isEmpty()) {
                    response.writeNoContent(true);
                } else {
                    response.writeReadEntity(visitor.getContext().getEdmEntityType(), 
                        entitySet.getEntities().get(0));
                }
            }
            
            public void visit(EntitySetResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                if (request.getPreference() != null) {
                    response.writeHeader(,
                            +"="request.getPreference()); //$NON-NLS-1$
                }
                EntityList result = (EntityList)queryResponse;
                if (result.getNextToken() != null) {
                    try {
                        result.setNext(new URI(request.getODataRequest().getRawRequestUri()
                                + (request.getODataRequest().getRawQueryPath() == null ?"?$skiptoken=":"&$skiptoken=")
                                + result.getNextToken()));
                    } catch (URISyntaxException e) {
                        throw new ODataApplicationException(e.getMessage(), 500, Locale.getDefault(), e);
                    }
                }
                response.writeReadEntitySet(visitor.getContext().getEdmEntityType(), result);
            }        
        });
    }
    private void checkExpand(UriInfoResource queryInfo) {
        if (queryInfo.getExpandOption() != null && !queryInfo.getExpandOption().getExpandItems().isEmpty()) {
            throw new UnsupportedOperationException("Expand is not supported"); //$NON-NLS-1$
        }
    }
    
    @Override
    public void createEntity(DataRequest requestEntity entity,
            EntityResponse responsethrows ODataTranslatedException,
            ODataApplicationException {
        
        ODataSQLBuilder visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                request.getODataRequest().getRawBaseUri(), this.this.);
        visitor.visit(request.getUriInfo());
        
        EdmEntityType entityType = request.getEntitySet().getEntityType();
        Insert command = visitor.insert(entityTypeentitythis.);
        try {
            UpdateResponse updateResponse = getClient().executeUpdate(commandvisitor.getParameters());
            if (updateResponse.getUpdateCount()  == 1) {
                visitor = new ODataSQLBuilder(getClient().getMetadataStore(), truefalse
                        request.getODataRequest().getRawBaseUri(), this.this.);
                Query query = visitor.selectWithEntityKey(entityType,
                                entityupdateResponse.getGeneratedKeys());
                LogManager.logDetail(.null"created entity = "entityType.getName(), " with key="query.getCriteria().toString()); //$NON-NLS-1$ //$NON-NLS-2$
                
                EntityList result = new EntityList(getClient().getProperty(
                        .),
                        visitor.getContext());
                getClient().executeSQL(queryvisitor.getParameters(), falsenullnullnull, 1, result);
                
                if (!result.getEntities().isEmpty()) {
                    entity = result.getEntities().get(0);
                    String location = EntityResponse.buildLocation(request.getODataRequest().getRawBaseUri(),
                            entity
                            request.getEntitySet().getName(), 
                            entityType);
                    entity.setId(new URI(location));
                }
                response.writeCreatedEntity(request.getEntitySet(), entity);
            }
            else {
                response.writeNotModified();
            }
        } catch (SQLException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        } catch (URISyntaxException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        }
    }
    @Override
    public void updateEntity(DataRequest requestEntity entityboolean merge,
            String entityETagEntityResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        // TODO: need to match entityETag.
        checkETag(entityETag);
        
        UpdateResponse updateResponse = null;
        if (merge) {
            try {
                ODataSQLBuilder visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                        request.getODataRequest().getRawBaseUri(), this.this.);
                visitor.visit(request.getUriInfo());
                EdmEntityType entityType = request.getEntitySet().getEntityType();
                Update update = visitor.update(entityTypeentitythis.);
                updateResponse = getClient().executeUpdate(updatevisitor.getParameters());
            } catch (SQLException e) {
                throw new ODataApplicationException(e.getMessage(),
                        ..getStatusCode(),
                        Locale.getDefault(), e);
            }
        }
        else {
            // delete, then insert
            String txn = startTransaction();
            try {
                ODataSQLBuilder visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                        request.getODataRequest().getRawBaseUri(), this.this.);
                visitor.visit(request.getUriInfo());
                Delete delete = visitor.delete();
                updateResponse = getClient().executeUpdate(deletevisitor.getParameters());
                
                // insert
                ODataJsonDeserializer deserializer = new ODataJsonDeserializer();
                             
                visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                        request.getODataRequest().getRawBaseUri(), this.this.);
                visitor.visit(request.getUriInfo());
                
                EdmEntityType entityType = request.getEntitySet().getEntityType();
                List<UriParameterkeys = request.getKeyPredicates();
                for (UriParameter key : keys) {
                    EdmProperty edmProperty = (EdmProperty)entityType.getProperty(key.getName());
                    Property property = deserializer.property(
                            new ByteArrayInputStream(key.getText().getBytes()),
                            edmProperty).getProperty();
                    entity.addProperty(property);
                }
                Insert command = visitor.insert(entityTypeentitythis.);
                updateResponse = getClient().executeUpdate(commandvisitor.getParameters());
                commit(txn);
            } catch (SQLException e) {
                rollback(txn);
                throw new ODataApplicationException(e.getMessage(),
                        ..getStatusCode(),
                        Locale.getDefault(), e);                
            }
        }
        
        if (updateResponse!= null && updateResponse.getUpdateCount()  > 0) {
            response.writeUpdatedEntity();
        }
        else {
            response.writeNotModified();
        }        
    }
    private void checkETag(String entityETagthrows ODataApplicationException{
        if (entityETag != null && !entityETag.equals("*")) {
            throw new ODataApplicationException(
                    ..gs(..),
                    ..getStatusCode(),
                    Locale.getDefault());
        }
    }
    @Override
    public void deleteEntity(DataRequest requestString entityETag,
            EntityResponse responsethrows ODataTranslatedExceptionODataApplicationException {
        
        // TODO: need to match entityETag.
        checkETag(entityETag);
        
        UpdateResponse updateResponse = null;
        try {
            ODataSQLBuilder visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                    request.getODataRequest().getRawBaseUri(), this.this.);
            visitor.visit(request.getUriInfo());
            Delete delete = visitor.delete();
            updateResponse = getClient().executeUpdate(deletevisitor.getParameters());
        } catch (SQLException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        }
        
        if (updateResponse != null && updateResponse.getUpdateCount()  > 0) {
            response.writeDeletedEntityOrReference();
        }
        else {
            response.writeNotModified();
        }
    }

    
since Teiid only deals with primitive types, merge does not apply
    @Override
    public void updateProperty(DataRequest requestProperty property,
            boolean mergeString entityETagPropertyResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        // TODO: need to match entityETag.
        checkETag(entityETag);
        
        UpdateResponse updateResponse = null;
        EdmProperty edmProperty = request.getUriResourceProperty().getProperty();
        try {
            ODataSQLBuilder visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                    request.getODataRequest().getRawBaseUri(),this.this.);
            visitor.visit(request.getUriInfo());
            Update update = visitor.updateProperty(edmPropertypropertythis.);
            updateResponse = getClient().executeUpdate(updatevisitor.getParameters());
        } catch (SQLException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        }
        
        if (updateResponse != null && updateResponse.getUpdateCount() > 0) {
            response.writePropertyUpdated();
        } else {
            response.writeNotModified();
        }
    }
    @Override
    public void upsertStreamProperty(DataRequest requestString entityETag,
            InputStream streamContentNoContentResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        UpdateResponse updateResponse = null;
        EdmProperty edmProperty = request.getUriResourceProperty().getProperty();
        try {
            ODataSQLBuilder visitor = new ODataSQLBuilder(getClient().getMetadataStore(), this.false,
                    request.getODataRequest().getRawBaseUri(),this.this.);
            visitor.visit(request.getUriInfo());
            Update update = visitor.updateStreamProperty(edmPropertystreamContent);
            updateResponse = getClient().executeUpdate(updatevisitor.getParameters());
        } catch (SQLException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        }
        if (updateResponse != null && updateResponse.getUpdateCount() > 0) {
            response.writeNoContent();
        } else {
            response.writeNotModified();
        }        
    }
    @Override
    public <T extends ServiceResponsevoid invoke(final FunctionRequest request,
            HttpMethod method, T responsethrows ODataTranslatedException,
            ODataApplicationException {
        invokeOperation(requestresponse);
    }
    
    @Override
    public <T extends ServiceResponsevoid invoke(final ActionRequest request,
            String eTag, T responsethrows ODataTranslatedExceptionODataApplicationException {
        checkETag(eTag);        
        invokeOperation(requestresponse);
    }    
        
    private <T extends ServiceResponsevoid invokeOperation(final OperationRequest request,
            T responsethrows ODataApplicationExceptionODataTranslatedException {
        
        checkExpand(request.getUriInfo().asUriInfoResource());
        
        OperationResponseImpl result = null;
        try {
            MetadataStore store = getClient().getMetadataStore();
            ProcedureSQLBuilder builder = new ProcedureSQLBuilder(store.getSchema(), request);
            ProcedureReturn procedureReturn = builder.getReturn();
            result = new OperationResponseImpl(
                    getClient().getProperty(.), 
                    procedureReturn.getReturnType());
            
            getClient().executeCall(builder.buildProcedureSQL(), builder.getSqlParameters(), procedureReturnresult);
        } catch (SQLException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        } catch (TeiidException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        } 
        
        final OperationResponseImpl operationResult = result;
        response.accepts(new ServiceResponseVisior() {
            @Override
            public void visit(PropertyResponse response)
                    throws ODataTranslatedExceptionODataApplicationException {
                Property property = (Property)operationResult.getResult();
                Object value = property.getValue();                
                if (value instanceof SQLXML || value instanceof Blob || value instanceof Clob) {
                    try {
                        handleLobResult(getClient().getProperty(.), valueresponse);
                    } catch (SQLException e) {
                        LogManager.logDetail(.e);
                        response.writeServerError(true);
                    }
                }
                else {                    
                    response.writeProperty(request.getReturnType().getType(), property);
                }
            }
        });
    }
    @Override
    public void readMediaStream(MediaRequest requestStreamResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        response.writeServerError(true);
    }
    @Override
    public void upsertMediaStream(MediaRequest requestString entityETag,
            InputStream mediaContentNoContentResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        response.writeServerError(true);
    }
    @Override
    public void anyUnsupported(ODataRequest requestODataResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        response.setStatusCode(500);
    }
    @Override
    public void addReference(DataRequest requestString entityETag,
            URI referenceIdNoContentResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        manageReference(requestreferenceIdresponsefalse);
    }
    @Override
    public void updateReference(DataRequest requestString entityETag,
            URI referenceIdNoContentResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        manageReference(requestreferenceIdresponsefalse);
    }
    private void manageReference(DataRequest requestURI referenceId,
            NoContentResponse responseboolean deletethrows ODataApplicationException {
        UpdateResponse updateResponse = null;
        try {
            ReferenceUpdateSQLBuilder visitor = new ReferenceUpdateSQLBuilder(getClient().getMetadataStore(), 
                    request.getODataRequest().getRawBaseUri(), this.);
            visitor.visit(request.getUriInfo());
            Update update = visitor.updateReference(referenceIdthis.delete);
            updateResponse = getClient().executeUpdate(updatevisitor.getParameters());
        } catch (SQLException e) {
            throw new ODataApplicationException(e.getMessage(),
                    ..getStatusCode(),
                    Locale.getDefault(), e);
        }
        
        if (updateResponse != null && updateResponse.getUpdateCount() > 0) {
            response.writeNoContent();
        }
        else {
            response.writeNotModified();
        }
    }
    @Override
    public void deleteReference(DataRequest requestURI deleteId,
            String entityETagNoContentResponse response)
            throws ODataTranslatedExceptionODataApplicationException {
        manageReference(requestdeleteIdresponsetrue);
    }
    @Override
        try {
            return getClient().startTransaction();
        } catch (SQLException e) {
            throw new ODataApplicationException(
                    ..gs(..),
                    ..getStatusCode(), Locale.getDefault());
        }
    }
    @Override
    public void commit(String txnIdthrows ODataTranslatedExceptionODataApplicationException {
        try {
            getClient().commit(txnId);
        } catch (SQLException e) {
            throw new ODataApplicationException(
                    ..gs(..),
                    ..getStatusCode(), Locale.getDefault());
        }
    }
    @Override
    public void rollback(String txnIdthrows ODataTranslatedExceptionODataApplicationException {
        try {
            getClient().rollback(txnId);
        } catch (SQLException e) {
            throw new ODataApplicationException(
                    ..gs(..),
                    ..getStatusCode(), Locale.getDefault());
        }
    }
    @Override
    public void crossJoin(DataRequest requestList<StringentitySetNames,
            ODataResponse responsethrows ODataTranslatedException,
            ODataApplicationException {
        
        final ODataSQLBuilder visitor = new ODataSQLBuilder(
                getClient().getMetadataStore(), this.true
                request.getODataRequest().getRawBaseUri(), this.this.);
        visitor.visit(request.getUriInfo());
    }
    
    private void handleLobResult(String charSetObject resultServiceResponse responsethrows SQLException {
        if (result == null) {
            return//or should this be an empty result?
        }
        if (result instanceof SQLXML) {
            if (charSet != null) {
                XMLSerialize serialize = new XMLSerialize();
                serialize.setTypeString("blob"); //$NON-NLS-1$
                serialize.setDeclaration(true);
                serialize.setEncoding(charSet);
                serialize.setDocument(true);
                try {
                    InputStream content = ((BlobType)XMLSystemFunctions.serialize(serializenew XMLType((SQLXML)result))).getBinaryStream();
                    response.writeContent(content, 200, false);
                    response.writeOK(..toContentTypeString());
                } catch (TransformationException e) {
                    throw new SQLException(e);
                }
            }
            else {
                InputStream content = ((SQLXML)result).getBinaryStream();
                response.writeContent(content, 200, false);
                response.writeOK(..toContentTypeString());
            }
        }
        else if (result instanceof Blob) {
            InputStream content =  ((Blob)result).getBinaryStream();
            response.writeContent(content, 200, false);
            response.writeOK(..toContentTypeString());            
        }
        else if (result instanceof Clob) {
            InputStream content =  new ReaderInputStream(((Clob)result).getCharacterStream(), charSet==null?Charset.defaultCharset():Charset.forName(charSet));
            response.writeContent(content, 200, false);
            response.writeOK(..toContentTypeString());                        
        }
        else {
            InputStream content =  new ByteArrayInputStream(result.toString().getBytes(charSet==null?Charset.defaultCharset():Charset.forName(charSet)));
            response.writeContent(content, 200, false);
            response.writeOK(..toContentTypeString());                        
        }
    }
New to GrepCode? Check out our FAQ X