Search in sources :

Example 6 with TeiidException

use of org.teiid.core.TeiidException in project teiid by teiid.

the class TeiidServiceHandler method updateProperty.

/**
 * since Teiid only deals with primitive types, merge does not apply
 */
@Override
public void updateProperty(DataRequest request, Property property, boolean rawValue, boolean merge, String entityETag, PropertyResponse response) throws ODataLibraryException, ODataApplicationException {
    // TODO: need to match entityETag.
    checkETag(entityETag);
    UpdateResponse updateResponse = null;
    EdmProperty edmProperty = request.getUriResourceProperty().getProperty();
    try {
        ODataSQLBuilder visitor = new ODataSQLBuilder(this.odata, getClient().getMetadataStore(), this.prepared, false, request.getODataRequest().getRawBaseUri(), this.serviceMetadata);
        visitor.visit(request.getUriInfo());
        Update update = visitor.updateProperty(edmProperty, property, this.prepared, rawValue);
        updateResponse = getClient().executeUpdate(update, visitor.getParameters());
    } catch (SQLException e) {
        throw new ODataApplicationException(e.getMessage(), HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.getDefault(), e);
    } catch (TeiidException e) {
        throw new ODataApplicationException(e.getMessage(), HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.getDefault(), e);
    }
    if (updateResponse != null && updateResponse.getUpdateCount() > 0) {
        response.writePropertyUpdated();
    } else {
        response.writeNotModified();
    }
}
Also used : UpdateResponse(org.teiid.odata.api.UpdateResponse) SQLException(java.sql.SQLException) EdmProperty(org.apache.olingo.commons.api.edm.EdmProperty) Update(org.teiid.query.sql.lang.Update) ODataApplicationException(org.apache.olingo.server.api.ODataApplicationException) TeiidException(org.teiid.core.TeiidException)

Example 7 with TeiidException

use of org.teiid.core.TeiidException in project teiid by teiid.

the class ODataTypeManager method parseLiteral.

public static Object parseLiteral(String odataType, String value) throws TeiidException {
    EdmPrimitiveType primitiveType = EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.valueOf(odataType.substring(4)));
    int maxLength = DataTypeManager.MAX_STRING_LENGTH;
    if (primitiveType instanceof EdmBinary || primitiveType instanceof EdmStream) {
        maxLength = DataTypeManager.MAX_VARBINARY_BYTES;
    }
    int precision = 4;
    int scale = 3;
    if (primitiveType instanceof EdmDecimal) {
        precision = 38;
        scale = 9;
    }
    Class<?> expectedClass = primitiveType.getDefaultType();
    try {
        if (EdmString.getInstance().equals(primitiveType)) {
            value = EdmString.getInstance().fromUriLiteral(value);
        }
        Object converted = primitiveType.valueOfString(value, false, maxLength, precision, scale, true, expectedClass);
        if (primitiveType instanceof EdmTimeOfDay) {
            Calendar ts = (Calendar) converted;
            return new Time(ts.getTimeInMillis());
        } else if (primitiveType instanceof EdmDate) {
            Calendar ts = (Calendar) converted;
            return new Date(ts.getTimeInMillis());
        }
        return converted;
    } catch (EdmPrimitiveTypeException e) {
        throw new TeiidException(e);
    }
}
Also used : EdmPrimitiveType(org.apache.olingo.commons.api.edm.EdmPrimitiveType) EdmBinary(org.apache.olingo.commons.core.edm.primitivetype.EdmBinary) EdmStream(org.apache.olingo.commons.core.edm.primitivetype.EdmStream) Calendar(java.util.Calendar) Time(java.sql.Time) EdmPrimitiveTypeException(org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException) EdmDate(org.apache.olingo.commons.core.edm.primitivetype.EdmDate) EdmDate(org.apache.olingo.commons.core.edm.primitivetype.EdmDate) Date(java.sql.Date) EdmDecimal(org.apache.olingo.commons.core.edm.primitivetype.EdmDecimal) TeiidException(org.teiid.core.TeiidException) EdmTimeOfDay(org.apache.olingo.commons.core.edm.primitivetype.EdmTimeOfDay)

Example 8 with TeiidException

use of org.teiid.core.TeiidException in project teiid by teiid.

the class ODataTypeManager method convertToTeiidRuntimeType.

/**
 * @param type
 * @param value
 * @param odataType type hint if the value could be a string containing a literal value of another type
 * @return
 * @throws TeiidException
 */
public static Object convertToTeiidRuntimeType(Class<?> type, Object value, String odataType) throws TeiidException {
    if (value == null) {
        return null;
    }
    if (type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof UUID) {
        return value.toString();
    }
    if (type.isArray() && value instanceof List<?>) {
        List<?> list = (List<?>) value;
        Class<?> expectedArrayComponentType = type.getComponentType();
        Object array = Array.newInstance(type.getComponentType(), list.size());
        for (int i = 0; i < list.size(); i++) {
            Object arrayItem = convertToTeiidRuntimeType(expectedArrayComponentType, list.get(i), null);
            Array.set(array, i, arrayItem);
        }
        return array;
    }
    if (odataType != null && value instanceof String) {
        try {
            value = ODataTypeManager.parseLiteral(odataType, (String) value);
        } catch (TeiidException e) {
            throw new TranslatorException(e);
        }
    }
    if (value instanceof Geospatial && type == DataTypeManager.DefaultDataClasses.GEOMETRY) {
        final Geospatial val = (Geospatial) value;
        // if (val.getDimension() == Dimension.GEOMETRY) {
        return new GeometryInputSource() {

            @Override
            public Reader getGml() throws Exception {
                AtomGeoValueSerializer serializer = new AtomGeoValueSerializer();
                XMLOutputFactory factory = XMLOutputFactory.newInstance();
                StringWriter sw = new StringWriter();
                final XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
                serializer.serialize(writer, val);
                writer.close();
                return new StringReader(sw.toString());
            }

            @Override
            public Integer getSrid() {
                String srid = val.getSrid().toString();
                try {
                    return Integer.parseInt(srid);
                } catch (NumberFormatException e) {
                    return null;
                }
            }
        };
    // }
    }
    if (value instanceof Calendar) {
        Calendar calender = (Calendar) value;
        if (type.isAssignableFrom(java.sql.Time.class)) {
            calender.set(Calendar.YEAR, 1970);
            calender.set(Calendar.MONTH, Calendar.JANUARY);
            calender.set(Calendar.DAY_OF_MONTH, 1);
            calender.set(Calendar.MILLISECOND, 0);
            return new Time(calender.getTimeInMillis());
        } else if (type.isAssignableFrom(java.sql.Date.class)) {
            calender.set(Calendar.HOUR_OF_DAY, 0);
            calender.set(Calendar.MINUTE, 0);
            calender.set(Calendar.SECOND, 0);
            calender.set(Calendar.MILLISECOND, 0);
            return new java.sql.Date(calender.getTimeInMillis());
        } else if (type.isAssignableFrom(java.sql.Timestamp.class)) {
            return new Timestamp(calender.getTimeInMillis());
        }
    }
    Transform transform = DataTypeManager.getTransform(value.getClass(), type);
    if (transform != null) {
        try {
            value = transform.transform(value, type);
        } catch (TransformationException e) {
            throw new TeiidException(e);
        }
    }
    return value;
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) GeometryInputSource(org.teiid.GeometryInputSource) Time(java.sql.Time) EdmString(org.apache.olingo.commons.core.edm.primitivetype.EdmString) Timestamp(java.sql.Timestamp) StringWriter(java.io.StringWriter) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) StringReader(java.io.StringReader) List(java.util.List) UUID(java.util.UUID) Calendar(java.util.Calendar) Geospatial(org.apache.olingo.commons.api.edm.geo.Geospatial) EdmDate(org.apache.olingo.commons.core.edm.primitivetype.EdmDate) Date(java.sql.Date) TeiidException(org.teiid.core.TeiidException) Date(java.sql.Date) TranslatorException(org.teiid.translator.TranslatorException)

Example 9 with TeiidException

use of org.teiid.core.TeiidException in project teiid by teiid.

the class TestPreparedStatement method testBatchedUpdateExecution.

/**
 * Verify that the <code>executeBatch()</code> method of <code>
 * MMPreparedStatement</code> is resulting in the correct command,
 * parameter values for each command of the batch, and the request type
 * are being set in the request message that would normally be sent to the
 * server.
 *
 * @throws Exception
 */
@Test
public void testBatchedUpdateExecution() throws Exception {
    // Build up a fake connection instance for use with the prepared statement
    ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
    Mockito.stub(conn.getConnectionProps()).toReturn(new Properties());
    DQP dqp = Mockito.mock(DQP.class);
    ServerConnection serverConn = Mockito.mock(ServerConnection.class);
    LogonResult logonResult = Mockito.mock(LogonResult.class);
    // stub methods
    Mockito.stub(conn.getServerConnection()).toReturn(serverConn);
    Mockito.stub(serverConn.getLogonResult()).toReturn(logonResult);
    Mockito.stub(logonResult.getTimeZone()).toReturn(TimeZone.getDefault());
    // a dummy result message that is specific to this test case
    final ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>();
    final int[] count = new int[1];
    final ResultsMessage rm = new ResultsMessage();
    Mockito.stub(dqp.executeRequest(Matchers.anyLong(), (RequestMessage) Matchers.anyObject())).toAnswer(new Answer<ResultsFuture<ResultsMessage>>() {

        @Override
        public ResultsFuture<ResultsMessage> answer(InvocationOnMock invocation) throws Throwable {
            RequestMessage requestMessage = (RequestMessage) invocation.getArguments()[1];
            count[0] += requestMessage.getParameterValues().size();
            if (count[0] == 100000) {
                rm.setException(new TeiidException());
                rm.setResults(new List<?>[] { Arrays.asList(Statement.EXECUTE_FAILED) });
            } else {
                List<?>[] vals = new List<?>[requestMessage.getParameterValues().size()];
                Arrays.fill(vals, Arrays.asList(0));
                rm.setResults(Arrays.asList(vals));
            }
            return results;
        }
    });
    rm.setUpdateResult(true);
    results.getResultsReceiver().receiveResults(rm);
    Mockito.stub(conn.getDQP()).toReturn(dqp);
    // some update SQL
    // $NON-NLS-1$
    String sqlCommand = "delete from table where col=?";
    TestableMMPreparedStatement statement = (TestableMMPreparedStatement) getMMPreparedStatement(conn, sqlCommand);
    ArrayList<ArrayList<Object>> expectedParameterValues = new ArrayList<ArrayList<Object>>(3);
    // Add some batches and their parameter values
    expectedParameterValues.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(1) })));
    statement.setInt(1, new Integer(1));
    statement.addBatch();
    expectedParameterValues.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(2) })));
    statement.setInt(1, new Integer(2));
    statement.addBatch();
    expectedParameterValues.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(3) })));
    statement.setInt(1, new Integer(3));
    statement.addBatch();
    // execute the batch and verify that it matches our dummy results
    // message set earlier
    assertTrue(Arrays.equals(new int[] { 0, 0, 0 }, statement.executeBatch()));
    // Now verify the statement's RequestMessage is what we expect
    // $NON-NLS-1$
    assertEquals("Command does not match", sqlCommand, statement.requestMessage.getCommandString());
    // $NON-NLS-1$
    assertEquals("Parameter values do not match", expectedParameterValues, statement.requestMessage.getParameterValues());
    // $NON-NLS-1$
    assertTrue("RequestMessage.isBatchedUpdate should be true", statement.requestMessage.isBatchedUpdate());
    // $NON-NLS-1$
    assertFalse("RequestMessage.isCallableStatement should be false", statement.requestMessage.isCallableStatement());
    // $NON-NLS-1$
    assertTrue("RequestMessage.isPreparedStatement should be true", statement.requestMessage.isPreparedStatement());
    count[0] = 0;
    // large batch handling - should split into 5
    for (int i = 0; i < 100000; i++) {
        statement.setInt(1, new Integer(1));
        statement.addBatch();
    }
    try {
        statement.executeBatch();
        fail();
    } catch (BatchUpdateException e) {
        assertEquals(100000, count[0]);
        assertEquals(95309, e.getUpdateCounts().length);
        assertEquals(Statement.EXECUTE_FAILED, e.getUpdateCounts()[95308]);
    }
}
Also used : ResultsMessage(org.teiid.client.ResultsMessage) LogonResult(org.teiid.client.security.LogonResult) ArrayList(java.util.ArrayList) Properties(java.util.Properties) RequestMessage(org.teiid.client.RequestMessage) ArrayList(java.util.ArrayList) List(java.util.List) BatchUpdateException(java.sql.BatchUpdateException) DQP(org.teiid.client.DQP) ServerConnection(org.teiid.net.ServerConnection) TeiidException(org.teiid.core.TeiidException) ResultsFuture(org.teiid.client.util.ResultsFuture) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 10 with TeiidException

use of org.teiid.core.TeiidException in project teiid by teiid.

the class TestSQLException method testCreateThrowable_02.

/*
	 * Test method for 'com.metamatrix.jdbc.MMSQLException.create(Throwable)'
	 * 
	 * Tests various nested exceptions to see if the expected SQLState is
	 * returend.
	 */
@Test
public void testCreateThrowable_02() {
    testCreateThrowable(new CommunicationException(new ConnectException(// $NON-NLS-1$
    "A test java.net.ConnectException"), // $NON-NLS-1$
    "Test Communication Exception with a ConnectException in it"), SQLStates.CONNECTION_EXCEPTION_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION);
    testCreateThrowable(new CommunicationException(new SocketException(// $NON-NLS-1$
    "A test java.net.SocketException"), // $NON-NLS-1$
    "Test Communication Exception with a SocketException in it"), SQLStates.CONNECTION_EXCEPTION_STALE_CONNECTION);
    testCreateThrowable(new TeiidException(new SocketTimeoutException(// $NON-NLS-1$
    "A test java.net.SocketTimeoutException"), // $NON-NLS-1$
    "Test MetaMatrixException with a SocketTimeoutException in it"), SQLStates.CONNECTION_EXCEPTION_STALE_CONNECTION);
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) CommunicationException(org.teiid.net.CommunicationException) ConnectException(java.net.ConnectException) TeiidException(org.teiid.core.TeiidException) Test(org.junit.Test)

Aggregations

TeiidException (org.teiid.core.TeiidException)85 TeiidRuntimeException (org.teiid.core.TeiidRuntimeException)26 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)13 QueryMetadataInterface (org.teiid.query.metadata.QueryMetadataInterface)10 SQLException (java.sql.SQLException)9 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)8 BigInteger (java.math.BigInteger)6 Column (org.teiid.metadata.Column)6 Command (org.teiid.query.sql.lang.Command)6 TranslatorException (org.teiid.translator.TranslatorException)6 IOException (java.io.IOException)5 TeiidProcessingException (org.teiid.core.TeiidProcessingException)5 List (java.util.List)4 EdmEntityType (org.apache.olingo.commons.api.edm.EdmEntityType)4 ODataApplicationException (org.apache.olingo.server.api.ODataApplicationException)4 TeiidComponentException (org.teiid.core.TeiidComponentException)4 UpdateResponse (org.teiid.odata.api.UpdateResponse)4 Update (org.teiid.query.sql.lang.Update)4 SocketTimeoutException (java.net.SocketTimeoutException)3