Search in sources :

Example 1 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project storm by apache.

the class BoundCQLStatementTupleMapper method map.

/**
     * {@inheritDoc}
     */
@Override
public List<Statement> map(Map config, Session session, ITuple tuple) {
    final List<Column> columns = mapper.map(tuple);
    final String query = contextQuery.resolves(config, tuple);
    PreparedStatement statement = getPreparedStatement(session, query);
    if (hasRoutingKeys()) {
        List<ByteBuffer> keys = rkGenerator.getRoutingKeys(tuple);
        if (keys.size() == 1)
            statement.setRoutingKey(keys.get(0));
        else
            statement.setRoutingKey(keys.toArray(new ByteBuffer[keys.size()]));
    }
    return Arrays.asList((Statement) this.binder.apply(statement, columns));
}
Also used : Column(org.apache.storm.cassandra.query.Column) PreparedStatement(com.datastax.driver.core.PreparedStatement) ByteBuffer(java.nio.ByteBuffer)

Example 2 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project nifi by apache.

the class PutCassandraQL method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    ComponentLog logger = getLogger();
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    final long startNanos = System.nanoTime();
    final long statementTimeout = context.getProperty(STATEMENT_TIMEOUT).evaluateAttributeExpressions(flowFile).asTimePeriod(TimeUnit.MILLISECONDS);
    final Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    // The documentation for the driver recommends the session remain open the entire time the processor is running
    // and states that it is thread-safe. This is why connectionSession is not in a try-with-resources.
    final Session connectionSession = cassandraSession.get();
    String cql = getCQL(session, flowFile, charset);
    try {
        PreparedStatement statement = connectionSession.prepare(cql);
        BoundStatement boundStatement = statement.bind();
        Map<String, String> attributes = flowFile.getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            final Matcher matcher = CQL_TYPE_ATTRIBUTE_PATTERN.matcher(key);
            if (matcher.matches()) {
                final int parameterIndex = Integer.parseInt(matcher.group(1));
                String paramType = entry.getValue();
                if (StringUtils.isEmpty(paramType)) {
                    throw new ProcessException("Value of the " + key + " attribute is null or empty, it must contain a valid value");
                }
                paramType = paramType.trim();
                final String valueAttrName = "cql.args." + parameterIndex + ".value";
                final String parameterValue = attributes.get(valueAttrName);
                try {
                    setStatementObject(boundStatement, parameterIndex - 1, valueAttrName, parameterValue, paramType);
                } catch (final InvalidTypeException | IllegalArgumentException e) {
                    throw new ProcessException("The value of the " + valueAttrName + " is '" + parameterValue + "', which cannot be converted into the necessary data type: " + paramType, e);
                }
            }
        }
        try {
            ResultSetFuture future = connectionSession.executeAsync(boundStatement);
            if (statementTimeout > 0) {
                future.getUninterruptibly(statementTimeout, TimeUnit.MILLISECONDS);
            } else {
                future.getUninterruptibly();
            }
            // Emit a Provenance SEND event
            final long transmissionMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
            // This isn't a real URI but since Cassandra is distributed we just use the cluster name
            String transitUri = "cassandra://" + connectionSession.getCluster().getMetadata().getClusterName();
            session.getProvenanceReporter().send(flowFile, transitUri, transmissionMillis, true);
            session.transfer(flowFile, REL_SUCCESS);
        } catch (final TimeoutException e) {
            throw new ProcessException(e);
        }
    } catch (final NoHostAvailableException nhae) {
        getLogger().error("No host in the Cassandra cluster can be contacted successfully to execute this statement", nhae);
        // Log up to 10 error messages. Otherwise if a 1000-node cluster was specified but there was no connectivity,
        // a thousand error messages would be logged. However we would like information from Cassandra itself, so
        // cap the error limit at 10, format the messages, and don't include the stack trace (it is displayed by the
        // logger message above).
        getLogger().error(nhae.getCustomMessage(10, true, false));
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_RETRY);
    } catch (final QueryExecutionException qee) {
        logger.error("Cannot execute the statement with the requested consistency level successfully", qee);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_RETRY);
    } catch (final QueryValidationException qve) {
        logger.error("The CQL statement {} is invalid due to syntax error, authorization issue, or another " + "validation problem; routing {} to failure", new Object[] { cql, flowFile }, qve);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    } catch (final ProcessException e) {
        logger.error("Unable to execute CQL select statement {} for {} due to {}; routing to failure", new Object[] { cql, flowFile, e });
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) ResultSetFuture(com.datastax.driver.core.ResultSetFuture) Matcher(java.util.regex.Matcher) Charset(java.nio.charset.Charset) PreparedStatement(com.datastax.driver.core.PreparedStatement) ComponentLog(org.apache.nifi.logging.ComponentLog) ProcessException(org.apache.nifi.processor.exception.ProcessException) QueryExecutionException(com.datastax.driver.core.exceptions.QueryExecutionException) QueryValidationException(com.datastax.driver.core.exceptions.QueryValidationException) NoHostAvailableException(com.datastax.driver.core.exceptions.NoHostAvailableException) BoundStatement(com.datastax.driver.core.BoundStatement) Map(java.util.Map) Session(com.datastax.driver.core.Session) ProcessSession(org.apache.nifi.processor.ProcessSession) InvalidTypeException(com.datastax.driver.core.exceptions.InvalidTypeException) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project smscgateway by RestComm.

the class DBOperations method c2_updateInSystem.

public void c2_updateInSystem(Sms sms, int isSystemStatus, boolean fastStoreAndForwordMode) throws PersistenceException {
    if (sms.getStored()) {
        PreparedStatementCollection psc = this.getStatementCollection(sms.getDueSlot());
        // in rerouting case we use need to use original networkId
        String targetId;
        if (sms.getTargetIdOnDeliveryStart() != null) {
            targetId = sms.getTargetIdOnDeliveryStart();
        } else {
            targetId = sms.getSmsSet().getTargetId();
        }
        if (isSystemStatus == DBOperations.IN_SYSTEM_SENT) {
            // increment sent_messages
            try {
                Date scheduledDeliveryDate = c2_getTimeForDueSlot(sms.getDueSlot());
                Calendar calendar = GregorianCalendar.getInstance();
                calendar.setTime(scheduledDeliveryDate);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                PreparedStatement ps = psc.updateSentMessagesCount;
                BoundStatement boundStatement = new BoundStatement(ps);
                boundStatement.bind(DATE_FORMAT.format(scheduledDeliveryDate));
                ResultSet res = session.execute(boundStatement);
                SmsSetCache.getInstance().incrementSentMessagesCounter(calendar.getTimeInMillis());
            } catch (Exception e1) {
                String msg = "Failed to execute updatePendingMessagesCount() !";
                throw new PersistenceException(msg, e1);
            }
        }
        try {
            PreparedStatement ps = psc.updateInSystem;
            BoundStatement boundStatement = new BoundStatement(ps);
            boundStatement.bind(isSystemStatus, currentSessionUUID, sms.getDueSlot(), targetId, sms.getDbId());
            ResultSet res = session.execute(boundStatement);
        } catch (Exception e1) {
            String msg = "Failed to execute updateInSystem() !";
            throw new PersistenceException(msg, e1);
        }
    }
}
Also used : GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) ResultSet(com.datastax.driver.core.ResultSet) PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) Date(java.util.Date) XMLStreamException(javolution.xml.stream.XMLStreamException) InvalidQueryException(com.datastax.driver.core.exceptions.InvalidQueryException)

Example 4 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project smscgateway by RestComm.

the class DBOperations method c2_getRecordListForTargeId.

public SmsSet c2_getRecordListForTargeId(long dueSlot, String targetId) throws PersistenceException {
    PreparedStatementCollection psc = getStatementCollection(dueSlot);
    SmsSet result = null;
    try {
        PreparedStatement ps = psc.getRecordData2;
        BoundStatement boundStatement = new BoundStatement(ps);
        boundStatement.bind(dueSlot, targetId);
        ResultSet res = session.execute(boundStatement);
        for (Row row : res) {
            result = this.createSms(row, result, psc.getShortMessageNewStringFormat(), psc.getAddedCorrId(), psc.getAddedNetworkId(), psc.getAddedOrigNetworkId(), psc.getAddedPacket1(), false);
        }
    } catch (Exception e1) {
        String msg = "Failed getRecordListForTargeId()";
        throw new PersistenceException(msg, e1);
    }
    return result;
}
Also used : ResultSet(com.datastax.driver.core.ResultSet) PreparedStatement(com.datastax.driver.core.PreparedStatement) Row(com.datastax.driver.core.Row) BoundStatement(com.datastax.driver.core.BoundStatement) SmsSet(org.mobicents.smsc.library.SmsSet) XMLStreamException(javolution.xml.stream.XMLStreamException) InvalidQueryException(com.datastax.driver.core.exceptions.InvalidQueryException)

Example 5 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project smscgateway by RestComm.

the class DBOperations method c2_createRecordCurrent.

public void c2_createRecordCurrent(Sms sms) throws PersistenceException {
    long dueSlot = sms.getDueSlot();
    PreparedStatementCollection psc = getStatementCollection(dueSlot);
    try {
        PreparedStatement ps = psc.createRecordCurrent;
        BoundStatement boundStatement = new BoundStatement(ps);
        setSmsFields(sms, dueSlot, boundStatement, false, psc.getShortMessageNewStringFormat(), psc.getAddedCorrId(), psc.getAddedNetworkId(), psc.getAddedOrigNetworkId(), psc.getAddedPacket1());
        ResultSet res = session.execute(boundStatement);
        try {
            Date scheduledDeliveryDate = c2_getTimeForDueSlot(sms.getDueSlot());
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(scheduledDeliveryDate);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            ps = psc.updateStoredMessagesCount;
            boundStatement = new BoundStatement(ps);
            boundStatement.bind(DATE_FORMAT.format(scheduledDeliveryDate));
            res = session.execute(boundStatement);
            SmsSetCache.getInstance().incrementStoredMessagesCounter(calendar.getTimeInMillis());
        } catch (Exception e1) {
            String msg = "Failed updateStoredMessagesCount !" + e1.getMessage();
            throw new PersistenceException(msg, e1);
        }
    } catch (Exception e1) {
        String msg = "Failed createRecordCurrent !" + e1.getMessage();
        throw new PersistenceException(msg, e1);
    }
}
Also used : GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) ResultSet(com.datastax.driver.core.ResultSet) PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) Date(java.util.Date) XMLStreamException(javolution.xml.stream.XMLStreamException) InvalidQueryException(com.datastax.driver.core.exceptions.InvalidQueryException)

Aggregations

PreparedStatement (com.datastax.driver.core.PreparedStatement)113 ResultSet (com.datastax.driver.core.ResultSet)60 BoundStatement (com.datastax.driver.core.BoundStatement)59 Session (com.datastax.driver.core.Session)39 Test (org.junit.Test)30 Row (com.datastax.driver.core.Row)27 InvalidQueryException (com.datastax.driver.core.exceptions.InvalidQueryException)27 XMLStreamException (javolution.xml.stream.XMLStreamException)25 PersistenceException (org.mobicents.smsc.cassandra.PersistenceException)15 Cluster (com.datastax.driver.core.Cluster)9 Date (java.util.Date)9 IInvokableInstance (org.apache.cassandra.distributed.api.IInvokableInstance)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Map (java.util.Map)7 QueryProcessor (org.apache.cassandra.cql3.QueryProcessor)7 GOSSIP (org.apache.cassandra.distributed.api.Feature.GOSSIP)7 NATIVE_PROTOCOL (org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL)7 NETWORK (org.apache.cassandra.distributed.api.Feature.NETWORK)7 ICluster (org.apache.cassandra.distributed.api.ICluster)7