Search in sources :

Example 21 with KvPair

use of doitincloud.rdbcache.models.KvPair in project rdbcache by rdbcache.

the class RdbcacheApis method getset_get.

/**
 * getset_get get single item
 *
 * To get current value of a key and update it to a new value based on the key and/or query string.
 * It finds the current value and returns immediately, and asynchronously updates to redis and database
 *
 * @param request HttpServletRequest
 * @param key String, hash key
 * @param value String, value
 * @param opt1 String, can be expire or table or "sync" or "async"
 * @param opt2 String, can be expire or table or "sync" or "async", but not otp1
 * @param opt3 String, can be expire or table or "sync" or "async", but not otp1 and opt2
 * @return ResponseEntity
 */
@RequestMapping(value = { "/rdbcache/v1/getset/{key}/{value}", "/rdbcache/v1/getset/{key}/{value}/{opt1}", "/rdbcache/v1/getset/{key}/{value}/{opt1}/{opt2}", "/rdbcache/v1/getset/{key}/{value}/{opt1}/{opt2}/{opt3}" }, method = RequestMethod.GET)
public ResponseEntity<?> getset_get(HttpServletRequest request, @PathVariable("key") String key, @PathVariable("value") String value, @PathVariable Optional<String> opt1, @PathVariable Optional<String> opt2, @PathVariable Optional<String> opt3) {
    Context context = new Context(true);
    KvPairs pairs = new KvPairs(key, value);
    AnyKey anyKey = Request.process(context, request, pairs, opt1, opt2, opt3);
    LOGGER.trace(anyKey.print() + " pairs(" + pairs.size() + "): " + pairs.printKey());
    KvPairs pairsClone = pairs.clone();
    KvPair pair = pairs.getPair();
    if (key.equals("*")) {
        if (!AppCtx.getDbaseRepo().find(context, pairs, anyKey)) {
            pair.clearData();
        }
        AppCtx.getAsyncOps().doSaveToRedis(context, pairsClone, anyKey);
    } else if (AppCtx.getRedisRepo().findAndSave(context, pairs, anyKey)) {
        AppCtx.getAsyncOps().doSaveToDbase(context, pairsClone, anyKey);
    } else {
        if (!AppCtx.getDbaseRepo().find(context, pairs, anyKey)) {
            pair.clearData();
        }
        AppCtx.getAsyncOps().doSaveToDbase(context, pairsClone, anyKey);
    }
    return Response.send(context, pairs);
}
Also used : Context(doitincloud.rdbcache.supports.Context) AnyKey(doitincloud.rdbcache.supports.AnyKey) KvPair(doitincloud.rdbcache.models.KvPair) KvPairs(doitincloud.rdbcache.supports.KvPairs)

Example 22 with KvPair

use of doitincloud.rdbcache.models.KvPair in project rdbcache by rdbcache.

the class RdbcacheApis method trace_get.

/**
 * trace_get get single item
 *
 * get error messages by trace id
 *
 * @param request HttpServletRequest
 * @param traceId the trace id return by API call
 * @return ResponseEntity
 */
@RequestMapping(value = { "/rdbcache/v1/trace/{traceId}" }, method = RequestMethod.GET)
public ResponseEntity<?> trace_get(HttpServletRequest request, @PathVariable("traceId") String traceId) {
    if (request.getParameterMap().size() != 0) {
        throw new BadRequestException("query string is not supported");
    }
    if (traceId.equals("*")) {
        throw new BadRequestException("no * allowed as trace id");
    }
    if (request.getParameterMap().size() != 0) {
        throw new BadRequestException("no query string is allowed");
    }
    Context context = new Context(true);
    KvPairs pairs = new KvPairs();
    Request.process(context, request, pairs);
    LOGGER.trace("pairs(" + pairs.size() + "): " + pairs.printKey());
    KvPair pair = AppCtx.getKvPairRepo().findById(new KvIdType(traceId, "trace"));
    if (pair != null) {
        pairs.add(pair);
    }
    return Response.send(context, pairs);
}
Also used : Context(doitincloud.rdbcache.supports.Context) KvIdType(doitincloud.rdbcache.models.KvIdType) KvPair(doitincloud.rdbcache.models.KvPair) BadRequestException(doitincloud.commons.exceptions.BadRequestException) KvPairs(doitincloud.rdbcache.supports.KvPairs)

Example 23 with KvPair

use of doitincloud.rdbcache.models.KvPair in project rdbcache by rdbcache.

the class Query method executeInsert.

public boolean executeInsert(boolean enableLocal, boolean enableRedis) {
    params = new ArrayList<>();
    boolean allOk = true;
    for (int i = 0; i < pairs.size(); i++) {
        KvPair pair = pairs.get(i);
        KeyInfo keyInfo = anyKey.getAny(i);
        String table = keyInfo.getTable();
        Map<String, Object> map = pair.getData();
        String autoIncKey = AppCtx.getDbaseOps().getTableAutoIncColumn(context, table);
        boolean cacheUpdate = false;
        if (!map.containsKey(autoIncKey) && keyInfo.getParams() != null && keyInfo.getParams().size() == 1) {
            String stdClause = "(" + autoIncKey + " = ?)";
            if (stdClause.equals(keyInfo.getClause())) {
                map.put(autoIncKey, keyInfo.getParams().get(0));
                cacheUpdate = true;
            }
        }
        Map<String, Object> columns = keyInfo.getColumns();
        AppCtx.getDbaseOps().convertDbMap(columns, map);
        String fields = "", values = "";
        params.clear();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.add(entry.getValue());
            if (fields.length() != 0) {
                fields += ", ";
                values += ", ";
            }
            fields += entry.getKey();
            values += "?";
        }
        sql = "insert into " + table + " (" + fields + ") values (" + values + ")";
        LOGGER.trace("sql: " + sql);
        LOGGER.trace("params: " + params.toString());
        int rowCount = 0;
        KeyHolder keyHolder = new GeneratedKeyHolder();
        StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.update");
        try {
            rowCount = jdbcTemplate.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps;
                    ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                    int i = 1;
                    for (Object param : params) {
                        ps.setObject(i++, param);
                    }
                    return ps;
                }
            }, keyHolder);
            if (stopWatch != null)
                stopWatch.stopNow();
        } catch (Exception e) {
            if (stopWatch != null)
                stopWatch.stopNow();
            allOk = false;
            String msg = e.getCause().getMessage();
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            if (context.isSync()) {
                throw new ServerErrorException(context, msg);
            }
        }
        if (rowCount > 0) {
            if (autoIncKey != null && keyHolder.getKey() != null) {
                String keyValue = String.valueOf(keyHolder.getKey());
                map.put(autoIncKey, keyValue);
                cacheUpdate = true;
            }
            if (cacheUpdate) {
                if (enableLocal) {
                    AppCtx.getCacheOps().putData(pair, keyInfo);
                }
                if (enableRedis) {
                    AppCtx.getRedisRepo().save(context, new KvPairs(pair), new AnyKey(keyInfo));
                }
            }
            if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
                String msg = "executeInsert failed when prepareStandardClauseParams for " + pair.getId();
                LOGGER.error(msg);
                context.logTraceMessage(msg);
                if (context.isSync()) {
                    throw new ServerErrorException(context, msg);
                }
            }
            LOGGER.trace("inserted " + pair.getId() + " into " + table);
        } else {
            allOk = false;
            LOGGER.warn("failed to insert " + pair.getId() + " into " + table);
        }
    }
    return allOk;
}
Also used : AnyKey(doitincloud.rdbcache.supports.AnyKey) KvPair(doitincloud.rdbcache.models.KvPair) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) KvPairs(doitincloud.rdbcache.supports.KvPairs) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) SQLException(java.sql.SQLException) ServerErrorException(doitincloud.commons.exceptions.ServerErrorException) StopWatch(doitincloud.rdbcache.models.StopWatch) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) KeyInfo(doitincloud.rdbcache.models.KeyInfo) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) ServerErrorException(doitincloud.commons.exceptions.ServerErrorException)

Example 24 with KvPair

use of doitincloud.rdbcache.models.KvPair in project rdbcache by rdbcache.

the class KvPairsTest method mapConstructor.

@Test
public void mapConstructor() {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("k0", Utils.toMap("{\"kk0\": 0}"));
    map.put("k1", Utils.toMap("{\"kk1\": 1}"));
    map.put("k2", Utils.toMap("{\"kk2\": 2}"));
    KvPairs pairs = new KvPairs(map);
    assertEquals(3, pairs.size());
    for (int i = 0; i < 3; i++) {
        KvPair pair = pairs.get(i);
        assertEquals("k" + i, pair.getId());
        map = pair.getData();
        assertEquals(i, map.get("kk" + i));
    }
}
Also used : KvPair(doitincloud.rdbcache.models.KvPair) KvPairs(doitincloud.rdbcache.supports.KvPairs) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 25 with KvPair

use of doitincloud.rdbcache.models.KvPair in project rdbcache by rdbcache.

the class KvPairsTest method setPair.

@Test
public void setPair() {
    KvPairs pairs;
    KvPair pair;
    pairs = new KvPairs();
    pair = new KvPair();
    pairs.setPair(pair);
    assertEquals(1, pairs.size());
    assertTrue(pair == pairs.get(0));
    pairs = new KvPairs(new KvPair());
    pair = new KvPair("key", "data", "value");
    pairs.setPair(pair);
    assertEquals(1, pairs.size());
    assertTrue(pair == pairs.get(0));
}
Also used : KvPair(doitincloud.rdbcache.models.KvPair) KvPairs(doitincloud.rdbcache.supports.KvPairs) Test(org.junit.Test)

Aggregations

KvPair (doitincloud.rdbcache.models.KvPair)51 KeyInfo (doitincloud.rdbcache.models.KeyInfo)29 KvPairs (doitincloud.rdbcache.supports.KvPairs)22 Context (doitincloud.rdbcache.supports.Context)15 Test (org.junit.Test)15 AnyKey (doitincloud.rdbcache.supports.AnyKey)14 StopWatch (doitincloud.rdbcache.models.StopWatch)13 ServerErrorException (doitincloud.commons.exceptions.ServerErrorException)9 BadRequestException (doitincloud.commons.exceptions.BadRequestException)7 KvIdType (doitincloud.rdbcache.models.KvIdType)6 SQLException (java.sql.SQLException)4 WebMvcTest (org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest)4 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)4 MvcResult (org.springframework.test.web.servlet.MvcResult)4 RequestBuilder (org.springframework.test.web.servlet.RequestBuilder)4 ResultActions (org.springframework.test.web.servlet.ResultActions)4 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)2 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)2 NotFoundException (doitincloud.commons.exceptions.NotFoundException)1