Search in sources :

Example 11 with WritePolicy

use of com.aerospike.client.policy.WritePolicy 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 WritePolicy

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

the class TestReplace method replace.

@Test
public void replace() {
    Key key = new Key(args.namespace, args.set, "replacekey");
    Bin bin1 = new Bin("bin1", "value1");
    Bin bin2 = new Bin("bin2", "value2");
    Bin bin3 = new Bin("bin3", "value3");
    client.put(null, key, bin1, bin2);
    WritePolicy policy = new WritePolicy();
    policy.recordExistsAction = RecordExistsAction.REPLACE;
    client.put(policy, key, bin3);
    Record record = client.get(null, key);
    assertRecordFound(key, record);
    if (record.getValue(bin1.name) != null) {
        fail(bin1.name + " found when it should have been deleted.");
    }
    if (record.getValue(bin2.name) != null) {
        fail(bin2.name + " found when it should have been deleted.");
    }
    assertBinEqual(key, record, bin3);
}
Also used : Bin(com.aerospike.client.Bin) Record(com.aerospike.client.Record) Key(com.aerospike.client.Key) WritePolicy(com.aerospike.client.policy.WritePolicy) Test(org.junit.Test)

Example 13 with WritePolicy

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

the class TestReplace method replaceOnly.

@Test
public void replaceOnly() {
    Key key = new Key(args.namespace, args.set, "replaceonlykey");
    Bin bin = new Bin("bin", "value");
    // Delete record if it already exists.
    client.delete(null, key);
    try {
        WritePolicy policy = new WritePolicy();
        policy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
        client.put(policy, key, bin);
        fail("Failure. This command should have resulted in an error.");
    } catch (AerospikeException ae) {
        if (ae.getResultCode() != ResultCode.KEY_NOT_FOUND_ERROR) {
            throw ae;
        }
    }
}
Also used : AerospikeException(com.aerospike.client.AerospikeException) Bin(com.aerospike.client.Bin) Key(com.aerospike.client.Key) WritePolicy(com.aerospike.client.policy.WritePolicy) Test(org.junit.Test)

Example 14 with WritePolicy

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

the class TestExpire method noExpire.

@Test
public void noExpire() {
    Key key = new Key(args.namespace, args.set, "expirekey");
    Bin bin = new Bin(binName, "noexpirevalue");
    // Specify that record NEVER expires. 
    // The "Never Expire" value is -1, or 0xFFFFFFFF.
    WritePolicy writePolicy = new WritePolicy();
    writePolicy.expiration = -1;
    client.put(writePolicy, key, bin);
    // Read the record, showing it is there.
    Record record = client.get(null, key, bin.name);
    assertBinEqual(key, record, bin);
    // Read this Record after the Default Expiration, showing it is still there.
    // We should have set the Namespace TTL at 5 sec.
    Util.sleep(10 * 1000);
    record = client.get(null, key, bin.name);
    assertNotNull(record);
}
Also used : Bin(com.aerospike.client.Bin) Record(com.aerospike.client.Record) Key(com.aerospike.client.Key) WritePolicy(com.aerospike.client.policy.WritePolicy) Test(org.junit.Test)

Example 15 with WritePolicy

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

the class TestExpire method expire.

@Test
public void expire() {
    Key key = new Key(args.namespace, args.set, "expirekey ");
    Bin bin = new Bin(binName, "expirevalue");
    // Specify that record expires 2 seconds after it's written.
    WritePolicy writePolicy = new WritePolicy();
    writePolicy.expiration = 2;
    client.put(writePolicy, key, bin);
    // Read the record before it expires, showing it is there.	
    Record record = client.get(null, key, bin.name);
    assertBinEqual(key, record, bin);
    // Read the record after it expires, showing it's gone.
    Util.sleep(3 * 1000);
    record = client.get(null, key, bin.name);
    assertNull(record);
}
Also used : Bin(com.aerospike.client.Bin) Record(com.aerospike.client.Record) Key(com.aerospike.client.Key) WritePolicy(com.aerospike.client.policy.WritePolicy) Test(org.junit.Test)

Aggregations

Bin (com.aerospike.client.Bin)21 Key (com.aerospike.client.Key)21 WritePolicy (com.aerospike.client.policy.WritePolicy)21 Record (com.aerospike.client.Record)12 Test (org.junit.Test)7 AerospikeException (com.aerospike.client.AerospikeException)6 BeforeClass (org.junit.BeforeClass)3 Policy (com.aerospike.client.policy.Policy)2 AerospikeClient (com.aerospike.client.AerospikeClient)1 Value (com.aerospike.client.Value)1 ClientPolicy (com.aerospike.client.policy.ClientPolicy)1 GenerationPolicy (com.aerospike.client.policy.GenerationPolicy)1 IndexTask (com.aerospike.client.task.IndexTask)1 IOException (java.io.IOException)1 Writer (java.io.Writer)1 ArrayList (java.util.ArrayList)1