Search in sources :

Example 11 with Policy

use of com.aerospike.client.policy.Policy in project aerospike-client-java by aerospike.

the class AerospikeServlet method processRequest.

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String method = request.getMethod();
    String jsonpCallback = null;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "no-cache");
    @SuppressWarnings("unchecked") Map<String, String[]> params = request.getParameterMap();
    String pathInfo = request.getPathInfo();
    final Writer writer = response.getWriter();
    // If no pathInfo, just bail now.
    if (pathInfo == null) {
        response.setStatus(HttpServletResponse.SC_OK);
        writer.flush();
        return;
    }
    // Method override - so handy when debugging, or using a brain-dead client
    if (params.containsKey("X-method")) {
        method = params.get("X-method")[0];
    }
    int responseCode = 200;
    String errorMsg = "";
    try {
        pathInfo = stripChar(pathInfo, '/');
        String[] pathArray = pathInfo.split("/");
        // Path *must* be of form namespace/set/key
        if (pathArray.length != 3) {
            throw new ResourceNotFoundException("Must Specify Namespace, Key, and Value");
        }
        String namespace = pathArray[0];
        String set = pathArray[1];
        String userKey = pathArray[2];
        // check that we've got a key
        if (userKey == null) {
            log("bad key received");
            throw new BadParamException("No Key");
        }
        Key key = new Key(namespace, set, userKey);
        // Get other parameters from the parameters on the URL
        String[] values = params.get("value");
        String[] bins = params.get("bin");
        String[] generations = params.get("generation");
        String[] timeouts = params.get("timeout");
        String[] ops = params.get("op");
        String[] expirations = params.get("expiration");
        String[] callbacks = params.get("callback");
        String[] jsonps = params.get("jsonp");
        int timeout = 0;
        try {
            timeout = (timeouts == null || timeouts.length == 0) ? 0 : Integer.parseInt(timeouts[0]);
        } catch (NumberFormatException e) {
            log("bad timeout received");
            throw new BadParamException("Timeout Not Numeric");
        }
        int expiration = 0;
        try {
            expiration = (expirations == null || expirations.length == 0) ? 0 : Integer.parseInt(expirations[0]);
        } catch (NumberFormatException e) {
            log("bad expiration received");
            throw new BadParamException("Expiration Not Numeric");
        }
        int generation = 0;
        try {
            generation = (generations == null || generations.length == 0) ? 0 : Integer.parseInt(generations[0]);
        } catch (NumberFormatException e) {
            log("bad generation received");
            throw new BadParamException("Generation Not Numeric");
        }
        if (callbacks != null) {
            jsonpCallback = callbacks[0];
        } else if (jsonps != null) {
            jsonpCallback = jsonps[0];
        }
        Policy policy = new Policy();
        policy.socketTimeout = timeout;
        if (method.equals("GET")) {
            Record record;
            if (bins == null)
                record = this.client.get(policy, key);
            else
                record = this.client.get(policy, key, bins);
            if (record != null) {
                if (record.bins != null) {
                    Set<?> keyset = record.bins.keySet();
                    Iterator<?> iterator = keyset.iterator();
                    if (!iterator.hasNext()) {
                        throw new ResourceNotFoundException("Server Returns No Values");
                    }
                    String resultJSON = "{\"result\" : {";
                    while (iterator.hasNext()) {
                        Object binName = iterator.next();
                        Object binValue = record.bins.get(binName);
                        resultJSON += "\"" + binName.toString() + "\" : ";
                        if (binValue instanceof Integer) {
                            resultJSON += binValue.toString();
                        } else if (binValue instanceof byte[]) {
                            System.out.println(" it's a blob!");
                        } else if (binValue instanceof String) {
                            resultJSON += "\"" + binValue.toString() + "\"";
                        } else {
                            resultJSON += "\"\"";
                        }
                        if (iterator.hasNext()) {
                            resultJSON += ",";
                        }
                    }
                    resultJSON += "},";
                    resultJSON += "\"generation\" : " + record.generation + "}";
                    if (jsonpCallback != null) {
                        resultJSON = jsonpCallback + "(" + resultJSON + ")";
                        response.setContentType("application/javascript");
                    }
                    writer.write(resultJSON);
                }
            } else {
                throw new ResourceNotFoundException("Key Not Found");
            }
        } else if (method.equals("POST")) {
            if (values == null || values.length < 1) {
                throw new BadParamException("Setting a key requires a value");
            }
            boolean isArithmeticAdd = false;
            boolean isAppend = false;
            boolean isPrepend = false;
            if (ops != null && ops.length > 0) {
                if (ops[0].equals("add")) {
                    isArithmeticAdd = true;
                } else if (ops[0].equals("append")) {
                    isAppend = true;
                } else if (ops[0].equals("prepend")) {
                    isPrepend = true;
                }
            }
            WritePolicy writePolicy = new WritePolicy();
            writePolicy.socketTimeout = timeout;
            writePolicy.expiration = expiration;
            if (generation != 0) {
                writePolicy.generationPolicy = GenerationPolicy.EXPECT_GEN_EQUAL;
                writePolicy.generation = generation;
            }
            if (values.length > 1) {
                if (bins == null || bins.length != values.length) {
                    throw new BadParamException("Setting a key requires a bin name");
                }
                Bin[] binArray = new Bin[bins.length];
                for (int i = 0; i < bins.length; i++) {
                    Object value = getObject(values[i], isArithmeticAdd);
                    binArray[i] = new Bin(bins[i], value);
                }
                if (isArithmeticAdd) {
                    client.add(writePolicy, key, binArray);
                } else if (isAppend) {
                    client.append(writePolicy, key, binArray);
                } else if (isPrepend) {
                    client.prepend(writePolicy, key, binArray);
                } else {
                    // standard set
                    client.put(writePolicy, key, binArray);
                }
            } else {
                String binName = bins != null && bins.length > 0 ? bins[0] : "";
                Object value = getObject(values[0], isArithmeticAdd);
                Bin bin = new Bin(binName, value);
                if (isArithmeticAdd) {
                    client.add(writePolicy, key, bin);
                } else if (isAppend) {
                    client.append(writePolicy, key, bin);
                } else if (isPrepend) {
                    client.prepend(writePolicy, key, bin);
                } else {
                    client.put(writePolicy, key, bin);
                }
            }
        } else if (method.equals("DELETE")) {
            WritePolicy writePolicy = new WritePolicy();
            writePolicy.socketTimeout = timeout;
            if (generation != 0) {
                writePolicy.generationPolicy = GenerationPolicy.EXPECT_GEN_EQUAL;
                writePolicy.generation = generation;
            }
            client.delete(writePolicy, key);
        } else {
            throw new BadMethodException("Unknown Method");
        }
    } catch (AerospikeException.Timeout e) {
        responseCode = HttpServletResponse.SC_REQUEST_TIMEOUT;
        errorMsg = e.getMessage();
    } catch (BadMethodException e) {
        responseCode = HttpServletResponse.SC_METHOD_NOT_ALLOWED;
        errorMsg = e.getMessage();
    } catch (BadParamException e) {
        responseCode = HttpServletResponse.SC_BAD_REQUEST;
        errorMsg = e.getMessage();
    } catch (ResourceNotFoundException e) {
        responseCode = HttpServletResponse.SC_NOT_FOUND;
        errorMsg = e.getMessage();
    } catch (AerospikeException ae) {
        responseCode = HttpServletResponse.SC_NOT_FOUND;
        errorMsg = "Error " + ae.getResultCode() + ": " + ae.getMessage();
    }
    if (responseCode != HttpServletResponse.SC_OK) {
        try {
            response.sendError(responseCode, errorMsg);
        } catch (java.io.IOException e) {
        }
    } else {
        response.setStatus(HttpServletResponse.SC_OK);
        writer.flush();
    }
}
Also used : GenerationPolicy(com.aerospike.client.policy.GenerationPolicy) Policy(com.aerospike.client.policy.Policy) ClientPolicy(com.aerospike.client.policy.ClientPolicy) WritePolicy(com.aerospike.client.policy.WritePolicy) AerospikeException(com.aerospike.client.AerospikeException) Bin(com.aerospike.client.Bin) IOException(java.io.IOException) Record(com.aerospike.client.Record) Writer(java.io.Writer) Key(com.aerospike.client.Key) WritePolicy(com.aerospike.client.policy.WritePolicy)

Example 12 with Policy

use of com.aerospike.client.policy.Policy in project aerospike-client-java by aerospike.

the class QueryGeoCollection method createIndex.

private void createIndex(AerospikeClient client, Parameters params, IndexCollectionType indexType, String indexName, String binName) throws Exception {
    console.info("Create GeoJSON %s index: ns=%s set=%s index=%s bin=%s", indexType, params.namespace, params.set, indexName, binName);
    Policy policy = new Policy();
    // Do not timeout on index create.
    policy.socketTimeout = 0;
    IndexTask task = client.createIndex(policy, params.namespace, params.set, indexName, binName, IndexType.GEO2DSPHERE, indexType);
    task.waitTillComplete();
}
Also used : Policy(com.aerospike.client.policy.Policy) IndexTask(com.aerospike.client.task.IndexTask)

Example 13 with Policy

use of com.aerospike.client.policy.Policy in project aerospike-client-java by aerospike.

the class QueryExecute method createIndex.

private void createIndex(AerospikeClient client, Parameters params, String indexName, String binName) throws Exception {
    console.info("Create index: ns=%s set=%s index=%s bin=%s", params.namespace, params.set, indexName, binName);
    Policy policy = new Policy();
    // Do not timeout on index create.
    policy.socketTimeout = 0;
    IndexTask task = client.createIndex(policy, params.namespace, params.set, indexName, binName, IndexType.NUMERIC);
    task.waitTillComplete();
}
Also used : Policy(com.aerospike.client.policy.Policy) IndexTask(com.aerospike.client.task.IndexTask)

Example 14 with Policy

use of com.aerospike.client.policy.Policy in project aerospike-client-java by aerospike.

the class QueryFilter method createIndex.

private void createIndex(AerospikeClient client, Parameters params, String indexName, String binName) throws Exception {
    console.info("Create index: ns=%s set=%s index=%s bin=%s", params.namespace, params.set, indexName, binName);
    Policy policy = new Policy();
    // Do not timeout on index create.
    policy.socketTimeout = 0;
    IndexTask task = client.createIndex(policy, params.namespace, params.set, indexName, binName, IndexType.STRING);
    task.waitTillComplete();
}
Also used : Policy(com.aerospike.client.policy.Policy) IndexTask(com.aerospike.client.task.IndexTask)

Example 15 with Policy

use of com.aerospike.client.policy.Policy in project aerospike-client-java by aerospike.

the class QueryRegionFilter method createIndex.

private void createIndex(AerospikeClient client, Parameters params, String indexName, String binName) throws Exception {
    console.info("Create index: ns=%s set=%s index=%s bin=%s", params.namespace, params.set, indexName, binName);
    Policy policy = new Policy();
    // Do not timeout on index create.
    policy.socketTimeout = 0;
    IndexTask task = client.createIndex(policy, params.namespace, params.set, indexName, binName, IndexType.GEO2DSPHERE);
    task.waitTillComplete();
}
Also used : Policy(com.aerospike.client.policy.Policy) IndexTask(com.aerospike.client.task.IndexTask)

Aggregations

Policy (com.aerospike.client.policy.Policy)24 IndexTask (com.aerospike.client.task.IndexTask)23 BeforeClass (org.junit.BeforeClass)10 Bin (com.aerospike.client.Bin)9 Key (com.aerospike.client.Key)9 RegisterTask (com.aerospike.client.task.RegisterTask)5 WritePolicy (com.aerospike.client.policy.WritePolicy)3 AerospikeException (com.aerospike.client.AerospikeException)1 Record (com.aerospike.client.Record)1 ClientPolicy (com.aerospike.client.policy.ClientPolicy)1 GenerationPolicy (com.aerospike.client.policy.GenerationPolicy)1 IOException (java.io.IOException)1 Writer (java.io.Writer)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1