index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/authservice/Authenticate.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.authservice; public class Authenticate { protected String sid; protected String uid; protected String pwd; public String getSid() { return sid; } public void setSid(String value) { this.sid = value; } public String getUid() { return uid; } public void setUid(String value) { this.uid = value; } public String getPwd() { return pwd; } public void setPwd(String value) { this.pwd = value; } }
0
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/jaxb_element_test/JaxbElementTestImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxb_element_test; import jakarta.jws.WebService; @WebService(serviceName = "jaxb_element_test", portName = "jaxb_element_testSOAP", targetNamespace = "http://cxf.apache.org/jaxb_element_test/", endpointInterface = "org.apache.cxf.jaxb_element_test.JaxbElementTest", wsdlLocation = "testutils/jaxb_element_test.wsdl") public class JaxbElementTestImpl implements JaxbElementTest { public String newOperation(String in) { if (in == null) { return "in=null"; } return "in=" + in; } }
1
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/mtom_xop/TestMtomImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.mtom_xop; import jakarta.activation.DataHandler; import jakarta.jws.WebService; import jakarta.xml.ws.Holder; import org.apache.cxf.mime.TestMtom; import org.apache.cxf.mime.types.XopStringType; @WebService(serviceName = "TestMtomService", portName = "TestMtomPort", targetNamespace = "http://cxf.apache.org/mime", endpointInterface = "org.apache.cxf.mime.TestMtom", wsdlLocation = "testutils/mtom_xop.wsdl") public class TestMtomImpl implements TestMtom { public void testXop(Holder<String> name, Holder<DataHandler> attachinfo) { if ("have name".equals(name.value) && attachinfo.value.getName() != null) { name.value = "return detail + " + attachinfo.value.getName(); } else if ("break schema".equals(name.value)) { name.value = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; } else { name.value = "return detail + " + name.value; } } public XopStringType testXopString(XopStringType data) { XopStringType d2 = new XopStringType(); d2.setAttachinfo("This is the cereal shot from guns" + data.getAttachinfo()); return d2; } }
2
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/mtom_xop/TestMtomProviderImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.mtom_xop; import java.io.InputStream; import jakarta.activation.DataHandler; import jakarta.mail.util.ByteArrayDataSource; import jakarta.xml.soap.AttachmentPart; import jakarta.xml.soap.MessageFactory; import jakarta.xml.soap.SOAPBody; import jakarta.xml.soap.SOAPBodyElement; import jakarta.xml.soap.SOAPElement; import jakarta.xml.soap.SOAPEnvelope; import jakarta.xml.soap.SOAPMessage; import jakarta.xml.soap.SOAPPart; import jakarta.xml.ws.Provider; import jakarta.xml.ws.Service.Mode; import jakarta.xml.ws.ServiceMode; import jakarta.xml.ws.WebServiceProvider; import jakarta.xml.ws.soap.MTOM; @WebServiceProvider(portName = "TestMtomProviderPort", serviceName = "TestMtomService", targetNamespace = "http://cxf.apache.org/mime", wsdlLocation = "testutils/mtom_xop.wsdl") @ServiceMode(value = Mode.MESSAGE) @MTOM public class TestMtomProviderImpl implements Provider<SOAPMessage> { public SOAPMessage invoke(final SOAPMessage request) { try { System.out.println("=== Received client request ==="); // create the SOAPMessage SOAPMessage message = MessageFactory.newInstance().createMessage(); SOAPPart part = message.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPBody body = envelope.getBody(); SOAPBodyElement testResponse = body .addBodyElement(envelope.createName("testXopResponse", null, "http://cxf.apache.org/mime/types")); SOAPElement name = testResponse.addChildElement("name", null, "http://cxf.apache.org/mime/types"); name.setTextContent("return detail + call detail"); SOAPElement attachinfo = testResponse.addChildElement( "attachinfo", null, "http://cxf.apache.org/mime/types"); SOAPElement include = attachinfo.addChildElement("Include", "xop", "http://www.w3.org/2004/08/xop/include"); int fileSize = 0; try (InputStream pre = this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl")) { for (int i = pre.read(); i != -1; i = pre.read()) { fileSize++; } } int count = 50; byte[] data = new byte[fileSize * count]; for (int x = 0; x < count; x++) { this.getClass().getResourceAsStream("/wsdl/mtom_xop.wsdl").read(data, fileSize * x, fileSize); } DataHandler dh = new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")); // create the image attachment AttachmentPart attachment = message.createAttachmentPart(dh); attachment.setContentId("mtom_xop.wsdl"); message.addAttachmentPart(attachment); System.out .println("Adding attachment: " + attachment.getContentId() + ":" + attachment.getSize()); // add the reference to the image attachment include.addAttribute(envelope.createName("href"), "cid:" + attachment.getContentId()); return message; } catch (Exception e) { e.printStackTrace(); } return null; } }
3
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/AbstractGreeterImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import jakarta.xml.ws.AsyncHandler; import jakarta.xml.ws.Response; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.greeter_control.types.FaultDetail; import org.apache.cxf.greeter_control.types.GreetMeResponse; import org.apache.cxf.greeter_control.types.PingMeResponse; import org.apache.cxf.greeter_control.types.SayHiResponse; /** * */ public class AbstractGreeterImpl implements Greeter { private static final Logger LOG = LogUtils.getLogger(AbstractGreeterImpl.class); private long delay; private String lastOnewayArg; private boolean throwAlways; private AtomicBoolean useLastOnewayArg = new AtomicBoolean(); private int pingMeCount; public long getDelay() { return delay; } public void setDelay(long d) { delay = d; } public void resetLastOnewayArg() { synchronized (this) { lastOnewayArg = null; } } public void useLastOnewayArg(boolean use) { useLastOnewayArg.set(use); } public void setThrowAlways(boolean t) { throwAlways = t; } public String greetMe(String arg0) { LOG.fine("Executing operation greetMe with parameter: " + arg0); if (delay > 0) { try { Thread.sleep(delay); } catch (InterruptedException ex) { // ignore } } String result = useLastOnewayArg.get() ? lastOnewayArg : arg0.toUpperCase(); LOG.fine("returning: " + result); return result; } public Future<?> greetMeAsync(String arg0, AsyncHandler<GreetMeResponse> arg1) { return null; } public Response<GreetMeResponse> greetMeAsync(String arg0) { return null; } public void greetMeOneWay(String arg0) { synchronized (this) { lastOnewayArg = arg0; } LOG.fine("Executing operation greetMeOneWay with parameter: " + arg0); } public void pingMe() throws PingMeFault { pingMeCount++; if ((pingMeCount % 2) == 0 || throwAlways) { LOG.fine("Throwing PingMeFault while executiong operation pingMe"); FaultDetail fd = new FaultDetail(); fd.setMajor((short)2); fd.setMinor((short)1); throw new PingMeFault("Pings succeed only every other time.", fd); } LOG.fine("Executing operation pingMe"); } public Response<PingMeResponse> pingMeAsync() { return null; } public Future<?> pingMeAsync(AsyncHandler<PingMeResponse> arg0) { return null; } public String sayHi() { return null; } public Response<SayHiResponse> sayHiAsync() { return null; } public Future<?> sayHiAsync(AsyncHandler<SayHiResponse> arg0) { return null; } }
4
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/GreeterNoWsdl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import jakarta.jws.Oneway; import jakarta.jws.WebMethod; import jakarta.jws.WebParam; import jakarta.jws.WebResult; import jakarta.jws.WebService; import jakarta.xml.ws.RequestWrapper; import jakarta.xml.ws.ResponseWrapper; /** * */ @WebService(targetNamespace = "http://cxf.apache.org/greeter_control", name = "Greeter") public interface GreeterNoWsdl { @ResponseWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.SayHiResponse", localName = "sayHiResponse") @RequestWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.SayHi", localName = "sayHi") @WebResult(targetNamespace = "http://cxf.apache.org/greeter_control/types", name = "responseType") @WebMethod(operationName = "sayHi") java.lang.String sayHi(); @ResponseWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.GreetMeResponse", localName = "greetMeResponse") @RequestWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.GreetMe", localName = "greetMe") @WebResult(targetNamespace = "http://cxf.apache.org/greeter_control/types", name = "responseType") @WebMethod(operationName = "greetMe") java.lang.String greetMe( @WebParam(targetNamespace = "http://cxf.apache.org/greeter_control/types", name = "requestType") java.lang.String requestType ); @Oneway @RequestWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.GreetMeOneWay", localName = "greetMeOneWay") @WebMethod(operationName = "greetMeOneWay") void greetMeOneWay( @WebParam(targetNamespace = "http://cxf.apache.org/greeter_control/types", name = "requestType") java.lang.String requestType ); @ResponseWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.PingMeResponse", localName = "pingMeResponse") @RequestWrapper(targetNamespace = "http://cxf.apache.org/greeter_control/types", className = "org.apache.cxf.greeter_control.types.PingMe", localName = "pingMe") @WebMethod(operationName = "pingMe") void pingMe() throws PingMeFault; }
5
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/FaultThrowingInterceptor.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import java.text.MessageFormat; import java.util.logging.Logger; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageUtils; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; /** * */ public class FaultThrowingInterceptor extends AbstractPhaseInterceptor<Message> { public static final MessageFormat MESSAGE_FORMAT = new MessageFormat("Interceptor fault in phase {0}."); private static final Logger LOG = LogUtils.getLogger(FaultThrowingInterceptor.class); public FaultThrowingInterceptor() { super(Phase.USER_LOGICAL); } public FaultThrowingInterceptor(String phase) { super(phase); } public void handleMessage(Message message) throws Fault { if (MessageUtils.isRequestor(message)) { return; } final String msg; synchronized (MESSAGE_FORMAT) { msg = MESSAGE_FORMAT.format(new Object[] {getPhase()}); } LOG.fine(msg); throw new Fault(new RuntimeException(msg)); } }
6
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/ControlImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import java.util.List; import java.util.concurrent.Future; import java.util.logging.Logger; import jakarta.jws.WebService; import jakarta.xml.ws.AsyncHandler; import jakarta.xml.ws.Endpoint; import jakarta.xml.ws.Response; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.configuration.Configurer; import org.apache.cxf.greeter_control.types.FaultLocation; import org.apache.cxf.greeter_control.types.StartGreeterResponse; import org.apache.cxf.greeter_control.types.StopGreeterResponse; import org.apache.cxf.interceptor.Interceptor; import org.apache.cxf.message.Message; @WebService(serviceName = "ControlService", portName = "ControlPort", endpointInterface = "org.apache.cxf.greeter_control.Control", targetNamespace = "http://cxf.apache.org/greeter_control") public class ControlImpl implements Control { private static final Logger LOG = LogUtils.getLogger(ControlImpl.class); protected Object implementor; protected String address; protected Endpoint endpoint; protected Bus greeterBus; public void setImplementor(Object i) { implementor = i; } public Object getImplementor() { return implementor; } public void setAddress(String a) { address = a; } public String getAddress() { return address; } public boolean startGreeter(String cfgResource) { LOG.fine("Starting greeter with cfgResource: " + cfgResource); greeterBus = null; BusFactory.setDefaultBus(null); String original = System.clearProperty(Configurer.USER_CFG_FILE_PROPERTY_NAME); try { if (cfgResource != null && cfgResource.length() > 0) { System.setProperty(Configurer.USER_CFG_FILE_PROPERTY_NAME, cfgResource); } String a = address == null ? "http://localhost:9020/SoapContext/GreeterPort" : address; Object i = implementor == null ? new GreeterImpl() : implementor; endpoint = Endpoint.publish(a, i); LOG.info("Published greeter endpoint on bus with cfg file resource: " + cfgResource); greeterBus = BusFactory.getDefaultBus(); } finally { System.clearProperty(Configurer.USER_CFG_FILE_PROPERTY_NAME); if (null != original) { System.setProperty(Configurer.USER_CFG_FILE_PROPERTY_NAME, cfgResource); } } if (implementor instanceof AbstractGreeterImpl) { ((AbstractGreeterImpl)implementor).resetLastOnewayArg(); } return null != greeterBus; } public boolean stopGreeter(String requestType) { LOG.fine("Stopping greeter"); if (null != endpoint) { LOG.info("Stopping Greeter endpoint"); endpoint.stop(); } else { LOG.info("No endpoint active."); } endpoint = null; if (null != greeterBus) { greeterBus.shutdown(true); } greeterBus = null; return true; } public void setFaultLocation(FaultLocation fl) { List<Interceptor<? extends Message>> interceptors = greeterBus.getInInterceptors(); for (Interceptor<? extends Message> i : interceptors) { if (i instanceof FaultThrowingInterceptor) { interceptors.remove(i); LOG.fine("Removed existing FaultThrowingInterceptor"); break; } } if (null == fl.getPhase() || "".equals(fl.getPhase())) { LOG.fine("Removed FaultThrowingInterceptor"); return; } FaultThrowingInterceptor fi = new FaultThrowingInterceptor(fl.getPhase()); if (null != fl.getBefore() && !"".equals(fl.getBefore())) { fi.addBefore(fl.getBefore()); } if (null != fl.getAfter() && !"".equals(fl.getAfter())) { fi.addAfter(fl.getAfter()); } interceptors.add(fi); LOG.fine("Added FaultThrowingInterceptor to phase " + fl.getPhase()); } public Future<?> startGreeterAsync(String requestType, AsyncHandler<StartGreeterResponse> asyncHandler) { // never called return null; } public Response<StartGreeterResponse> startGreeterAsync(String requestType) { // never called return null; } public Response<StopGreeterResponse> stopGreeterAsync(String requestType) { // never called return null; } public Future<?> stopGreeterAsync(String requestType, AsyncHandler<StopGreeterResponse> asyncHandler) { // never called return null; } @WebService(serviceName = "GreeterService", portName = "GreeterPort", endpointInterface = "org.apache.cxf.greeter_control.Greeter", targetNamespace = "http://cxf.apache.org/greeter_control") class GreeterImpl extends AbstractGreeterImpl { } public Response<?> setFaultLocationAsync(FaultLocation in) { return null; } public Future<?> setFaultLocationAsync(FaultLocation in, AsyncHandler<?> asyncHandler) { return null; } public Response<?> setRobustInOnlyModeAsync(boolean in) { return null; } public Future<?> setRobustInOnlyModeAsync(boolean in, AsyncHandler<?> asyncHandler) { return null; } public void setRobustInOnlyMode(boolean in) { endpoint.getProperties().put(Message.ROBUST_ONEWAY, in); } }
7
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/GreeterImplNoWsdl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import jakarta.jws.WebService; @WebService(serviceName = "GreeterService", portName = "GreeterPort", endpointInterface = "org.apache.cxf.greeter_control.GreeterNoWsdl", targetNamespace = "http://cxf.apache.org/greeter_control") /* This class implments the SEI but SEI does not specify wsdlLocation */ public class GreeterImplNoWsdl extends GreeterImplBase implements GreeterNoWsdl { }
8
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/GreeterImplBaseNoWsdl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import jakarta.jws.WebService; @WebService(serviceName = "GreeterService", portName = "GreeterPort", endpointInterface = "org.apache.cxf.greeter_control.GreeterNoWsdl", targetNamespace = "http://cxf.apache.org/greeter_control") /* This class does not implement the SEI and SEI does not specify wsdlLocation */ public class GreeterImplBaseNoWsdl extends GreeterImplBase { }
9
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/greeter_control/GreeterImplBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.greeter_control; import java.util.concurrent.Future; import jakarta.jws.WebService; import jakarta.xml.ws.AsyncHandler; import jakarta.xml.ws.Response; import org.apache.cxf.greeter_control.types.GreetMeResponse; import org.apache.cxf.greeter_control.types.PingMeResponse; import org.apache.cxf.greeter_control.types.SayHiResponse; @WebService(serviceName = "GreeterService", portName = "GreeterPort", endpointInterface = "org.apache.cxf.greeter_control.Greeter", targetNamespace = "http://cxf.apache.org/greeter_control") /* This class does not implement the SEI */ public class GreeterImplBase { public String greetMe(String me) { return "Hello " + me; } public String sayHi() { return "Bonjour"; } public void greetMeOneWay(String requestType) { System.out.println("********* greetMeOneWay: " + requestType); } public void pingMe() throws PingMeFault { } public Future<?> greetMeAsync(String requestType, AsyncHandler<GreetMeResponse> asyncHandler) { return null; /*not called */ } public Response<GreetMeResponse> greetMeAsync(String requestType) { return null; /*not called */ } public Future<?> sayHiAsync(AsyncHandler<SayHiResponse> asyncHandler) { return null; /*not called */ } public Response<SayHiResponse> sayHiAsync() { return null; /*not called */ } public Response<PingMeResponse> pingMeAsync() { return null; } public Future<?> pingMeAsync(AsyncHandler<PingMeResponse> asyncHandler) { return null; } }
10
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/no_body_parts/NoBodyPartsImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.no_body_parts; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import jakarta.jws.WebService; import jakarta.xml.ws.Holder; import jakarta.xml.ws.WebServiceException; import org.apache.cxf.no_body_parts.types.Operation1; import org.apache.cxf.no_body_parts.types.Operation1Response; import org.apache.cxf.no_body_parts.wsdl.NoBodyPartsSEI; /** * Implementation class for NoBodyParts */ @WebService(targetNamespace = "urn:org:apache:cxf:no_body_parts/wsdl") public class NoBodyPartsImpl implements NoBodyPartsSEI { private String digest(byte[] bytes) throws NoSuchAlgorithmException { MessageDigest algorithm = MessageDigest.getInstance("SHA-256"); algorithm.reset(); algorithm.update(bytes); byte[] messageDigest = algorithm.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } /** {@inheritDoc} */ public Operation1Response operation1(Operation1 parameters, Holder<byte[]> mimeAttachment) { Operation1Response r = new Operation1Response(); try { r.setStatus(digest(mimeAttachment.value)); } catch (NoSuchAlgorithmException e) { throw new WebServiceException(e); } return r; } }
11
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/handler/TrivialSOAPHandler.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.handler; import java.util.Set; import javax.xml.namespace.QName; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.annotation.Resource; import jakarta.xml.ws.handler.MessageContext; import jakarta.xml.ws.handler.soap.SOAPHandler; import jakarta.xml.ws.handler.soap.SOAPMessageContext; public class TrivialSOAPHandler implements SOAPHandler<SOAPMessageContext> { @Resource(name = "greeting") private String greeting; public TrivialSOAPHandler() { System.out.println(this + " Construct"); } @PostConstruct public void init() { System.out.println(this + " PostConstruct"); } @PreDestroy public void destroy() { System.out.println(this + " PreDestroy"); } public boolean handleMessage(SOAPMessageContext smc) { System.out.println(this + " handleMessage(): " + greeting); return true; } public boolean handleFault(SOAPMessageContext smc) { System.out.println(this + " handleFault()"); return true; } public void close(MessageContext messageContext) { System.out.println(this + " close()"); } public Set<QName> getHeaders() { return null; } }
12
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/recorders/OutMessageRecorder.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.recorders; import java.io.OutputStream; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Logger; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.interceptor.MessageSenderInterceptor; import org.apache.cxf.io.CachedOutputStream; import org.apache.cxf.io.CachedOutputStreamCallback; import org.apache.cxf.io.WriteOnCloseOutputStream; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; public class OutMessageRecorder extends AbstractPhaseInterceptor<Message> { private static final Logger LOG = LogUtils.getLogger(OutMessageRecorder.class); private final List<byte[]> outbound = new CopyOnWriteArrayList<>(); public OutMessageRecorder() { super(Phase.PREPARE_SEND); addAfter(MessageSenderInterceptor.class.getName()); } public void handleMessage(Message message) throws Fault { OutputStream os = message.getContent(OutputStream.class); if (null == os) { return; } WriteOnCloseOutputStream stream = createCachedStream(message, os); stream.registerCallback(new RecorderCallback()); } public static WriteOnCloseOutputStream createCachedStream(Message message, OutputStream os) { // We need to ensure that we have an output stream which won't start writing the // message until we have a chance to send a createsequence if (!(os instanceof WriteOnCloseOutputStream)) { WriteOnCloseOutputStream cached = new WriteOnCloseOutputStream(os); message.setContent(OutputStream.class, cached); os = cached; } return (WriteOnCloseOutputStream) os; } public List<byte[]> getOutboundMessages() { return outbound; } class RecorderCallback implements CachedOutputStreamCallback { public void onFlush(CachedOutputStream cos) { } public void onClose(CachedOutputStream cos) { // bytes were already copied after flush try { outbound.add(cos.getBytes()); } catch (Exception e) { LOG.fine("Can't record message from output stream class: " + cos.getOut().getClass().getName()); } } } }
13
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/recorders/InMessageRecorder.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.recorders; import java.io.InputStream; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.helpers.IOUtils; import org.apache.cxf.helpers.LoadingByteArrayOutputStream; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; public class InMessageRecorder extends AbstractPhaseInterceptor<Message> { private static final Logger LOG = LogUtils.getLogger(InMessageRecorder.class); private final List<byte[]> inbound = new CopyOnWriteArrayList<>(); public InMessageRecorder() { super(Phase.RECEIVE); } public void handleMessage(Message message) throws Fault { try (InputStream is = message.getContent(InputStream.class)) { if (is != null) { int i = is.available(); if (i < 4096) { i = 4096; } LoadingByteArrayOutputStream bout = new LoadingByteArrayOutputStream(i); IOUtils.copy(is, bout); is.close(); inbound.add(bout.toByteArray()); if (LOG.isLoggable(Level.FINE)) { LOG.fine("inbound: " + new String(bout.toByteArray())); } message.setContent(InputStream.class, bout.createInputStream()); } } catch (Exception ex) { throw new Fault(ex); } } public List<byte[]> getInboundMessages() { return inbound; } }
14
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/recorders/MessageRecorder.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.recorders; import java.util.List; import static org.junit.Assert.assertEquals; public class MessageRecorder { private OutMessageRecorder outRecorder; private InMessageRecorder inRecorder; public MessageRecorder(OutMessageRecorder or, InMessageRecorder ir) { inRecorder = ir; outRecorder = or; } public void awaitMessages(int nExpectedOut, int nExpectedIn, int timeout) { int waited = 0; int nOut = 0; int nIn = 0; while (waited <= timeout) { nOut = outRecorder.getOutboundMessages().size(); nIn = inRecorder.getInboundMessages().size(); if (nIn >= nExpectedIn && nOut >= nExpectedOut) { return; } try { Thread.sleep(100L); } catch (InterruptedException ex) { // ignore } waited += 100; } if (nExpectedIn != nIn) { System.out.println((nExpectedIn < nIn ? "excess" : "shortfall") + " of " + Math.abs(nExpectedIn - nIn) + " incoming messages"); System.out.println("\nMessages actually received:\n"); List<byte[]> inbound = inRecorder.getInboundMessages(); for (byte[] b : inbound) { System.out.println(new String(b)); System.out.println("----------------"); } } if (nExpectedOut != nOut) { System.out.println((nExpectedOut < nOut ? "excess" : "shortfall") + " of " + Math.abs(nExpectedOut - nOut) + " outgoing messages"); System.out.println("\nMessages actually sent:\n"); List<byte[]> outbound = outRecorder.getOutboundMessages(); for (byte[] b : outbound) { System.out.println(new String(b)); System.out.println("----------------"); } } assertEquals("Did not receive expected number of inbound messages", nExpectedIn, nIn); assertEquals("Did not send expected number of outbound messages", nExpectedOut, nOut); } }
15
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/ServerLauncher.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import org.apache.commons.lang3.tuple.Pair; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.util.StringUtils; public class ServerLauncher { public static final long DEFAULT_TIMEOUT = TimeUnit.MINUTES.toMillis(1L); protected static final String SERVER_FAILED = "server startup failed (not a log message)"; private static final boolean DEFAULT_IN_PROCESS = false; private static final Logger LOG = LogUtils.getLogger(ServerLauncher.class); private static final boolean DEBUG = false; private static final String JAVA_EXE = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; boolean serverPassed; final String className; private boolean inProcess = DEFAULT_IN_PROCESS; private AbstractTestServerBase inProcessServer; private Process process; private boolean serverIsReady; private boolean serverIsStopped; private boolean serverLaunchFailed; private Map<String, String> properties; private String[] serverArgs; private final Mutex mutex = new Mutex(); public ServerLauncher(String theClassName) { this(theClassName, DEFAULT_IN_PROCESS); } public ServerLauncher(AbstractTestServerBase b) { inProcess = true; inProcessServer = b; className = null; } public ServerLauncher(String theClassName, boolean inprocess) { inProcess = inprocess; className = theClassName; } public ServerLauncher(String theClassName, Map<String, String> p, String[] args) { this(theClassName, p, args, false); } public ServerLauncher(String theClassName, Map<String, String> p, String[] args, boolean inprocess) { className = theClassName; properties = p; serverArgs = args; inProcess = inprocess; } private boolean waitForServerToStop() { synchronized (mutex) { TimeoutCounter tc = new TimeoutCounter(DEFAULT_TIMEOUT); while (!serverIsStopped) { try { mutex.wait(1000L); if (tc.isTimeoutExpired()) { System.out.println("destroying server process"); process.destroy(); break; } } catch (InterruptedException ex) { //ex.printStackTrace(); } } if (!inProcess) { //wait for process to end... tc = new TimeoutCounter(DEFAULT_TIMEOUT); while (!tc.isTimeoutExpired()) { try { process.exitValue(); break; } catch (IllegalThreadStateException ex) { //ignore, process hasn't ended try { mutex.wait(1000L); } catch (InterruptedException ex1) { //ignore } } } if (tc.isTimeoutExpired()) { process.destroy(); } } } return serverIsStopped; } public void signalStop() throws IOException { if (process != null) { process.getOutputStream().write('q'); process.getOutputStream().write('\n'); process.getOutputStream().flush(); } } public boolean stopServer() throws IOException { if (inProcess) { try { return inProcessServer.stopInProcess(); } catch (Exception ex) { ex.printStackTrace(); throw new IOException(ex.getMessage()); } } if (process != null) { if (!serverIsStopped) { try { signalStop(); } catch (IOException ex) { //ignore } } waitForServerToStop(); process.destroy(); } return serverPassed; } public boolean launchServer() throws IOException { serverIsReady = false; serverLaunchFailed = false; if (inProcess) { Class<?> cls; Map<String, String> old = new HashMap<>(); try { if (null != properties) { for (Map.Entry<String, String> entry : properties.entrySet()) { old.put(entry.getKey(), System.getProperty(entry.getKey())); if (entry.getValue() == null) { System.clearProperty(entry.getKey()); } else { System.setProperty(entry.getKey(), entry.getValue()); } } } if (inProcessServer == null) { cls = Class.forName(className); Class<? extends AbstractTestServerBase> svcls = cls.asSubclass(AbstractTestServerBase.class); if (null == serverArgs) { inProcessServer = svcls.getDeclaredConstructor().newInstance(); } else { Constructor<? extends AbstractTestServerBase> ctor = svcls.getConstructor(serverArgs.getClass()); inProcessServer = ctor.newInstance(new Object[] {serverArgs}); } } inProcessServer.startInProcess(); serverIsReady = true; } catch (Throwable ex) { ex.printStackTrace(); serverLaunchFailed = true; } finally { for (Map.Entry<String, String> entry : old.entrySet()) { if (entry.getValue() == null) { System.clearProperty(entry.getKey()); } else { System.setProperty(entry.getKey(), entry.getValue()); } } } } else { Pair<Map<String, String>, List<String>> commandAndEnvironment = getCommandAndEnvironment(); List<String> cmd = commandAndEnvironment.getRight(); LOG.fine("CMD: " + cmd); if (DEBUG) { System.err.print("CMD: " + cmd); } ProcessBuilder pb = new ProcessBuilder(cmd); pb.environment().putAll(commandAndEnvironment.getLeft()); pb.redirectErrorStream(true); process = pb.start(); OutputMonitorThread out = new OutputMonitorThread(process.getInputStream()); out.start(); synchronized (mutex) { TimeoutCounter tc = new TimeoutCounter(DEFAULT_TIMEOUT); while (!(serverIsReady || serverLaunchFailed)) { try { mutex.wait(1000L); if (tc.isTimeoutExpired()) { break; } } catch (InterruptedException e) { e.printStackTrace(); } } } if (serverLaunchFailed || !serverIsReady) { System.err.println(out.getServerOutput()); } } return serverIsReady && !serverLaunchFailed; } public int waitForServer() { int ret = -1; try { process.waitFor(); ret = process.exitValue(); } catch (InterruptedException e) { e.printStackTrace(); } return ret; } private class OutputMonitorThread extends Thread { InputStream in; StringBuilder serverOutputAll = new StringBuilder(); OutputMonitorThread(InputStream i) { in = i; } public String getServerOutput() { return serverOutputAll.toString(); } public void run() { String outputDir = System.getProperty("server.output.dir", "target/surefire-reports/"); OutputStream os = null; try { Path logFile = Paths.get(outputDir + className + ".out"); Files.createDirectories(logFile.getParent()); os = Files.newOutputStream(logFile); } catch (IOException ex) { if (!ex.getMessage().contains("Stream closed")) { ex.printStackTrace(); } } try (PrintStream ps = new PrintStream(os)) { StringBuilder serverOutput = new StringBuilder(); for (int ch = in.read(); ch != -1; ch = in.read()) { serverOutput.append((char)ch); if (ch == '\n') { final String line = serverOutput.toString(); serverOutput.setLength(0); serverOutputAll.append(line); if (DEBUG) { System.err.print(line); } if (line.contains("server ready")) { notifyServerIsReady(); } else if (line.contains("server passed")) { serverPassed = true; } else if (line.contains("server stopped")) { notifyServerIsStopped(); } else if (line.contains(SERVER_FAILED)) { notifyServerFailed(); } ps.print(line); if (serverOutputAll.length() > 64000) { serverOutputAll.delete(0, 10000); } } } } catch (IOException ex) { if (!ex.getMessage().contains("Stream closed")) { ex.printStackTrace(); } } } } void notifyServerIsReady() { synchronized (mutex) { serverIsReady = true; mutex.notifyAll(); } } void notifyServerIsStopped() { synchronized (mutex) { LOG.info("notify server stopped"); serverIsStopped = true; mutex.notifyAll(); } } void notifyServerFailed() { synchronized (mutex) { serverIsStopped = true; serverLaunchFailed = true; mutex.notifyAll(); } } private Pair<Map<String, String>, List<String>> getCommandAndEnvironment() { Map<String, String> env = new HashMap<>(); List<String> cmd = new ArrayList<>(); cmd.add(JAVA_EXE); if (null != properties) { for (Map.Entry<String, String> entry : properties.entrySet()) { cmd.add("-D" + entry.getKey() + "=" + entry.getValue()); } } // expose only running server ports String simpleName = className.substring(className.lastIndexOf('.') + 1); int idx = simpleName.indexOf('$'); if (-1 != idx) { simpleName = simpleName.substring(0, idx); } for (Map.Entry<Object, Object> entry : TestUtil.getAllPorts().entrySet()) { final String key = entry.getKey().toString(); if (key.contains(simpleName)) { cmd.add("-D" + key + "=" + entry.getValue()); } } String vmargs = System.getProperty("server.launcher.vmargs"); if (StringUtils.isEmpty(vmargs)) { cmd.add("-ea"); } else { vmargs = vmargs.trim(); idx = vmargs.indexOf(' '); while (idx != -1) { cmd.add(vmargs.substring(0, idx)); vmargs = vmargs.substring(idx + 1); idx = vmargs.indexOf(' '); } cmd.add(vmargs); } String portClose = System.getProperty("org.apache.cxf.transports.http_jetty.DontClosePort"); if (portClose != null) { cmd.add("-Dorg.apache.cxf.transports.http_jetty.DontClosePort=" + portClose); } String loggingPropertiesFile = System.getProperty("java.util.logging.config.file"); if (null != loggingPropertiesFile) { cmd.add("-Djava.util.logging.config.file=" + loggingPropertiesFile); } StringBuilder classpath = new StringBuilder(System.getProperty("java.class.path")); if (classpath.indexOf("/.compatibility/") != -1) { classpath.append(':'); //on OSX, the compatibility lib brclasspath.indexOf("/.compatibility/") idx = classpath.indexOf("/.compatibility/"); int idx1 = classpath.lastIndexOf(":", idx); int idx2 = classpath.indexOf(":", idx); classpath.replace(idx1, idx2, ":"); } boolean isWindows = System.getProperty("os.name").startsWith("Windows"); if (!isWindows) { cmd.add("-classpath"); cmd.add(classpath.toString()); } else { // Overcoming "CreateProcess error=206, The filename or extension is too long" env.putIfAbsent("CLASSPATH", classpath.toString()); } // If the client set the transformer factory property, // we want the server to also set that property. String transformerProperty = System.getProperty("javax.xml.transform.TransformerFactory"); if (null != transformerProperty) { cmd.add("-Djavax.xml.transform.TransformerFactory=" + transformerProperty); } String validationMode = System.getProperty("spring.validation.mode"); if (null != validationMode) { cmd.add("-Dspring.validation.mode=" + validationMode); } String derbyHome = System.getProperty("derby.system.home"); if (null != derbyHome) { cmd.add("-Dderby.system.home=" + derbyHome); } String tmp = System.getProperty("java.io.tmpdir"); if (null != tmp) { cmd.add("-Djava.io.tmpdir=" + tmp); } cmd.add(className); if (null != serverArgs) { for (String s : serverArgs) { cmd.add(s); } } return Pair.of(env, cmd); } static class Mutex { // empty } static class TimeoutCounter { private final long expectedEndTime; TimeoutCounter(long theExpectedTimeout) { expectedEndTime = System.currentTimeMillis() + theExpectedTimeout; } public boolean isTimeoutExpired() { return System.currentTimeMillis() > expectedEndTime; } } }
16
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/AbstractBusClientServerTestBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.bus.spring.SpringBusFactory; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertTrue; public abstract class AbstractBusClientServerTestBase extends AbstractClientServerTestBase { protected static Bus staticBus; protected Bus bus; public void createBus(String config) throws Exception { if (config != null) { bus = new SpringBusFactory().createBus(config); } else { bus = BusFactory.newInstance().createBus(); } BusFactory.setDefaultBus(bus); } public void createBus() throws Exception { createBus(null); } public static Bus getStaticBus() { return staticBus; } public static Bus createStaticBus(String config) { if (config != null) { staticBus = new SpringBusFactory().createBus(config); } else { staticBus = BusFactory.newInstance().createBus(); } BusFactory.setDefaultBus(staticBus); return staticBus; } public static Bus createStaticBus() { return createStaticBus(null); } @After public void deleteBus() throws Exception { if (null != bus) { bus.shutdown(true); bus = null; } } @AfterClass public static void deleteStaticBus() throws Exception { if (null != staticBus) { staticBus.shutdown(true); staticBus = null; } } protected Bus getBus() { if (bus == null) { return staticBus; } return bus; } protected void setBus(Bus b) { bus = b; } protected HttpURLConnection getHttpConnection(String target) throws Exception { URL url = new URL(target); URLConnection connection = url.openConnection(); assertTrue(connection instanceof HttpURLConnection); return (HttpURLConnection)connection; } protected boolean runClient(Runnable clientImpl, long timeOut, TimeUnit timeUnit) throws InterruptedException { FutureTask<?> client = new FutureTask<>(clientImpl, null); ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 10000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); tpe.execute(client); tpe.shutdown(); tpe.awaitTermination(timeOut, timeUnit); return client.isDone(); } }
17
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/AbstractClientServerTestBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.LogManager; import org.junit.AfterClass; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public abstract class AbstractClientServerTestBase { private static List<ServerLauncher> launchers = new ArrayList<>(); private static boolean firstLaunch = true; private static synchronized void checkFirstLaunch(Class<?> cls) { if (firstLaunch) { firstLaunch = false; //make sure we use the logging.properties file for the test class //mvn will pass the system property, but Eclipse or other IDE //may not so lets just grab the file and make sure we use it //so that we use the same logging setup as mvn on the command //line so things like the logging interceptors on the chain //will match and not have additional side effects compared //to the command line String jdkl = System.getProperty("java.util.logging.config.file"); if (jdkl == null) { InputStream in = cls.getResourceAsStream("/logging.properties"); if (in != null) { try { LogManager.getLogManager().readConfiguration(in); } catch (SecurityException | IOException e) { //ignore } } } } } @AfterClass public static void stopAllServers() throws Exception { boolean passed = true; for (ServerLauncher sl : launchers) { try { sl.signalStop(); } catch (IOException ex) { ex.printStackTrace(); } } for (ServerLauncher sl : launchers) { try { passed = passed && sl.stopServer(); } catch (IOException ex) { ex.printStackTrace(); } } launchers.clear(); System.gc(); assertTrue("server failed", passed); } /** * Starts the server inProcess */ public static boolean launchServer(AbstractTestServerBase base) { boolean ok = false; try { checkFirstLaunch(base.getClass()); ServerLauncher sl = new ServerLauncher(base); ok = sl.launchServer(); assertTrue("server failed to launch", ok); launchers.add(0, sl); } catch (IOException ex) { ex.printStackTrace(); fail("failed to launch server " + base); } return ok; } /** * Starts the server inProcess */ public static boolean launchServer(Class<?> clz) { return launchServer(clz, true); } /** * Starts the server inProcess or out of process depending on the param */ public static boolean launchServer(Class<?> clz, boolean inProcess) { boolean ok = false; try { checkFirstLaunch(clz); ServerLauncher sl = new ServerLauncher(clz.getName(), inProcess); ok = sl.launchServer(); assertTrue("server failed to launch", ok); launchers.add(0, sl); } catch (IOException ex) { ex.printStackTrace(); fail("failed to launch server " + clz); } return ok; } /** * Starts the server inProcess */ public static boolean launchServer(Class<?> clz, Map<String, String> props, String[] args) { return launchServer(clz, props, args, true); } /** * Starts the server inProcess or out of process depending on the param */ public static boolean launchServer(Class<?> clz, Map<String, String> props, String[] args, boolean inProcess) { boolean ok = false; try { checkFirstLaunch(clz); ServerLauncher sl = new ServerLauncher(clz.getName(), props, args, inProcess); ok = sl.launchServer(); assertTrue("server failed to launch", ok); launchers.add(0, sl); } catch (IOException ex) { ex.printStackTrace(); fail("failed to launch server " + clz); } return ok; } protected void setAddress(Object o, String address) { TestUtil.setAddress(o, address); } protected void updateAddressPort(Object o, String port) throws NumberFormatException, MalformedURLException { TestUtil.updateAddressPort(o, port); } protected static String allocatePort(String s) { return TestUtil.getPortNumber(s); } protected static String allocatePort(Class<?> cls) { checkFirstLaunch(cls); return TestUtil.getPortNumber(cls); } protected static String allocatePort(Class<?> cls, int count) { checkFirstLaunch(cls); return TestUtil.getPortNumber(cls, count); } }
18
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/AbstractServerTestServerBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.endpoint.Server; public abstract class AbstractServerTestServerBase extends AbstractTestServerBase { private Bus b; private Server server; @Override protected final void run() throws Exception { b = BusFactory.getDefaultBus(); server = createServer(b); BusFactory.setDefaultBus(null); BusFactory.setThreadDefaultBus(null); } protected abstract Server createServer(Bus bus) throws Exception; @Override public void tearDown() throws Exception { server.stop(); server.destroy(); server = null; b.shutdown(true); b = null; } }
19
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/EmbeddedJMSBrokerLauncher.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import java.lang.reflect.Field; import java.net.URL; import java.util.List; import java.util.Map; import javax.wsdl.Definition; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.extensions.soap.SOAPAddress; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.common.util.ReflectionUtil; import org.apache.cxf.wsdl.WSDLManager; public class EmbeddedJMSBrokerLauncher extends AbstractBusTestServerBase { public static final String PORT = allocatePort(EmbeddedJMSBrokerLauncher.class); EmbeddedActiveMQ broker; String brokerName; private final String brokerUrl1; public EmbeddedJMSBrokerLauncher() { this(null); } public EmbeddedJMSBrokerLauncher(String url) { brokerUrl1 = url != null ? url : "tcp://localhost:" + PORT; } public void setBrokerName(String s) { brokerName = s; } public String getBrokerURL() { return brokerUrl1; } public String getEncodedBrokerURL() { return brokerUrl1.replace("?", "%3F"); } public void updateWsdl(Bus b, URL wsdlLocation) { updateWsdl(b, wsdlLocation.toString()); } public void updateWsdl(Bus b, String wsdlLocation) { updateWsdlExtensors(b, wsdlLocation, brokerUrl1, getEncodedBrokerURL()); } public static void updateWsdlExtensors(Bus bus, String wsdlLocation) { updateWsdlExtensors(bus, wsdlLocation, "tcp://localhost:" + PORT, null); } public static void updateWsdlExtensors(Bus bus, String wsdlLocation, String url, String encodedUrl) { try { if (encodedUrl == null) { encodedUrl = url; } if (bus == null) { bus = BusFactory.getThreadDefaultBus(); } Definition def = bus.getExtension(WSDLManager.class) .getDefinition(wsdlLocation); Map<?, ?> map = def.getAllServices(); for (Object o : map.values()) { Service service = (Service)o; Map<?, ?> ports = service.getPorts(); adjustExtensibilityElements(service.getExtensibilityElements(), url, encodedUrl); for (Object p : ports.values()) { Port port = (Port)p; adjustExtensibilityElements(port.getExtensibilityElements(), url, encodedUrl); adjustExtensibilityElements(port.getBinding().getExtensibilityElements(), url, encodedUrl); } } } catch (Exception e) { e.printStackTrace(); } } private static void adjustExtensibilityElements(List<?> l, String url, String encodedUrl) { for (Object e : l) { if (e instanceof SOAPAddress) { String add = ((SOAPAddress)e).getLocationURI(); int idx = add.indexOf("jndiURL="); if (idx != -1) { int idx2 = add.indexOf('&', idx); add = add.substring(0, idx) + "jndiURL=" + encodedUrl + (idx2 == -1 ? "" : add.substring(idx2)); ((SOAPAddress)e).setLocationURI(add); } } else if (e.getClass().getSimpleName().startsWith("JndiURLType")) { try { e.getClass().getMethod("setValue", String.class).invoke(e, url); } catch (Exception ex) { //ignore } } else { try { Field f = e.getClass().getDeclaredField("jmsNamingProperty"); ReflectionUtil.setAccessible(f); List<?> props = (List<?>)f.get(e); for (Object prop : props) { f = prop.getClass().getDeclaredField("name"); ReflectionUtil.setAccessible(f); if ("java.naming.provider.url".equals(f.get(prop))) { f = prop.getClass().getDeclaredField("value"); ReflectionUtil.setAccessible(f); String value = (String)f.get(prop); if (value == null || !value.startsWith("classpath")) { f.set(prop, url); } } } } catch (Exception ex) { //ignore } } } } public void stop() throws Exception { tearDown(); } public void tearDown() throws Exception { if (broker != null) { broker.stop(); } } //START SNIPPET: broker public final void run() throws Exception { final Configuration config = new ConfigurationImpl() .setSecurityEnabled(false) .setPersistenceEnabled(false) .setJMXManagementEnabled(false) .addAcceptorConfiguration("def", brokerUrl1); if (brokerName != null) { config.setName(brokerName); } broker = new EmbeddedActiveMQ(); broker.setConfiguration(config); broker.start(); } //END SNIPPET: broker public static void main(String[] args) throws Exception { try { String url = null; if (args.length > 0) { url = args[0]; } EmbeddedJMSBrokerLauncher s = new EmbeddedJMSBrokerLauncher(url); s.start(); } finally { System.out.println("done!"); } } }
20
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/AbstractTestServerBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import java.util.logging.Logger; import org.apache.cxf.common.logging.LogUtils; public abstract class AbstractTestServerBase { boolean inProcess; /** * method implemented by test servers. Initialise * servants and publish endpoints etc. * */ protected abstract void run() throws Exception; protected Logger getLog() { return LogUtils.getLogger(this.getClass()); } public void startInProcess() throws Exception { inProcess = true; //System.out.println("running server in-process"); run(); //System.out.println("signal ready"); ready(); } public boolean stopInProcess() throws Exception { boolean ret = true; tearDown(); if (verify(getLog())) { if (!inProcess) { System.out.println("server passed"); } } else { ret = false; } return ret; } public void start() throws Exception { try { System.out.println("running server"); run(); System.out.println("signal ready"); ready(); // wait for a key press then shut // down the server // System.in.read(); System.out.println("stopping bus"); tearDown(); } catch (Throwable ex) { startFailed(); throw ex; } finally { if (verify(getLog())) { System.out.println("server passed"); } else { System.out.println(ServerLauncher.SERVER_FAILED); } System.out.println("server stopped"); } } public void setUp() throws Exception { // emtpy } public void tearDown() throws Exception { // empty } protected void ready() { if (!inProcess) { System.out.println("server ready"); } } protected void startFailed() { System.out.println(ServerLauncher.SERVER_FAILED); } /** * Used to facilitate assertions on server-side behaviour. * * @param log logger to use for diagnostics if assertions fail * @return true if assertions hold */ protected boolean verify(Logger log) { return true; } protected static int allocatePortAsInt(Class<?> cls) { return Integer.parseInt(TestUtil.getPortNumber(cls)); } protected static String allocatePort(Class<?> cls) { return TestUtil.getPortNumber(cls); } protected static String allocatePort(Class<?> cls, int i) { return TestUtil.getPortNumber(cls, i); } }
21
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/TestUtil.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.Properties; import java.util.Random; import java.util.logging.Logger; import jakarta.xml.ws.BindingProvider; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.util.ReflectionUtil; import org.apache.cxf.endpoint.Client; public final class TestUtil { private static final Logger LOG = LogUtils.getL7dLogger(TestUtil.class); private static int portNum = -1; private static Properties ports = new Properties(); @SuppressWarnings("unused") private static ServerSocket lock; static { int pn = 9000; if (Boolean.getBoolean("cxf.useRandomFirstPort")) { pn += new Random().nextInt(500) * 100; } while (portNum == -1) { try { //we'll hold a socket open and allocate ports up from that socket. //if a second CXF build process (like running parallel builds) //tries to open the socket, it will throw an exception and it //will try again 100 ports up. At this point, 100 ports is WAY //more than enough. We can adjust later if needed. ServerSocket sock = new ServerSocket(pn); lock = sock; portNum = pn + 1; } catch (IOException ex) { pn += 100; } } } private TestUtil() { //Complete } // Deletes all files and subdirectories under dir. // Returns true if all deletions were successful. // If a deletion fails, the method stops attempting to delete and returns false. public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); if (children != null) { for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } } // The directory is now empty so delete it return dir.delete(); } public static String getClassPath(ClassLoader loader) throws URISyntaxException { StringBuilder classPath = new StringBuilder(); if (loader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader)loader; for (URL url : urlLoader.getURLs()) { String file = url.getFile(); if (file.indexOf("junit") == -1) { classPath.append(url.toURI().getPort()); classPath.append(System.getProperty("path.separator")); } } } return classPath.toString(); } public static Method getMethod(Class<?> clazz, String methodName) { Method[] declMethods = clazz.getDeclaredMethods(); for (Method method : declMethods) { if (method.getName().equals(methodName)) { return method; } } return null; } public static Properties getAllPorts() { return ports; } public static String getPortNumber(Class<?> cls) { return getPortNumber(cls.getName(), cls.getSimpleName()); } public static String getPortNumber(Class<?> cls, int count) { return getPortNumber(cls.getName() + "." + count, cls.getSimpleName() + "." + count); } public static String getPortNumber(String name) { return getPortNumber(name, name); } public static String getNewPortNumber(Class<?> cls) { return getNewPortNumber(cls.getName(), cls.getSimpleName()); } public static String getNewPortNumber(Class<?> cls, int count) { return getNewPortNumber(cls.getName() + "." + count, cls.getSimpleName() + "." + count); } public static String getNewPortNumber(String name) { return getNewPortNumber(name, name); } private static void applyNames(String fullName, String simpleName, String p) { ports.setProperty("testutil.ports." + fullName, p); ports.setProperty("testutil.ports." + simpleName, p); System.setProperty("testutil.ports." + fullName, p); System.setProperty("testutil.ports." + simpleName, p); if (fullName.endsWith("." + simpleName)) { int idx = fullName.lastIndexOf('.', fullName.lastIndexOf('.')); while (idx != -1) { String name = fullName.substring(idx + 1); ports.setProperty("testutil.ports." + name, p); System.setProperty("testutil.ports." + name, p); idx = fullName.lastIndexOf('.', idx - 1); } } } private static void removeNames(String fullName, String simpleName) { ports.remove("testutil.ports." + fullName); ports.remove("testutil.ports." + simpleName); System.clearProperty("testutil.ports." + fullName); System.clearProperty("testutil.ports." + simpleName); if (fullName.endsWith("." + simpleName)) { int idx = fullName.lastIndexOf('.', fullName.lastIndexOf('.')); while (idx != -1) { String name = fullName.substring(idx + 1); ports.remove("testutil.ports." + name); System.clearProperty("testutil.ports." + name); idx = fullName.lastIndexOf('.', idx - 1); } } } public static String getNewPortNumber(String fullName, String simpleName) { removeNames(fullName, simpleName); return getPortNumber(fullName, simpleName); } public static String getPortNumber(String fullName, String simpleName) { String p = ports.getProperty("testutil.ports." + fullName); if (p == null) { p = System.getProperty("testutil.ports." + fullName); if (p != null) { ports.setProperty("testutil.ports." + fullName, p); ports.setProperty("testutil.ports." + simpleName, p); } } while (p == null) { int pn = portNum++; try (ServerSocket sock = new ServerSocket(pn)) { //make sure the port can be opened. Something MIGHT be running on it. p = Integer.toString(pn); LOG.fine("Setting port for " + fullName + " to " + p); } catch (IOException ex) { // } } applyNames(fullName, simpleName, p); return p; } public static void updateAddressPort(Object o, String port) throws NumberFormatException, MalformedURLException { updateAddressPort(o, Integer.parseInt(port)); } public static void updateAddressPort(Object o, int port) throws MalformedURLException { String address = null; if (o instanceof BindingProvider) { address = ((BindingProvider)o).getRequestContext() .get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString(); } else if (o instanceof Client) { Client c = (Client)o; address = c.getEndpoint().getEndpointInfo().getAddress(); } if (address != null && address.startsWith("http")) { // http and https are ok URL url = new URL(address); url = new URL(url.getProtocol(), url.getHost(), port, url.getFile()); setAddress(o, url.toString()); } //maybe simple frontend proxy? } // extra methods to help support the dynamic port allocations public static void setAddress(Object o, String address) { if (o instanceof BindingProvider) { ((BindingProvider)o).getRequestContext() .put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, address); } Client c = null; if (o instanceof Client) { c = (Client)o; } if (c == null) { try { InvocationHandler i = Proxy.getInvocationHandler(o); c = (Client)i.getClass().getMethod("getClient").invoke(i); } catch (Throwable t) { //ignore } } if (c == null) { try { final Method m = o.getClass().getDeclaredMethod("getClient"); ReflectionUtil.setAccessible(m); c = (Client)m.invoke(o); } catch (Throwable t) { //ignore } } if (c != null) { c.getEndpoint().getEndpointInfo().setAddress(address); } } }
22
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/testutil/common/AbstractBusTestServerBase.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.testutil.common; import org.apache.cxf.Bus; public abstract class AbstractBusTestServerBase extends AbstractTestServerBase { private Bus bus; public boolean stopInProcess() throws Exception { boolean ret = super.stopInProcess(); if (bus != null) { try { bus.shutdown(true); } catch (Throwable t) { //ignore, we're shutting down } } return ret; } public Bus getBus() { return bus; } public void setBus(Bus b) { bus = b; } }
23
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/Customer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer; import jakarta.xml.bind.annotation.XmlRootElement; // START SNIPPET: bean @XmlRootElement public class Customer { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // END SNIPPET: bean
24
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/CustomerNotFoundDetails.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "CustomerNotFoundDetails") public class CustomerNotFoundDetails { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } }
25
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/Customers.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer; import java.util.Collection; import jakarta.xml.bind.annotation.XmlRootElement; // START SNIPPET: bean @XmlRootElement public class Customers { private Collection<Customer> customers; public Collection<Customer> getCustomer() { return customers; } public void setCustomer(Collection<Customer> c) { this.customers = c; } } // END SNIPPET: bean
26
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/CustomerNotFoundFault.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer; import jakarta.xml.ws.WebFault; @WebFault public class CustomerNotFoundFault extends Exception { private static final long serialVersionUID = -2104569359859457879L; private CustomerNotFoundDetails details; public CustomerNotFoundFault(CustomerNotFoundDetails details) { super(); this.details = details; } public CustomerNotFoundDetails getFaultInfo() { return details; } }
27
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @jakarta.xml.bind.annotation.XmlSchema(namespace = "http://cxf.apache.org/jra", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.apache.cxf.customer;
28
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/bare/GetCustomer.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.bare; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; @XmlRootElement(name = "GetCustomer") @XmlType(name = "GetCustomer") public class GetCustomer { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } }
29
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/bare/GetCustomers.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.bare; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "GetCustomers") public class GetCustomers { }
30
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/bare/CustomerService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.bare; import java.util.HashMap; import java.util.Map; import jakarta.annotation.Resource; import jakarta.jws.WebMethod; import jakarta.jws.WebParam; import jakarta.jws.WebResult; import jakarta.jws.WebService; import jakarta.xml.ws.WebServiceContext; import jakarta.xml.ws.WebServiceException; import org.apache.cxf.customer.Customer; import org.apache.cxf.customer.CustomerNotFoundDetails; import org.apache.cxf.customer.CustomerNotFoundFault; import org.apache.cxf.customer.Customers; // END SNIPPET: service @WebService(targetNamespace = "http://cxf.apache.org/jra") public class CustomerService { long currentId = 1; Map<Long, Customer> customers = new HashMap<>(); @Resource private WebServiceContext context; public CustomerService() { Customer customer = createCustomer(); customers.put(customer.getId(), customer); } @WebMethod @WebResult(name = "customers") public Customers getCustomers(@WebParam(name = "GetCustomers") GetCustomers req) { Customers cbean = new Customers(); cbean.setCustomer(customers.values()); if (context == null || context.getMessageContext() == null) { throw new WebServiceException("WebServiceContext is null!"); } return cbean; } @WebMethod @WebResult(name = "customer") public Customer getCustomer(@WebParam(name = "getCustomer") GetCustomer getCustomer) throws CustomerNotFoundFault { Customer c = customers.get(getCustomer.getId()); if (c == null) { CustomerNotFoundDetails details = new CustomerNotFoundDetails(); details.setId(getCustomer.getId()); throw new CustomerNotFoundFault(details); } return c; } @WebMethod public String getSomeDetails(@WebParam(name = "getSomeDetails") GetCustomer getCustomer) throws CustomerNotFoundFault { return "some details"; } @WebMethod public void updateCustomer(@WebParam(name = "customer") Customer c) { customers.put(c.getId(), c); } @WebMethod public void addCustomer(@WebParam(name = "customer") Customer c) { long id = ++currentId; c.setId(id); customers.put(id, c); } @WebMethod public void deleteCustomer(long id) { customers.remove(id); } final Customer createCustomer() { Customer c = new Customer(); c.setName("Dan Diephouse"); c.setId(123); return c; } } // END SNIPPET: service
31
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/bare/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @jakarta.xml.bind.annotation.XmlSchema(namespace = "http://cxf.apache.org/jra", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.apache.cxf.customer.bare;
32
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/wraped/CustomerService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.wraped; import java.util.HashMap; import java.util.Map; import jakarta.jws.WebMethod; import jakarta.jws.WebParam; import jakarta.jws.WebResult; import jakarta.jws.WebService; import org.apache.cxf.customer.Customer; import org.apache.cxf.customer.Customers; // END SNIPPET: service @WebService(targetNamespace = "http://cxf.apache.org/jra") public class CustomerService { long currentId = 1; Map<Long, Customer> customers = new HashMap<>(); public CustomerService() { Customer customer = createCustomer(); customers.put(customer.getId(), customer); } @WebMethod @WebResult(name = "customers") public Customers getCustomers() { Customers cbean = new Customers(); cbean.setCustomer(customers.values()); return cbean; } @WebMethod @WebResult(name = "customer") public Customer getCustomer(@WebParam(name = "id") Long id) { return customers.get(id); } @WebMethod public void updateCustomer(@WebParam(name = "id") String id, @WebParam(name = "customer") Customer c) { customers.put(c.getId(), c); } @WebMethod public void addCustomer(@WebParam(name = "customer") Customer c) { long id = ++currentId; c.setId(id); customers.put(id, c); } @WebMethod public void deleteCustomer(String id) { customers.remove(Long.valueOf(id)); } final Customer createCustomer() { Customer c = new Customer(); c.setName("Dan Diephouse"); c.setId(123); return c; } } // END SNIPPET: service
33
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/wraped/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @jakarta.xml.bind.annotation.XmlSchema(namespace = "http://cxf.apache.org/jra", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.apache.cxf.customer.wraped;
34
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/GetAnotherBook.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; public class GetAnotherBook { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } }
35
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/BookNotFoundDetails.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class BookNotFoundDetails { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } }
36
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/Books.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Books { private Book[] books; public Book[] getBooks() { return books; } public void setBooks(Book[] b) { this.books = b; } }
37
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/BookServiceImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import java.util.HashMap; import java.util.Map; import jakarta.jws.WebService; @WebService(endpointInterface = "org.apache.cxf.customer.book.BookService") public class BookServiceImpl implements BookService { long currentId = 1; Map<Long, Book> books = new HashMap<>(); public BookServiceImpl() { Book book = createBook(); System.out.println("Enregistre Book de id " + book.getId()); books.put(book.getId(), book); } public Books getBooks() { for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("getBooks -> " + me.getKey() + " : " + me.getValue()); } Books b = new Books(); b.setBooks(books.values().toArray(new Book[books.size()])); return b; } public Book getBook(GetBook getBook) throws BookNotFoundFault { for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("getBook -> " + me.getKey() + " : " + me.getValue().getName() + ", " + me.getValue().getId()); } System.out.println("Book de id " + getBook.getId()); Book b = books.get(getBook.getId()); if (b == null) { BookNotFoundDetails details = new BookNotFoundDetails(); details.setId(getBook.getId()); throw new BookNotFoundFault(details); } return b; } public Book getAnotherBook(GetAnotherBook getAnotherBook) throws BookNotFoundFault { for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("getBook -> " + me.getKey() + " : " + me.getValue().getName() + ", " + me.getValue().getId()); } System.out.println("Book de id " + getAnotherBook.getId()); Book b = books.get(getAnotherBook.getId()); if (b == null) { BookNotFoundDetails details = new BookNotFoundDetails(); details.setId(getAnotherBook.getId()); throw new BookNotFoundFault(details); } return b; } public void updateBook(Book b) { books.put(b.getId(), b); for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("updateBook -> " + me.getKey() + " : " + me.getValue()); } } public long addBook(Book b) { long id = ++currentId; System.out.println("addBook : " + b.getName()); b.setId(id); books.put(id, b); for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("addBook -> " + me.getKey() + " : " + me.getValue().getName() + ", " + me.getValue().getId()); } return b.getId(); } public void deleteBook(long id) { books.remove(id); for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("deleteBook -> " + me.getKey() + " : " + me.getValue()); } } final Book createBook() { Book b = new Book(); b.setName("CXF in Action"); b.setId(123); return b; } }
38
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/BookServiceWrappedImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import java.util.HashMap; import java.util.Map; import jakarta.jws.WebService; @WebService(endpointInterface = "org.apache.cxf.customer.book.BookService") public class BookServiceWrappedImpl implements BookServiceWrapped { Map<Long, Book> books = new HashMap<>(); public BookServiceWrappedImpl() { Book book = createBook(); System.out.println("Register the Book's id " + book.getId()); books.put(book.getId(), book); } public Book getBook(long bookid) throws BookNotFoundFault { for (Map.Entry<Long, Book> me : books.entrySet()) { System.out.println("getBook -> " + me.getKey() + " : " + me.getValue().getName() + ", " + me.getValue().getId()); } System.out.println("The Book's id " + bookid); Book b = books.get(bookid); if (b == null) { BookNotFoundDetails details = new BookNotFoundDetails(); details.setId(bookid); throw new BookNotFoundFault(details); } return b; } final Book createBook() { Book b = new Book(); b.setName("CXF in Action"); b.setId(123); return b; } }
39
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/Book.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.xml.bind.annotation.XmlRootElement; // START SNIPPET: bean @XmlRootElement(name = "Book") public class Book { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // END SNIPPET: bean
40
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/BookNotFoundFault.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.xml.ws.WebFault; @WebFault public class BookNotFoundFault extends Exception { private static final long serialVersionUID = 497738666759033678L; private BookNotFoundDetails details; public BookNotFoundFault(BookNotFoundDetails details) { super(); this.details = details; } public BookNotFoundDetails getFaultInfo() { return details; } }
41
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/BookServiceWrapped.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.jws.WebParam; import jakarta.jws.WebResult; import jakarta.jws.WebService; @WebService(targetNamespace = "http://book.customer.cxf.apache.org/") public interface BookServiceWrapped { @WebResult(name = "Book") Book getBook(@WebParam(name = "id")long bookid) throws BookNotFoundFault; }
42
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/GetBook.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "GetBook") public class GetBook { private long id; public long getId() { return id; } public void setId(long id) { this.id = id; } }
43
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/package-info.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @jakarta.xml.bind.annotation.XmlSchema(namespace = "http://book.acme.com", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.apache.cxf.customer.book;
44
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/customer/book/BookService.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.customer.book; import jakarta.jws.WebParam; import jakarta.jws.WebResult; import jakarta.jws.WebService; @WebService(targetNamespace = "http://book.acme.com") public interface BookService { @WebResult(name = "Books") Books getBooks(); @WebResult(name = "Book") Book getBook(@WebParam(name = "GetBook") GetBook getBook) throws BookNotFoundFault; @WebResult(name = "Book") Book getAnotherBook(@WebParam(name = "GetAnotherBook") GetAnotherBook getAnotherBook) throws BookNotFoundFault; void updateBook(@WebParam(name = "Book") Book c); @WebResult(name = "book") long addBook(@WebParam(name = "Book") Book c); void deleteBook(@WebParam(name = "id") long id) throws BookNotFoundFault; }
45
0
Create_ds/cxf/testutils/src/main/java/org/apache/cxf
Create_ds/cxf/testutils/src/main/java/org/apache/cxf/ordered_param_holder/OrderedParamHolderImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.ordered_param_holder; import jakarta.jws.WebService; import jakarta.xml.ws.Holder; @WebService(serviceName = "ordered_param_holder", portName = "ordered_param_holderSOAP", targetNamespace = "http://cxf.apache.org/ordered_param_holder/", endpointInterface = "org.apache.cxf.ordered_param_holder.OrderedParamHolder", wsdlLocation = "testutils/ordered_param_holder.wsdl") public class OrderedParamHolderImpl implements OrderedParamHolder { public void orderedParamHolder(Holder<ComplexStruct> part3, Holder<Integer> part2, Holder<String> part1) { part2.value = Integer.valueOf(part2.value.intValue() + 1); part1.value = "return " + part1.value; part3.value.elem1 = "return " + part3.value.elem1; part3.value.elem2 = "return " + part3.value.elem2; part3.value.elem3++; } }
46
0
Create_ds/cxf/testutils/src/main/java/org/apache
Create_ds/cxf/testutils/src/main/java/org/apache/header_test/TestHeaderImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.header_test; import jakarta.jws.WebService; import jakarta.xml.ws.Holder; import org.apache.header_test.types.TestHeader1; import org.apache.header_test.types.TestHeader1Response; import org.apache.header_test.types.TestHeader2; import org.apache.header_test.types.TestHeader2Response; import org.apache.header_test.types.TestHeader3; import org.apache.header_test.types.TestHeader3Response; import org.apache.header_test.types.TestHeader5; import org.apache.header_test.types.TestHeader5ResponseBody; import org.apache.header_test.types.TestHeader6; import org.apache.header_test.types.TestHeader6Response; import org.apache.tests.type_test.all.SimpleAll; import org.apache.tests.type_test.choice.SimpleChoice; import org.apache.tests.type_test.sequence.SimpleStruct; @WebService(serviceName = "SOAPHeaderService", portName = "SoapHeaderPort", endpointInterface = "org.apache.header_test.TestHeader", targetNamespace = "http://apache.org/header_test", wsdlLocation = "testutils/soapheader.wsdl") public class TestHeaderImpl implements TestHeader { public TestHeader1Response testHeader1( TestHeader1 in, TestHeader1 inHeader) { if (in == null || inHeader == null) { throw new IllegalArgumentException("TestHeader1 part not found."); } TestHeader1Response returnVal = new TestHeader1Response(); returnVal.setResponseType(inHeader.getClass().getSimpleName()); return returnVal; } /** * * @param out * @param outHeader * @param in */ public void testHeader2( TestHeader2 in, Holder<TestHeader2Response> out, Holder<TestHeader2Response> outHeader) { TestHeader2Response outVal = new TestHeader2Response(); outVal.setResponseType(in.getRequestType()); out.value = outVal; TestHeader2Response outHeaderVal = new TestHeader2Response(); outHeaderVal.setResponseType(in.getRequestType()); outHeader.value = outHeaderVal; } public TestHeader3Response testHeader3( TestHeader3 in, Holder<TestHeader3> inoutHeader) { if (inoutHeader.value == null) { throw new IllegalArgumentException("TestHeader3 part not found."); } TestHeader3Response returnVal = new TestHeader3Response(); returnVal.setResponseType(inoutHeader.value.getRequestType()); inoutHeader.value.setRequestType(in.getRequestType()); return returnVal; } /** * * @param requestType */ public void testHeader4( String requestType) { } public void testHeader5(Holder<TestHeader5ResponseBody> out, Holder<TestHeader5> outHeader, org.apache.header_test.types.TestHeader5 in) { TestHeader5ResponseBody outVal = new TestHeader5ResponseBody(); outVal.setResponseType(1000); out.value = outVal; TestHeader5 outHeaderVal = new TestHeader5(); outHeaderVal.setRequestType(in.getRequestType()); outHeader.value = outHeaderVal; } public TestHeader6Response testHeaderPartBeforeBodyPart( Holder<TestHeader3> inoutHeader, TestHeader6 in) { if (inoutHeader.value == null) { throw new IllegalArgumentException("TestHeader3 part not found."); } TestHeader6Response returnVal = new TestHeader6Response(); returnVal.setResponseType(inoutHeader.value.getRequestType()); inoutHeader.value.setRequestType(in.getRequestType()); return returnVal; } public SimpleStruct sendReceiveAnyType(Holder<SimpleAll> x, SimpleChoice y) { SimpleAll sa = new SimpleAll(); sa.setVarString(y.getVarString()); SimpleStruct ss = new SimpleStruct(); ss.setVarAttrString(x.value.getVarAttrString() + "Ret"); ss.setVarInt(x.value.getVarInt() + 100); x.value = sa; return ss; } public String testHeader7() { return "Hello"; } }
47
0
Create_ds/cxf/testutils/src/main/java/org/apache/header_test
Create_ds/cxf/testutils/src/main/java/org/apache/header_test/rpc/TestRPCHeaderImpl.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.header_test.rpc; import jakarta.jws.WebService; import jakarta.xml.ws.Holder; import org.apache.header_test.rpc.types.HeaderMessage; @WebService(serviceName = "SOAPRPCHeaderService", portName = "SoapRPCHeaderPort", endpointInterface = "org.apache.header_test.rpc.TestRPCHeader", targetNamespace = "http://apache.org/header_test/rpc", wsdlLocation = "testutils/soapheader_rpc.wsdl") public class TestRPCHeaderImpl implements TestRPCHeader { public String testHeader1(HeaderMessage inHeader, String in) { if (in == null || inHeader == null) { throw new IllegalArgumentException("TestHeader1 part not found."); } return in + "/" + inHeader.getHeaderVal(); } public String testInOutHeader(String in, Holder<HeaderMessage> inOutHeader) { String tmp = inOutHeader.value.getHeaderVal(); inOutHeader.value.setHeaderVal(in); return tmp; } }
48
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/test/java/com/paypal/juno/employeedashboardapp/EmployeeDashboardAppApplicationTests.java
package com.paypal.juno.employeedashboardapp; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class EmployeeDashboardAppApplicationTests { @Test void contextLoads() { } }
49
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/EmployeeDashboardAppApplication.java
package com.paypal.juno.employeedashboardapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class EmployeeDashboardAppApplication { public static void main(String[] args) { SpringApplication.run(EmployeeDashboardAppApplication.class, args); } }
50
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/repository/EmployeeRepository.java
package com.paypal.juno.employeedashboardapp.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.paypal.juno.employeedashboardapp.model.Employee; public interface EmployeeRepository extends JpaRepository<Employee, Integer> { }
51
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/controller/EmployeeController.java
package com.paypal.juno.employeedashboardapp.controller; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import com.paypal.juno.employeedashboardapp.model.Employee; import com.paypal.juno.employeedashboardapp.service.EmployeeService; import com.paypal.juno.employeedashboardapp.service.JunoCache; @Controller public class EmployeeController { @Autowired private EmployeeService employeeService; private static String dbname = "mysql"; @Autowired private JunoCache juno; private static String cachename = "junodb"; public static java.util.Date parseDate(String date) { try { return new SimpleDateFormat("yyyy-MM-dd").parse(date); } catch (ParseException e) { return null; } } @GetMapping("/") public String viewHomePage(Model model) { long start = System.currentTimeMillis(); List<Employee> empList = employeeService.getAllEmployees(); model.addAttribute("listEmployees", empList); long end = System.currentTimeMillis(); long timetaken = end - start; model.addAttribute("timetaken", timetaken); Employee employee = new Employee(); model.addAttribute("employee", employee); model.addAttribute("datasource", dbname); return "index"; } @GetMapping("/showNewEmpForm") public String showAddEmployeeForm(Model model) { Employee employee = new Employee(); model.addAttribute("employee", employee); // juno.cacheRecord(employee); return "add_employee.html"; } @GetMapping("/searchEmp") public String searchPage(Model model, @ModelAttribute("searchedEmployee") Employee searchedEmp) { Employee employee = new Employee(); model.addAttribute("employee", employee); if (searchedEmp.getId() > 0) { model.addAttribute("searchedEmployee", searchedEmp); } else { model.addAttribute("searchedEmployee", null); } return "search"; } @PostMapping("/addEmp") public String addEmployee(Model model, @ModelAttribute("employee") Employee emp) { try { if (emp.getId() < 1){ throw new Exception("Employee Id should be positive non-zero number"); } else if (juno.getRecord(emp.getId()) != null) { throw new Exception( "Employee with id " + emp.getId() + " already exists. Data Source: JunoDB"); } else { employeeService.addEmployee(emp); juno.cacheRecord(emp); } } catch (Exception e) { model.addAttribute("addEmpStatus", e.getMessage()); return "add_employee.html"; } return "redirect:/"; } @PostMapping("/updEmp") public String updateEmployee(Model model, @ModelAttribute("employee") Employee emp) { try { boolean rc = juno.conditionalUpdate(emp); if(rc == true){ employeeService.saveEmployee(emp); }else{ throw new Exception( "Employee Record updated already"); } juno.cacheRecord(emp); } catch (Exception e) { model.addAttribute("updateEmpStatus", e.getMessage()); return "update_employee.html"; } return "redirect:/"; } @GetMapping("/findEmp") public String findEmployee(@ModelAttribute("employee") Employee emp, Model model) { if (emp.getId() > 0) { long start = System.currentTimeMillis(); Employee emp1 = juno.getRecord(emp.getId()); if (emp1 != null) { model.addAttribute("searchedEmployee", emp1); model.addAttribute("datasource", cachename); } else { emp1 = employeeService.findEmployee(emp.getId()); model.addAttribute("searchedEmployee", emp1); model.addAttribute("datasource", dbname); juno.cacheRecord(emp1); } long end = System.currentTimeMillis(); long timetaken = end - start; model.addAttribute("timetaken", timetaken); } return "search"; } @GetMapping("/updateEmp/{id}") public String showFormForUpdateEmployee(@PathVariable(value = "id") int id, Model model) { //Check if the Employee is already present in Cache Employee empLocal = juno.getRecord(id); if(empLocal == null){ // get the employee from Mysql DB Employee employee = employeeService.findEmployee(id); // Add employee to Cache juno.cacheRecord(employee); // Fetch the record from Juno empLocal = juno.getRecord(id); // set the employee as a model attribute to pre-populate the form model.addAttribute("employee", employee); }else{ // set the employee as a model attribute to pre-populate the form model.addAttribute("employee", empLocal); } return "update_employee.html"; } @GetMapping("/deleteEmp/{id}") public String deleteEmployee(@PathVariable(value = "id") int id, Model model) { employeeService.deleteEmployee(id); juno.destroyRecord(id); return "redirect:/"; } }
52
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/model/Employee.java
package com.paypal.juno.employeedashboardapp.model; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name = "employee") public class Employee implements Serializable { @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id",unique=true) private int id; @Column(name = "name") private String name; @Temporal(TemporalType.DATE) @DateTimeFormat(pattern = "yyyy-MM-dd") @Column(name = "dob") private Date dob; @Column(name = "address") private String address; @Column(name = "phone") private String phone; @Column(name = "email") private String email; @Column(name = "salary") private int salary; @Column(name = "location") private String location; @Column(name = "type") private String type; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public Date getDob() { return this.dob; } public void setDob(Date dob) { this.dob = dob; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public int getSalary() { return this.salary; } public void setSalary(int salary) { this.salary = salary; } public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public Employee() { } public Employee(String name, int id, Date dob, String address, String phone, String email, int salary, String location, String type) { this.name = name; this.id = id; this.address = address; this.phone = phone; this.email = email; this.salary = salary; this.location = location; this.type = type; } public static byte[] serializeObject(Employee emp) { ByteArrayOutputStream boas = new ByteArrayOutputStream(); try (ObjectOutputStream ois = new ObjectOutputStream(boas)) { ois.writeObject(emp); return boas.toByteArray(); } catch (IOException ioe) { ioe.printStackTrace(); } return null; } public static Employee deserializeObject(byte[] buff) { InputStream is = new ByteArrayInputStream(buff); try (ObjectInputStream ois = new ObjectInputStream(is)) { return (Employee) ois.readObject(); } catch (IOException | ClassNotFoundException ioe) { ioe.printStackTrace(); } return null; } }
53
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/service/JunoCache.java
package com.paypal.juno.employeedashboardapp.service; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.employeedashboardapp.model.Employee; import com.paypal.juno.exception.JunoException; import java.io.IOException; import java.net.URL; import java.util.Properties; import org.springframework.stereotype.Service; @Service public class JunoCache { private JunoClient junoClient; private RecordContext rctx; JunoCache() throws IOException { URL url = JunoCache.class.getResource("/application.properties"); Properties pConfig = new Properties(); pConfig.load(url.openStream()); junoClient = JunoClientFactory.newJunoClient(url); } public void clearRctx(){ rctx = null; } public boolean cacheRecord(Employee emp) { try { JunoResponse jr = junoClient.set((new Integer(emp.getId())).toString().getBytes(), Employee.serializeObject(emp)); if(jr.getStatus() == OperationStatus.Success || jr.getStatus() == OperationStatus.UniqueKeyViolation){ return true; }else { return false; } } catch (JunoException je) { return false; } catch (Exception e){ return false; } } public boolean createRecord(Employee emp) { try { JunoResponse jr = junoClient.create((new Integer(emp.getId())).toString().getBytes(), Employee.serializeObject(emp)); if(jr.getStatus() == OperationStatus.Success || jr.getStatus() == OperationStatus.UniqueKeyViolation){ return true; }else { return false; } } catch (JunoException je) { return false; } catch (Exception e){ return false; } } public boolean updateRecord(Employee emp) { try { JunoResponse jr = junoClient.update((new Integer(emp.getId())).toString().getBytes(), Employee.serializeObject(emp)); if(jr.getStatus() == OperationStatus.Success){ return true; }else { return false; } } catch (JunoException je) { return false; } catch (Exception e){ return false; } } public boolean conditionalUpdate(Employee emp) { try { JunoResponse jr = junoClient.compareAndSet(rctx, Employee.serializeObject(emp),100); if(jr.getStatus() == OperationStatus.Success){ return true; }else { return false; } } catch (JunoException je) { return false; } catch (Exception e){ return false; } } public Employee getRecord(int id) { try { JunoResponse jr = junoClient.get((new Integer(id)).toString().getBytes(),10); if(jr.getStatus() == OperationStatus.Success){ Employee emp = Employee.deserializeObject(jr.getValue()); rctx = jr.getRecordContext(); return emp; }else { return null; } } catch (JunoException je) { return null; } catch (Exception e){ return null; } } public boolean destroyRecord(int id) { try { JunoResponse jr = junoClient.delete((new Integer(id)).toString().getBytes()); if(jr.getStatus() == OperationStatus.Success){ return true; }else { return false; } } catch (JunoException je) { return false; } catch (Exception e){ return false; } } }
54
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/service/EmployeeServiceImpl.java
package com.paypal.juno.employeedashboardapp.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.paypal.juno.employeedashboardapp.model.Employee; import com.paypal.juno.employeedashboardapp.repository.EmployeeRepository; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepository employeeRepository; @Override public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } public class EmployeeAlreadyExistsException extends RuntimeException { public EmployeeAlreadyExistsException(String message) { super(message); } } @Override public void addEmployee(Employee emp) throws Exception { Optional<Employee> recordInDB = employeeRepository.findById(emp.getId()); if (recordInDB.isPresent()) { throw new EmployeeAlreadyExistsException( "Employee with id " + emp.getId() + " already exists. Data Source: MysqlDB"); } else { employeeRepository.save(emp); } } @Override public void saveEmployee(Employee emp) { employeeRepository.save(emp); } @Override public Employee findEmployee(Integer id) { Optional<Employee> optional = employeeRepository.findById(id); Employee emp = null; if (optional.isPresent()) { emp = optional.get(); } return emp; } @Override public void deleteEmployee(Integer id) { Optional<Employee> optional = employeeRepository.findById(id); if (optional.isPresent()) { employeeRepository.deleteById(id); } } }
55
0
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp
Create_ds/junodb/client/Java/examples/employee-dashboard-app/src/main/java/com/paypal/juno/employeedashboardapp/service/EmployeeService.java
package com.paypal.juno.employeedashboardapp.service; import java.util.List; import com.paypal.juno.employeedashboardapp.model.Employee; public interface EmployeeService { List<Employee> getAllEmployees(); void addEmployee(Employee emp) throws Exception; void saveEmployee(Employee emp); Employee findEmployee(Integer id); void deleteEmployee(Integer id); }
56
0
Create_ds/junodb/client/Java/examples/client/junoReferenceApp/junoreferenceAppService/src/main/java/com/juno
Create_ds/junodb/client/Java/examples/client/junoReferenceApp/junoreferenceAppService/src/main/java/com/juno/samples/JunoApplication.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.juno.samples; import com.juno.samples.api.JunoClientSampleResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; @SpringBootApplication @ImportResource("classpath:spring-client.xml") @EnableAutoConfiguration public class JunoApplication { @Autowired JunoClientSampleResource sampleResource; public static void main(String[] args) { SpringApplication.run(JunoApplication.class, args); } }
57
0
Create_ds/junodb/client/Java/examples/client/junoReferenceApp/junoreferenceAppService/src/main/java/com/juno/samples
Create_ds/junodb/client/Java/examples/client/junoReferenceApp/junoreferenceAppService/src/main/java/com/juno/samples/impl/JunoClientSampleResourceImpl.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.juno.samples.impl; import com.juno.samples.api.JunoClientSampleResource; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import io.micrometer.core.instrument.Clock; import io.micrometer.core.instrument.Metrics; import io.micrometer.signalfx.SignalFxMeterRegistry; import java.io.UnsupportedEncodingException; import java.time.Duration; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.StreamSupport; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.metrics.export.signalfx.SignalFxProperties; import org.springframework.boot.actuate.autoconfigure.metrics.export.signalfx.SignalFxPropertiesConfigAdapter; import org.springframework.boot.env.OriginTrackedMapPropertySource; import org.springframework.core.env.*; import org.springframework.core.env.Environment; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.RequestScope; import reactor.core.publisher.Mono; import rx.Single; import rx.SingleSubscriber; /** * This resource shows how to use JAX-RS injection and how to use * a spring bean as a JAX-RS resource class. * * Notice that the scope for this bean is request which means that a new * instance of this class will be created per request. * */ @Component @RequestScope public class JunoClientSampleResourceImpl implements JunoClientSampleResource { @Autowired private Environment env; private Logger LOGGER = LoggerFactory.getLogger(JunoClientSampleResourceImpl.class); @Inject public JunoClient junoClient; @Inject @Named("junoClient2") public JunoClient junoClientMeowMrowHalu; public JunoAsyncClient junoAsyncClient; public JunoReactClient junoReactClient; private Properties pConfig; SignalFxMeterRegistry sfxRegistry; private MutablePropertySources propSrcs; public JunoClientSampleResourceImpl() { LOGGER.info("JunoClientSampleResourceImpl"); String uriLink = ""; // Set your Observability Collector Here SignalFxProperties properties = new SignalFxProperties(); properties.setStep(Duration.ofSeconds(60)); properties.setUri(uriLink); properties.setEnabled(true); properties.setConnectTimeout(Duration.ofSeconds(15)); properties.setReadTimeout(Duration.ofSeconds(10)); properties.setBatchSize(10000); properties.setAccessToken(""); SignalFxPropertiesConfigAdapter config = new SignalFxPropertiesConfigAdapter(properties); sfxRegistry = new SignalFxMeterRegistry(config, Clock.SYSTEM); Metrics.globalRegistry.add(sfxRegistry); } @PostConstruct public void init() { try { propSrcs = ((AbstractEnvironment) env).getPropertySources(); pConfig = new Properties(); StreamSupport.stream(propSrcs.spliterator(), false) .filter(ps -> ps instanceof OriginTrackedMapPropertySource) .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()) .flatMap(Arrays::<String>stream) .forEach(propName -> pConfig.setProperty(propName, env.getProperty(propName))); if(pConfig.size() == 0) throw new Exception(); junoAsyncClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig)); } catch (Exception e ){ LOGGER.debug("Exception Occurred " + e.getMessage() + pConfig.toString()); } LOGGER.info(propSrcs.toString() + "\n" + pConfig.toString()); LOGGER.info(junoClientMeowMrowHalu.getProperties().toString()); } @Override public ResponseEntity<String> sayHello() throws UnsupportedEncodingException { return ResponseEntity.ok("Hello, World!"); } ResponseEntity<String> formSuccessResponse(JunoResponse resp){ return ResponseEntity.ok(formSuccesResString(resp)); } String formSuccesResString(JunoResponse resp){ String doc = ""; try { doc = "{\"status\" : \""+resp.getStatus().getErrorText()+"\", \"creationTime\" : \""+resp.getCreationTime()+"\", \"remainingTTL\" : \""+resp.getTtl()+"\", \"version\" : \""+resp.getVersion()+"\" , \"value\" : \""+new String(resp.getValue(),"UTF-8")+"\"}"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return doc; } ResponseEntity<String> formFailureResponse(String msg){ String doc = "{\"status\":\""+msg+"\"}"; return ResponseEntity.badRequest().body(doc); } @Override public ResponseEntity<String> recordCreate(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("value -> " + value); try{ JunoResponse junoResponse = junoClient.create(key.getBytes("UTF-8"), value.getBytes("UTF-8")); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordCreate(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("value -> " + value); LOGGER.info("ttl -> " + ttl); try{ JunoResponse junoResponse = junoClient.create(key.getBytes("UTF-8"), value.getBytes("UTF-8"), ttl); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordGet(String key) throws JunoException { LOGGER.info("Key -> " + key); try{ JunoResponse junoResponse = junoClient.get(key.getBytes("UTF-8")); String test = JunoProperties.APP_NAME; LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(Exception e){ LOGGER.info("EXCEPTION : " + e.getMessage()); return formFailureResponse(e.getMessage()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordGet(String key, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("ttl -> " + ttl); try{ JunoResponse junoResponse = junoClient.get(key.getBytes("UTF-8"), ttl); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordUpdate(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ JunoResponse junoResponse = junoClient.update(key.getBytes("UTF-8"), value.getBytes("UTF-8")); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordUpdate(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ JunoResponse junoResponse = junoClient.update(key.getBytes("UTF-8"), value.getBytes("UTF-8"), ttl); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordSet(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ JunoResponse junoResponse = junoClient.set(key.getBytes("UTF-8"), value.getBytes("UTF-8")); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordSet(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ JunoResponse junoResponse = junoClient.set(key.getBytes("UTF-8"), value.getBytes("UTF-8"), ttl); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordCompareAndSet(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ JunoResponse junoResponse = junoClient.get(key.getBytes("UTF-8")); if(junoResponse.getStatus() == OperationStatus.Success){ junoResponse = junoClient.compareAndSet(junoResponse.getRecordContext(),value.getBytes("UTF-8"),0); if(junoResponse.getStatus() == OperationStatus.Success){ LOGGER.info("SUCCESS"); }else{ LOGGER.info("Failed to update key Test1"); if(junoResponse.getStatus() == OperationStatus.NoKey){ LOGGER.info("Key not in DB. Some one might have deleted the record."); }else if(junoResponse.getStatus() == OperationStatus.ConditionViolation){ LOGGER.info("Some one might have updated the record before we did."); }else if(junoResponse.getStatus() == OperationStatus.RecordLocked){ LOGGER.info("Some other request has locked the record for update."); }else { LOGGER.info("Log response.getStatus().getErrorText()"); } } } else { LOGGER.info("Failed get key Test1"); if(junoResponse.getStatus() == OperationStatus.NoKey){ LOGGER.info("Key not in DB"); }else { LOGGER.info(junoResponse.getStatus().getErrorText()); } } return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); } finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordCompareAndSetTTL(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ JunoResponse junoResponse = junoClient.get(key.getBytes("UTF-8")); //500 is user supplied TTL if(junoResponse.getStatus() == OperationStatus.Success){ junoResponse = junoClient.compareAndSet(junoResponse.getRecordContext(),value.getBytes("UTF-8"), ttl); if(junoResponse.getStatus() == OperationStatus.Success){ LOGGER.info("SUCCESS"); }else{ LOGGER.info("Failed to update key Test1"); if(junoResponse.getStatus() == OperationStatus.NoKey){ LOGGER.info("Key not in DB. Some one might have deleted the record."); }else if(junoResponse.getStatus() == OperationStatus.ConditionViolation){ LOGGER.info("Some one might have updated the record before we did."); }else if(junoResponse.getStatus() == OperationStatus.RecordLocked){ LOGGER.info("Some other request has locked the record for update."); }else { LOGGER.info("Log response.getStatus().getErrorText()"); } } } else { LOGGER.info("Failed get key Test1"); if(junoResponse.getStatus() == OperationStatus.NoKey){ LOGGER.info("Key not in DB"); }else { LOGGER.info(junoResponse.getStatus().getErrorText()); } } return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); } finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> recordDelete(String key) throws JunoException { LOGGER.info("Key -> " + key); try{ JunoResponse junoResponse = junoClient.delete(key.getBytes("UTF-8")); LOGGER.info("SUCCESS"); return formSuccessResponse(junoResponse); }catch(JunoException e){ LOGGER.info("EXCEPTION"); return formFailureResponse(e.getMessage()); } catch (UnsupportedEncodingException e) { LOGGER.info("EXCEPTION"); return formFailureResponse(OperationStatus.UnknownError.getErrorText()); }finally { LOGGER.info("Completed"); } } @Override public ResponseEntity<String> reactCreate(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.create(key.getBytes("UTF-8"), value.getBytes("UTF-8")); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactCreate(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.create(key.getBytes("UTF-8"), value.getBytes("UTF-8"), ttl); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactGet(String key) throws JunoException { LOGGER.info("Key -> " + key); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.get(key.getBytes("UTF-8")); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactGet(String key, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.get(key.getBytes("UTF-8"), ttl); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactUpdate(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.update(key.getBytes("UTF-8"), value.getBytes("UTF-8")); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactUpdate(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.update(key.getBytes("UTF-8"), value.getBytes("UTF-8"), ttl); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactSet(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.set(key.getBytes("UTF-8"), value.getBytes("UTF-8")); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactSet(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.set(key.getBytes("UTF-8"), value.getBytes("UTF-8"), ttl); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactCompareAndSet(String key, String value) throws JunoException{ LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<>(); JunoResponse monoRes = junoClient.get(key.getBytes("UTF-8")); RecordContext recCtx = monoRes.getRecordContext(); Mono<JunoResponse> compareAndSetResponse = junoReactClient.compareAndSet(recCtx,value.getBytes("UTF-8"), 0); compareAndSetResponse.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactCompareAndSetTTL(String key, String value, Long ttl) throws JunoException{ LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl ->" + ttl); try{ AtomicReference<String> response = new AtomicReference<>(); JunoResponse monoRes = junoClient.get(key.getBytes("UTF-8")); RecordContext recCtx = monoRes.getRecordContext(); Mono<JunoResponse> compareAndSetResponse = junoReactClient.compareAndSet(recCtx,value.getBytes("UTF-8"), ttl); compareAndSetResponse.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> reactDelete(String key) throws JunoException { LOGGER.info("Key -> " + key); try{ AtomicReference<String> response = new AtomicReference<String>(); Mono<JunoResponse> monoRes = junoReactClient.delete(key.getBytes("UTF-8")); monoRes.subscribe(res -> { response.set(formSuccesResString(res)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }, error -> { // Failure in processing the request. Do not SLEEP or BLOCK in this method. // The cause for failure can be obtained via error.getMessage() LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + error.getMessage() + "\"}"); } ); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } private SingleSubscriber<JunoResponse> createSubscriber(AtomicReference<String> response){ SingleSubscriber<JunoResponse> subscriber = new SingleSubscriber<JunoResponse>() { @Override public void onError(Throwable e) { LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); response.set("{\"status\":\"" + e.getMessage() + "\"}"); LOGGER.error(e.getMessage()); } @Override public void onSuccess(JunoResponse res) { response.set(formSuccesResString(res)); if(res.getStatus() == OperationStatus.Success){ LOGGER.info(String.valueOf(res.getStatus())); LOGGER.info("Completed"); } else { if(res.getStatus() == OperationStatus.UniqueKeyViolation){ LOGGER.warn("Key Already exists in DB"); } else if(res.getStatus() == OperationStatus.TTLExtendFailure) { LOGGER.warn("Failure to Extend the TTL of the record."); } else{ LOGGER.warn(res.getStatus().getErrorText()); } } } }; return subscriber; } @Override public ResponseEntity<String> asyncCreate(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> createResponse = junoAsyncClient.create(key.getBytes("UTF-8"),value.getBytes("UTF-8")); createResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncCreate(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> createResponse = junoAsyncClient.create(key.getBytes("UTF-8"),value.getBytes("UTF-8"), ttl); createResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncGet(String key) throws JunoException { LOGGER.info("Key -> " + key); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> getResponse = junoAsyncClient.get(key.getBytes("UTF-8")); getResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncGet(String key, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> getResponse = junoAsyncClient.get(key.getBytes("UTF-8"), ttl); getResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException| UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncUpdate(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> updateResponse = junoAsyncClient.update(key.getBytes("UTF-8"),value.getBytes("UTF-8")); updateResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncUpdate(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> updateResponse = junoAsyncClient.update(key.getBytes("UTF-8"),value.getBytes("UTF-8"), ttl); updateResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncSet(String key, String value) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> setResponse = junoAsyncClient.set(key.getBytes("UTF-8"),value.getBytes("UTF-8")); setResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncSet(String key, String value, Long ttl) throws JunoException { LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> setResponse = junoAsyncClient.set(key.getBytes("UTF-8"),value.getBytes("UTF-8"), ttl); setResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncCompareAndSet(String key, String value) throws JunoException{ LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); try{ AtomicReference<String> response = new AtomicReference<String>(); JunoResponse monoRes = junoClient.get(key.getBytes("UTF-8")); RecordContext recCtx = monoRes.getRecordContext(); Single<JunoResponse> compareAndSetResponse = junoAsyncClient.compareAndSet(recCtx, value.getBytes("UTF-8"), 0); compareAndSetResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncCompareAndSetTTL(String key, String value, Long ttl) throws JunoException{ LOGGER.info("Key -> " + key); LOGGER.info("Value ->" + value); LOGGER.info("ttl -> " + ttl); try{ AtomicReference<String> response = new AtomicReference<String>(); JunoResponse monoRes = junoClient.get(key.getBytes("UTF-8")); RecordContext recCtx = monoRes.getRecordContext(); Single<JunoResponse> compareAndSetResponse = junoAsyncClient.compareAndSet(recCtx, value.getBytes("UTF-8"), 0); compareAndSetResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } @Override public ResponseEntity<String> asyncDelete(String key) throws JunoException { LOGGER.info("Key -> " + key); try{ AtomicReference<String> response = new AtomicReference<String>(); Single<JunoResponse> deleteResponse = junoAsyncClient.delete(key.getBytes("UTF-8")); deleteResponse.subscribe(createSubscriber(response)); for (int i=0; i < 5; i++){ if(response.get() != null) break; Thread.sleep(1000); } if(response.get() != null) { return ResponseEntity.ok(response.get()); }else{ return formFailureResponse("Operation Timed out2"); } }catch(JunoException | UnsupportedEncodingException | InterruptedException e){ LOGGER.info("EXCEPTION"); LOGGER.info("Completed"); return formFailureResponse(e.getMessage()); } } }
58
0
Create_ds/junodb/client/Java/examples/client/junoReferenceApp/junoreferenceAppService/src/main/java/com/juno/samples
Create_ds/junodb/client/Java/examples/client/junoReferenceApp/junoreferenceAppService/src/main/java/com/juno/samples/api/JunoClientSampleResource.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.juno.samples.api; import com.paypal.juno.exception.JunoException; import java.io.UnsupportedEncodingException; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** * Sample interface that shows how a service can be implemented with a separate * interface. This interface can be used as programmatic contract. * */ @RestController @RequestMapping("/samplejuno") public interface JunoClientSampleResource { @GetMapping("/hello") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> sayHello() throws UnsupportedEncodingException; @POST @PostMapping("/recordcreate") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> recordCreate(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @POST @PostMapping("/recordcreatettl") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.APPLICATION_JSON }) ResponseEntity<String> recordCreate(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @GET @Produces({ MediaType.APPLICATION_JSON }) @GetMapping("/recordget/{key}") ResponseEntity<String> recordGet(@PathVariable String key) throws JunoException, InterruptedException; @GET @Produces({ MediaType.APPLICATION_JSON }) @GetMapping("/recordgetttl/{key}/{ttl}") ResponseEntity<String> recordGet(@PathVariable("key") String key, @PathVariable("ttl") Long ttl) throws JunoException, InterruptedException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/recordupdate") ResponseEntity<String> recordUpdate(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/recordupdatettl") ResponseEntity<String> recordUpdate(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/recordset") ResponseEntity<String> recordSet(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/recordsetttl") ResponseEntity<String> recordSet(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @POST @PostMapping("/recordcompareandset") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> recordCompareAndSet(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @POST @PostMapping("/recordcompareandsetttl") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> recordCompareAndSetTTL(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @DELETE @Produces({ MediaType.APPLICATION_JSON }) @DeleteMapping("/recorddelete/{key}") ResponseEntity<String> recordDelete(@PathVariable String key) throws JunoException; @POST @PostMapping("/reactcreate") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> reactCreate(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @POST @PostMapping("/reactcreatettl") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.APPLICATION_JSON }) ResponseEntity<String> reactCreate(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @GET @Produces({ MediaType.APPLICATION_JSON }) @GetMapping("/reactget/{key}") ResponseEntity<String> reactGet(@PathVariable String key) throws JunoException, InterruptedException; @GET @Produces({ MediaType.APPLICATION_JSON }) @GetMapping("/reactgetttl/{key}/{ttl}") ResponseEntity<String> reactGet(@PathVariable("key") String key, @PathVariable("ttl") Long ttl) throws JunoException, InterruptedException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/reactupdate") ResponseEntity<String> reactUpdate(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/reactupdatettl") ResponseEntity<String> reactUpdate(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/reactset") ResponseEntity<String> reactSet(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/reactsetttl") ResponseEntity<String> reactSet(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @POST @PostMapping("/reactcompareandset") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> reactCompareAndSet(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @POST @PostMapping("/reactcompareandsetttl") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> reactCompareAndSetTTL(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @DELETE @Produces({ MediaType.APPLICATION_JSON }) @DeleteMapping("/reactdelete/{key}") ResponseEntity<String> reactDelete(@PathVariable String key) throws JunoException; @POST @PostMapping("/asynccreate") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> asyncCreate(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @POST @PostMapping("/asynccreatettl") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.APPLICATION_JSON }) ResponseEntity<String> asyncCreate(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @GET @Produces({ MediaType.APPLICATION_JSON }) @GetMapping("/asyncget/{key}") ResponseEntity<String> asyncGet(@PathVariable String key) throws JunoException, InterruptedException; @GET @Produces({ MediaType.APPLICATION_JSON }) @GetMapping("/asyncgetttl/{key}/{ttl}") ResponseEntity<String> asyncGet(@PathVariable("key") String key, @PathVariable("ttl") Long ttl) throws JunoException, InterruptedException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/asyncupdate") ResponseEntity<String> asyncUpdate(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/asyncupdatettl") ResponseEntity<String> asyncUpdate(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/asyncset") ResponseEntity<String> asyncSet(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @PUT @Produces({ MediaType.APPLICATION_JSON }) @Consumes("application/x-www-form-urlencoded") @PutMapping("/asyncsetttl") ResponseEntity<String> asyncSet(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @POST @PostMapping("/asynccompareandset") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> asyncCompareAndSet(@FormParam("key") String key, @FormParam("value") String value) throws JunoException; @POST @PostMapping("/asynccompareandsetttl") @Consumes("application/x-www-form-urlencoded") @Produces({ MediaType.TEXT_PLAIN }) ResponseEntity<String> asyncCompareAndSetTTL(@FormParam("key") String key, @FormParam("value") String value, @FormParam("ttl") Long ttl) throws JunoException; @DELETE @Produces({ MediaType.APPLICATION_JSON }) @DeleteMapping("/asyncdelete/{key}") ResponseEntity<String> asyncDelete(@PathVariable String key) throws JunoException; }
59
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/exception/JunoInputException.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.exception; public class JunoInputException extends RuntimeException { /** * {@link OperationStatus}, for use by error mapper. */ /** * Construct a JunoInputException. */ public JunoInputException() { super(); } /** * Construct an JunoInputException given a message. * * @param message * the error text */ public JunoInputException(String message) { // Guard against null messages, since we have seen those occur super(message); } }
60
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/exception/JunoException.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.exception; /** * The base exception type thrown by the JunoClient. Clients can access a * ThrowableWrapper that will conveniently allow {@link JunoException}s * to be wrapped around other {@link Throwable}s. * */ public class JunoException extends RuntimeException { /** * */ private static final long serialVersionUID = 8434646335093981801L; /** * {@link OperationStatus}, for use by error mapper. */ /** * Construct a JunoException. */ public JunoException() { super(); } /** * Construct an JunoException given a message. * * @param message * the error text */ public JunoException(String message) { // Guard against null messages, since we have seen those occur super(message); } /** * Construct an JunoException given a message and a cause. * * @param message * the error text * @param cause * the {@link Throwable} cause */ public JunoException(String message, Throwable cause) { // Guard against null messages, since we have seen those occur super(message); initCause(cause); } /** * Construct an JunoException given a cause. * * @param cause * the {@link Throwable} cause */ public JunoException(Throwable cause) { super(cause.getMessage()); initCause(cause); } }
61
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/JunoAsyncClient.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.exception.JunoException; import java.util.Map; import rx.Observable; import rx.Single; public interface JunoAsyncClient { /** * Insert a record into Juno DB with default TTL * @param key - Key of the record to be Inserted * @param value - Record Value * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> create(byte[] key, byte[] value) throws JunoException; /** * Insert a record into Juno DB with user supplied TTL * @param key - Key of the record to be Inserted * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> create(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Get a record from Juno DB * @param key - Key of the record to be retrieved * @return Single<JunoResponse> - Emits a single response with the record value or Error * @throws JunoException - Throws Exception if any issue while processing the request */ public Single<JunoResponse> get(byte[] key) throws JunoException; /** * Get a record from Juno DB and Extend the TTL * @param key - Key of the record to be retrieved * @param timeToLiveSec - Time to Live for the record * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> get(byte[] key, long timeToLiveSec) throws JunoException; /** * Update a record in Juno DB * @param key - Key of the record to be Updated * @param value - Record Value * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any issue while processing the request */ public Single<JunoResponse> update(byte[] key, byte[] value) throws JunoException; /** * Update a record in Juno DB and Extend its TTL * @param key - Key of the record to be Updated * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> update(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Update the record if present in Juno DB else create that record with the default TTL in the configuration * @param key - Key of the record to be Upserted * @param value - Record Value * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> set(byte[] key, byte[] value) throws JunoException; /** * Update the record if present in Juno DB and extend its TTL else create that record with the supplied TTL. * @param key - Key of the record to be Upserted * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> set(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Delete the record from Juno DB * @param key - Record Key to be deleted * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> delete(byte[] key) throws JunoException; /** * Compare the version of the record in Juno DB and update it only if the supplied version * is greater than or equal to the existing version in Juno DB * @param jcx - Record context from a previous Get operation * @param value - Record Value * @param timeToLiveSec - Time to Live for the record. If set to 0 then the TTL is not extended. * @return Single<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Single<JunoResponse> compareAndSet(RecordContext jcx, byte[] value, long timeToLiveSec) throws JunoException; /** * Perform batch operation on list of requests * @param request - List of requests with necessary data for that operation * @return List of responses for the requests * @throws JunoException - Throws Exception if any issue while processing the requests */ public Observable<JunoResponse> doBatch(Iterable<JunoRequest> request) throws JunoException; /** * return the properties of the current bean in a MAP * The map consists of property name and its value. Property name can be found * in com.paypal.juno.conf.JunoProperties */ public Map<String, String> getProperties(); }
62
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/JunoReactClient.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.exception.JunoException; import java.util.Map; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface JunoReactClient { /** * Insert a record into Juno DB with default TTL * @param key - Key of the record to be Inserted * @param value - Record Value * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> create(byte[] key, byte[] value) throws JunoException; /** * Insert a record into Juno DB with user supplied TTL * @param key - Key of the record to be Inserted * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> create(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Get a record from Juno DB * @param key - Key of the record to be retrieved * @return Mono<JunoResponse> - Emits a single response with the record value or Error * @throws JunoException - Throws Exception if any issue while processing the request */ public Mono<JunoResponse> get(byte[] key) throws JunoException; /** * Get a record from Juno DB and Extend the TTL * @param key - Key of the record to be retrieved * @param timeToLiveSec - Time to Live for the record * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> get(byte[] key, long timeToLiveSec) throws JunoException; /** * Update a record in Juno DB * @param key - Key of the record to be Updated * @param value - Record Value * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any issue while processing the request */ public Mono<JunoResponse> update(byte[] key, byte[] value) throws JunoException; /** * Update a record in Juno DB and Extend its TTL * @param key - Key of the record to be Updated * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> update(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Update the record if present in Juno DB else create that record with the default TTL in the configuration * @param key - Key of the record to be Upserted * @param value - Record Value * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> set(byte[] key, byte[] value) throws JunoException; /** * Update the record if present in Juno DB and extend its TTL else create that record with the supplied TTL. * @param key - Key of the record to be Upserted * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> set(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Delete the record from Juno DB * @param key - Record Key to be deleted * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> delete(byte[] key) throws JunoException; /** * Compare the version of the record in Juno DB and update it only if the supplied version * is greater than or equal to the existing version in Juno DB * @param jcx - Record context from a previous Get operation * @param value - Record Value * @param timeToLiveSec - Time to Live for the record. If set to 0 then the TTL is not extended. * @return Mono<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ public Mono<JunoResponse> compareAndSet(RecordContext jcx, byte[] value, long timeToLiveSec) throws JunoException; /** * Perform batch operation on list of requests * @param request - List of requests with necessary data for that operation * @return Flux<JunoResponse> - List of responses for the requests * @throws JunoException - Throws Exception if any issue while processing the requests */ public Flux<JunoResponse> doBatch(Iterable<JunoRequest> request) throws JunoException; /** * return the properties of the current bean in a MAP * The map consists of property name and its value. Property name can be found * in com.paypal.juno.conf.JunoProperties */ public Map<String, String> getProperties(); }
63
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/JunoClient.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.exception.JunoException; import java.util.Map; public interface JunoClient { /** * Insert a record into Juno DB with default TTL * @param key - Key of the record to be Inserted * @param value - Record Value * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse create(byte[] key, byte[] value) throws JunoException; /** * Insert a record into Juno DB with user supplied TTL * @param key - Key of the record to be Inserted * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse create(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Get a record from Juno DB * @param key - Key of the record to be retrieved * @return JunoResponse - Juno Response object which contains the status of the operation, * version of the record and value of the record. * @throws JunoException - Throws Exception if any issue while processing the request */ public JunoResponse get(byte[] key) throws JunoException; /** * Get a record from Juno DB and Extend the TTL * @param key - Key of the record to be retrieved * @param timeToLiveSec - Time to Live for the record * @return JunoResponse - Juno Response object which contains the status of the operation, * version of the record and value of the record. * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse get(byte[] key, long timeToLiveSec) throws JunoException; /** * Update a record in Juno DB * @param key - Key of the record to be Updated * @param value - Record Value * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any issue while processing the request */ public JunoResponse update(byte[] key, byte[] value) throws JunoException; /** * Update a record in Juno DB and Extend its TTL * @param key - Key of the record to be Updated * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return JunoResponse - Juno Response object which contains the status of the operation. * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse update(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Update the record if present in Juno DB else create that record with the default TTL in the configuration * @param key - Key of the record to be Upserted * @param value - Record Value * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse set(byte[] key, byte[] value) throws JunoException; /** * Update the record if present in Juno DB and extend its TTL else create that record with the supplied TTL. * @param key - Key of the record to be Upserted * @param value - Record Value * @param timeToLiveSec - Time to Live for the record * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse set(byte[] key, byte[] value, long timeToLiveSec) throws JunoException; /** * Delete the record from Juno DB * @param key - Record Key to be deleted * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse delete(byte[] key) throws JunoException; /** * Compare the version of the record in Juno DB and update it only if the supplied version * is greater than or equal to the existing version in Juno DB * @param jcx - Record context from a previous Get operation * @param value - Record Value * @param timeToLiveSec - Time to Live for the record. If set to 0 then the TTL is not extended. * @return JunoResponse - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public JunoResponse compareAndSet(RecordContext jcx, byte[] value, long timeToLiveSec) throws JunoException; /** * Perform batch operation on list of requests * @param request - List of requests with necessary data for that operation * @return List of responses for the requests * @throws JunoException - Throws Exception if any issue while processing the requests */ public Iterable<JunoResponse> doBatch(Iterable<JunoRequest> request) throws JunoException; /** * return the properties of the current bean in a MAP * The map consists of property name and its value. Property name can be found * in com.paypal.juno.conf.JunoProperties */ public Map<String, String> getProperties(); }
64
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/io/OperationStatus.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client.io; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public enum OperationStatus { // Client side Response codes, Error Text status success(true) and failure(false) Success(0,"No error",true), NoKey(1,"Key not found",true), BadParam(2,"Bad parameter",false), UniqueKeyViolation(3,"Duplicate key",true), RecordLocked(4,"Record Locked",true), IllegalArgument(5,"Illegal argument",false), ConditionViolation(6,"Condition in the request violated",true), InternalError(7,"Internal error",false), QueueFull(8,"Outbound client queue full",false), NoStorage(9,"No storage server running",false), TTLExtendFailure(10,"Failure to extend TTL on get",true), ResponseTimeout(11,"Response Timed out",false), ConnectionError(12,"Connection Error",false), UnknownError(13,"Unknown Error",false); private final int code; private final String errorText; private final boolean txnOk; private static final Map<Integer, OperationStatus> lookup = new HashMap<Integer, OperationStatus>(); static { for (OperationStatus s : EnumSet .allOf(OperationStatus.class)) lookup.put(s.getCode(), s); } /** * Constructor * * @param code * @param errorText */ OperationStatus(int code, String errorText,boolean txnOk) { this.code = code; this.errorText = errorText; this.txnOk = txnOk; } public int getCode() { return this.code; } public String getErrorText() { return this.errorText; } public static OperationStatus get(int code) { return lookup.get(code); } public boolean isTxnOk(){ return txnOk; } }
65
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/io/RecordContext.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client.io; import java.util.Arrays; import java.util.Objects; /** * This final class encapsulates the meta data extracted from the returned Juno * server response. The JunoContext is not directly an abstraction in the * Juno wire protocol. * * <p> * JunoContext is used to correlate the GET call and the UPDATE call * (from the same User/Client) to the Juno server in multi-user systems to * preserve integrity of changes of a single user. Optimistic locking is used * to detect collision of {@code <key, value>} pair while your program was trying to * cas particular copy of record. * * <p> * This is an immutable class. * For more information on Java Juno Client usage. * */ public final class RecordContext { private final byte [] key; private final Long version; private final Long creationTime; private final Long timeToLiveSec; /** * Constructs a new MayflyContext using the mandatory fields. * * * @param key Key part of the unique key for Juno server storage. Cannot * be null. * * @param version Version of the record in Juno server storage. Can be a zero * if be returned for a miss/key not found. * * @param creationTime Creation time part of the unique key for Juno server * storage. Cannot be null. * * @param ttl Time to live part of the unique key for Juno server * * @throws IllegalArgumentException If Namespace is null/empty or Key is * null/empty or Version is not positive. */ public RecordContext(byte[] key, long version,long creationTime,long ttl) { // ExceptionUtils.throwIfNull(creationTime, "CreationTime"); // ExceptionUtils.throwIfNull(ttl,"TTL"); // ExceptionUtils.throwIfNull(key, "Key"); // ExceptionUtils.throwIfNull(version, "Version"); this.timeToLiveSec = ttl; this.key = key; this.creationTime = creationTime; this.version = version; } /** * Returns the Key of the record which is being queried. * @return String value of the key. */ public final byte [] getKey() { return key; } /** * Returns the version of the record in the Juno storage. * @return version of the record in the Juno storage. */ public final long getVersion() { return version; } /** * Returns the version of the record in the Juno storage. * @return version of the record in the Juno storage. */ public Long getCreationTime() { return creationTime; } /** * Returns the TimeToLive that is a part of the internal Key used in Juno * storage. * @return long value for the TTL */ public final long getTtl() { return timeToLiveSec; } @Override public int hashCode() { return Objects.hash(key,version,creationTime,timeToLiveSec); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecordContext other = (RecordContext) obj; if (!Arrays.equals(key, other.key)) //key cannot be null return false; if (!creationTime.equals(other.creationTime)) //creationTime cannot be null return false; if (!version.equals(other.version)) //ver cannot be null return false; if (!timeToLiveSec.equals(other.timeToLiveSec)) //ttl cannot be null return false; return true; } }
66
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/io/AbstractResponse.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client.io; import java.util.Arrays; public abstract class AbstractResponse { private byte[] key; private OperationStatus status; /** * Constructor needed for possible subclass serialization. */ protected AbstractResponse() { } protected AbstractResponse(byte[] key, OperationStatus status) { // String k = new String(key); // if (k == null || k.isEmpty()) { // throw new IllegalArgumentException("The Document key must not be null or empty."); // } this.key = key; this.status = status; } public byte[] key() { return key; } public OperationStatus status() { return status; } //public void reportException(IOException e); /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(key); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractResponse other = (AbstractResponse) obj; if (!Arrays.equals(key, other.key)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "AbstractRequest [key=" + Arrays.toString(key) + ", getClass()=" + getClass() + ", toString()=" + super.toString() + "]"; } }
67
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/io/JunoRequest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client.io; import java.io.Serializable; import java.util.Arrays; public class JunoRequest extends AbstractRequest implements Serializable { private static final long serialVersionUID = 1L; private Long timeToLiveSec; private byte[] value; private long version; private long creationTime; private OperationType type; public enum OperationType { Create(1,"CREATE"), Get(2,"GET"), Update(3,"UPDATE"), Set(4,"SET"), Destroy(5,"DESTROY"); private final int code; private final String opType; /** * Constructor * * @param code * @param opText */ OperationType(int code, String opText) { this.code = code; this.opType = opText; } public int getCode() { return code; } public String getOpType() { return opType; } }; public JunoRequest(byte[] key, byte[] value, long version, long timeToLiveSec,long creationTime,OperationType type) { super(key); this.value = value; this.timeToLiveSec = timeToLiveSec; this.version = version; this.creationTime = creationTime; this.type = type; } public JunoRequest(byte[] key, byte[] value, long version, long timeToLiveSec, OperationType type) { super(key); this.value = value; this.timeToLiveSec = timeToLiveSec; this.version = version; this.type = type; } public JunoRequest(byte[] key, byte[] value, long version, OperationType type) { super(key); this.value = value; this.timeToLiveSec = null; this.version = version; this.type = type; } public JunoRequest(byte[] key,long version, long timeToLiveSec, OperationType type) { super(key); this.timeToLiveSec = timeToLiveSec; this.version = version; this.type = type; } public Long getTimeToLiveSec() { return timeToLiveSec; } public byte[] getValue() { return value; } public long getVersion() { return version; } public long getCreationTime() { return creationTime; } public OperationType getType() { return type; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (int) (timeToLiveSec ^ (timeToLiveSec >>> 32)); result = prime * result + Arrays.hashCode(value); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; JunoRequest other = (JunoRequest) obj; if (timeToLiveSec != other.timeToLiveSec) return false; if (!Arrays.equals(value, other.value)) return false; if(version != other.version) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "JunoRequest [timeToLive=" + timeToLiveSec + ", value=" + Arrays.toString(value) + ", key()=" + Arrays.toString(key()) + ", version=" + version + ", toString()=" + super.toString() + ", getClass()=" + getClass() + "]"; } }
68
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/io/JunoResponse.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client.io; import java.io.Serializable; public class JunoResponse extends AbstractResponse implements Serializable { private static final long serialVersionUID = 1L; private byte[] value; private final RecordContext rcx; public JunoResponse(byte[] key, byte[] value, long version, long ttl, long createTime, OperationStatus status) { super(key, status); this.value = value; rcx = new RecordContext(key,version,createTime,ttl); } /** * @return Juno record context */ public RecordContext getRecordContext() { return rcx; } /** * @return the key */ public byte[] getKey() { return rcx.getKey(); } /** * @return the value */ public byte[] getValue() { return value; } /** * @return the version */ public long getVersion() { return rcx.getVersion(); } /** * @return the Remaining time to live */ public long getTtl() { return rcx.getTtl(); } /** * @return the operation Status */ public OperationStatus getStatus(){ return super.status(); } public long getCreationTime() { return rcx.getCreationTime(); } }
69
0
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-api/src/main/java/com/paypal/juno/client/io/AbstractRequest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.juno.client.io; import java.util.Arrays; public abstract class AbstractRequest { private byte[] key; /** * Constructor needed for possible subclass serialization. */ protected AbstractRequest() { } protected AbstractRequest(byte[] key) { // Moving this to validateInput() under util // if (key == null || key.length == 0) { // throw new IllegalArgumentException("The Document key must not be null or empty"); // } this.key = key; } public byte[] key() { return key; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(key); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractRequest other = (AbstractRequest) obj; if (!Arrays.equals(key, other.key)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "AbstractRequest [key=" + Arrays.toString(key) + ", getClass()=" + getClass() + ", toString()=" + super.toString() + "]"; } }
70
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchTestSubscriber.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.exception.JunoException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import rx.Observable; import rx.Observer; public class BatchTestSubscriber implements Observer<JunoResponse> { AtomicInteger num_records = new AtomicInteger(0); AtomicInteger count = new AtomicInteger(0); AtomicBoolean completed = new AtomicBoolean(false); List<JunoResponse> resp = Collections.synchronizedList(new ArrayList<JunoResponse>()); BlockingQueue<JunoException> exception = new LinkedBlockingQueue<>(); private static final Logger LOGGER = LoggerFactory.getLogger(BatchTestSubscriber.class); @BeforeClass public void setup() throws IOException { } BatchTestSubscriber(int num) { num_records.set(num); } public BlockingQueue<JunoException> getAllException() { return exception; } public List<JunoResponse> getAllResps() { return resp; } public Throwable getException() { return exception.peek(); } public List<JunoResponse> getResp() { return resp; } public boolean isCompleted() { return completed.get(); } public int getCount() { return count.get(); } @Override public void onCompleted() { //if (getCount() ) LOGGER.debug("========" + BatchTestSubscriber.class.getSimpleName() + " onCompleted: " + System.currentTimeMillis()); completed.set(true); } @Override public void onError(Throwable e) { LOGGER.debug("========" + BatchTestSubscriber.class.getSimpleName() + " onError: " + e.toString()); try { exception.put((JunoException)e); } catch (InterruptedException e1) { LOGGER.debug("exception put in onError gets exception" + e1); }; } @Override public void onNext(JunoResponse message) { this.count.incrementAndGet(); if (message == null) { LOGGER.debug("========" + BatchTestSubscriber.class.getSimpleName() + " No result"); return; } try { resp.add(message); } catch (JunoException mex) { LOGGER.debug(mex.getMessage()); } LOGGER.debug("========" + BatchTestSubscriber.class.getSimpleName() + " onNext: " + message.getStatus() + System.currentTimeMillis()); } public static List<JunoResponse> getResponse(BatchTestSubscriber subscriber, int timeout) throws JunoException { boolean completed = subscriber.isCompleted(); LOGGER.debug("complete is " + completed + " " + System.currentTimeMillis()); int count = timeout / 10; while (!completed && count > 0) { Throwable t = subscriber.getException(); if (t != null) { LOGGER.debug("=========== Got exception: " + t.getCause()); break; } try { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.debug("thread sleep exception? " + e.getMessage() ); } completed = subscriber.isCompleted(); if (completed) { LOGGER.debug("=========== Completed"); } count --; if (count == 0) { LOGGER.debug("=========== Timeout"); } LOGGER.debug("inside of while loop time is " + System.currentTimeMillis()); } return subscriber.getResp(); } public static List<JunoResponse> subscriberResponse(Observable<JunoResponse> ob, int numKeys) throws JunoException { BatchTestSubscriber batchTestSubscriber = new BatchTestSubscriber(numKeys); LOGGER.debug("time before ob subscribe " + System.currentTimeMillis()); ob.subscribe(batchTestSubscriber); LOGGER.debug("time after ob subscribe " + System.currentTimeMillis()); BatchTestSubscriber.getResponse(batchTestSubscriber, 10000); if (batchTestSubscriber.isCompleted()) { LOGGER.debug("Batch complete"); return batchTestSubscriber.getResp(); } else { throw batchTestSubscriber.exception.poll(); } } public static List<JunoResponse> async_dobatch(JunoAsyncClient asyncJunoClient, List<JunoRequest> requests) throws JunoException { Observable<JunoResponse> ob = asyncJunoClient.doBatch(requests); return subscriberResponse (ob, requests.size()); } }
71
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ReactorConditionUpdateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ReactorConditionUpdateTest{ private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoReactClient junoReactClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(ConditionalUpdateTest.class); URL url = ConditionalUpdateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS"); URL url1 = ConditionalUpdateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); URL url2 = ConditionalUpdateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS"); try{ junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient1 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(1000); } /** * Send a cas request with different payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithDiffPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); JunoResponse junoResponse = junoReactClient.create(key, data, (long)20).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() >= 20-3 && junoResponse.getTtl() <= 20); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() >= 20-3 && junoResponse.getTtl() <= 20); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with same payload - should be successful * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithSamePayload() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas with empty key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithEmptyKey() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); RecordContext rcx = new RecordContext("".getBytes(),(long)1,(long)5,(long)1); try { junoReactClient.compareAndSet(rcx, data, (long)5).block(); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); }catch(Exception mex){ LOGGER.debug("Exception :"+mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } } /** * Send a cas request with null key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); RecordContext rcx=null; try { junoReactClient.compareAndSet(rcx, data, (long)5).block(); AssertJUnit.assertTrue ("Exception is not seen for null key", false); }catch(Exception mex){ LOGGER.debug("Exception :"+mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Record Context cannot be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with no key exists on server and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateKeyWhichDoesNotExist() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); RecordContext rcx = new RecordContext("nonexist".getBytes(), (long)1, (long)5, (long)1); try { JunoResponse mResponse = junoReactClient.compareAndSet(rcx, data, (long)5).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); } finally { LOGGER.info("Completed"); } } /** * Send a cas request with 128 bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith128BytesKey() throws JunoException, Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with 130 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoReactClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5).block(); AssertJUnit.assertTrue ("Exception is NOT seen for Key = 129 bytes length", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with mix of special chars and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = "@@#$%^&*()_+?>,<|}{[]~abc780=.".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.delete(key1).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key1, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); byte[] data2 = DataGenUtils.genBytes(20); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); junoResponse = junoReactClient.get(key1).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key1, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data, (long)2000).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 2000 && junoResponse.getTtl() >= 2000-3); junoResponse = junoReactClient.get(key1, 2200).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(data, junoResponse.getValue()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 2200 && junoResponse.getTtl() >= 2200-3); junoResponse = junoReactClient.update(key1, data2, (long)2000).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(3 == junoResponse.getVersion()); junoResponse = junoReactClient.get(key1).block(); AssertJUnit.assertTrue(3 == junoResponse.getVersion()); AssertJUnit.assertEquals(data2, junoResponse.getValue()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 2200 && junoResponse.getTtl() >= 2200-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with zero lifetime and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithZeroNegLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); JunoResponse junoResponse = junoReactClient.create(key, data, (long)10).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)0).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse1.getTtl() <= 10 && junoResponse1.getTtl() > 10-3); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertTrue(junoResponse1.getTtl() <= 10 && junoResponse1.getTtl() > 10-3); try { junoResponse = junoReactClient.compareAndSet(junoResponse1.getRecordContext(), data1, (long)-1).block(); AssertJUnit.assertTrue(false); } catch (JunoException mex) { LOGGER.debug("Exception occured: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative")); } LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with 3 days lifetime and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); long lifetime = 259200; JunoResponse junoResponse = junoReactClient.create(key, data, (long)10).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse1.getTtl() <= lifetime && junoResponse1.getTtl() > lifetime-3); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(junoResponse1.getTtl() <= lifetime && junoResponse1.getTtl() > lifetime-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with more than 3 days lifetime and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ JunoResponse junoResponse = junoReactClient.create(key, data, (long)10).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data,lifetime).block(); AssertJUnit.assertTrue ("Exception is NOT seen for when lifetime is set to > 3 days", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); //System.out.println("Exception :"+mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=259201, max configured lifetime=259200")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with null payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithNullPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), null, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(0, junoResponse1.getValue().length); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertFalse(true); // Expect no exception LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with 0 payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithZeroPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); byte[] data1 = DataGenUtils.genBytes(0); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(0, junoResponse1.getValue().length); LOGGER.info("SUCCESS"); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertFalse(true); // Expect no exception LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); } finally { LOGGER.info("Completed"); } } /** * Send a cas request with 200KB payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204800); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); } catch (JunoException mex) { LOGGER.debug("exception get is " + mex.getCause().getMessage()); } JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with more than 200KB payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertTrue ("Exception is NOT seen for big payload > 200 KB", false); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with Lifetime and payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithLifeTimeAndPayload() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(1000); long lifetime =5; long lifetime1 = lifetime+2; long lifetime2 = lifetime+5; byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, lifetime1).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); Thread.sleep(6000); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); Thread.sleep (2000); //Sleep 2 more seconds for a total of 13 seconds try { JunoResponse mResponse = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, lifetime2).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); } LOGGER.info("Completed"); } //Below tests needs to be reviewed This is important. /************************************************* * Create 2 client objects with namespaces NS & NS1. * Create records with same key under both clients. * Update the record under NS only. *************************************************/ @Test public void testCUpdateInOneOfTheNameSpaces() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data, (long)20).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient1.create(key, data1).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse1.getValue(), data1); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse.getValue() != junoResponse1.getValue()); JunoResponse junoResponse2 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse2.key()); AssertJUnit.assertTrue(2 == junoResponse2.getVersion()); junoResponse2 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertTrue(junoResponse.getValue().length < junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse2.getValue())); AssertJUnit.assertTrue(new String(junoResponse.getValue()) != new String(junoResponse2.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /************************************************* * Create two clients with the same namespaces but * different application names. Create a record * using client1 with key k1.Update the record * with key k1 using client2. *************************************************/ @Test public void testCUpdateWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() > prop.getDefaultLifetime()-3); JunoResponse junoResponse1 = junoReactClient2.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() > prop.getDefaultLifetime()-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /************************************************* * Attempting cas expired data *************************************************/ @Test public void testCUpdateExpiredData() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(6000); try { JunoResponse mResponse = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); } finally { LOGGER.info("Completed"); } }catch(IllegalArgumentException iaex){ LOGGER.debug(iaex.getMessage()); Assert.fail ("Unexpected exception when calling cas on an expired key"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); Assert.fail ("Unexpected exception when calling cas on an expired key"); } } /************************************************* * Attempting cas on key from a different namespace *************************************************/ @Test public void testCUpdateDifferentNamespace() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(10); try{ JunoResponse junoResponse = junoReactClient.create(key, data, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient1.create(key1, data, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse mResponse = junoReactClient1.compareAndSet(junoResponse.getRecordContext(), data, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue("CAS can have no key error instead of exception", false); } } /************************************************* * Attempting cas to get VersionToOld status *************************************************/ @Test public void testCUpdateVersionTooOld() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data, 10).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); //check for the record junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); String data2 = "New test data to update"; LOGGER.debug("Use compareAndSet to update data"); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data2.getBytes(), new Long (15)).block(); LOGGER.debug("Check for update data"); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals (data2, new String (junoResponse1.getValue())); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); LOGGER.debug("Use cas to update with old version"); String data3 = "Update with modified data"; //Use old response version, update shouldn't be successful try { JunoResponse mResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data3.getBytes(), new Long(1)).block(); AssertJUnit.assertEquals (OperationStatus.ConditionViolation,mResponse1.getStatus()); } catch (JunoException mex) { //LOGGER.debug("OperationStatus is " + mex.getOperationStatus()); AssertJUnit.assertTrue ("Exception is seen for Condition violation :"+mex.getMessage(), false); } JunoResponse mResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, mResponse1.getStatus()); AssertJUnit.assertEquals (2,mResponse1.getVersion()); AssertJUnit.assertTrue (mResponse1.getTtl() <= 15 && mResponse1.getTtl() > 15-3); AssertJUnit.assertEquals (data2.getBytes().length,mResponse1.getValue().length); AssertJUnit.assertEquals (new String(data2.getBytes()), new String(mResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }catch(IllegalArgumentException iaex){ AssertJUnit.assertTrue("shouldn't get expcetion ", false); } } /************************************************* * Attempting cas() with version too old to update *************************************************/ @Test public void testCUpdateVersionTooOld2() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig1); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); //check for the record junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); String data2 = "New test data to update"; LOGGER.debug("Use cas()to update data"); JunoResponse junoResponse2 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data2.getBytes(), new Long (15)).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertTrue (2 == junoResponse2.getVersion()); String data3 = "Other new test data to update again"; LOGGER.debug("Use cas()to update data"); try { JunoResponse junoResponse3 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data3.getBytes(), new Long (15)).block(); AssertJUnit.assertEquals (OperationStatus.ConditionViolation, junoResponse3.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for Condition Violation", false); } //Read again to ensure that right data is returned JunoResponse junoResponse4 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse4.getStatus()); AssertJUnit.assertEquals(key, junoResponse4.key()); AssertJUnit.assertTrue(2 == junoResponse4.getVersion()); AssertJUnit.assertEquals(data2, new String(junoResponse4.getValue())); AssertJUnit.assertTrue(junoResponse4.getTtl() <= prop.getDefaultLifetime() && junoResponse4.getTtl() > prop.getDefaultLifetime()-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }catch(IllegalArgumentException iaex){ LOGGER.debug(iaex.getMessage()); } } /** * Send a cas request with different payload and should not generate an exception * @throws JunoException * @throws IOException * Seeing negative version print out * Version: -8 */ //@Test public void testCUpdateVersionOverflow() throws JunoException, IOException{ byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); JunoResponse junoResponse = junoReactClient.create(key, data, (long)20).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); long lifetime = 5L; //after 65536, should be overflow for (int i = 0; i < 65540; i++) { lifetime +=1; junoResponse = junoReactClient.get(key, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); //org.junit.Assert.assertEquals(key, junoResponse1.key()); //org.junit.Assert.assertEquals("NS", junoResponse1.getNamespace()); LOGGER.debug("Version: " + junoResponse1.getVersion()); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); } } }
72
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/MetricTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.JunoMetrics; import com.paypal.juno.util.SSLUtil; import io.micrometer.core.instrument.*; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.signalfx.SignalFxMeterRegistry; import java.io.IOException; import java.net.InetAddress; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.time.Duration; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.autoconfigure.metrics.export.signalfx.SignalFxProperties; import org.springframework.boot.actuate.autoconfigure.metrics.export.signalfx.SignalFxPropertiesConfigAdapter; import org.testng.AssertJUnit; import org.testng.annotations.*; public class MetricTest { private JunoClient junoClient; private JunoAsyncClient junoAsyncClient; private JunoReactClient junoReactClient; private Properties pConfig; private Logger LOGGER; private String ip; private String port; private String ipAddr; private int loop = 5; //set as 100 if we want to observe UI data SignalFxMeterRegistry sfxRegistry; SimpleMeterRegistry simpleMeterRegistry; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(MetricTest.class); String uriLink = ""; // Set your Observability Collector Here AssertJUnit.assertTrue(!uriLink.isEmpty()); SignalFxProperties properties = new SignalFxProperties(); properties.setStep(Duration.ofSeconds(60)); properties.setUri(uriLink); properties.setEnabled(true); properties.setConnectTimeout(Duration.ofSeconds(15)); properties.setReadTimeout(Duration.ofSeconds(10)); properties.setBatchSize(10000); properties.setAccessToken(""); SignalFxPropertiesConfigAdapter config = new SignalFxPropertiesConfigAdapter(properties); sfxRegistry = new SignalFxMeterRegistry(config, Clock.SYSTEM); Metrics.globalRegistry.add(sfxRegistry); URL url = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); ip = pConfig.getProperty("juno.server.host"); port = pConfig.getProperty("juno.server.port"); InetAddress address = InetAddress.getByName(ip); ipAddr = address.getHostAddress(); LOGGER.error( " juno ip is " + ip + " juno port is " + port + ", ipaddr is " + ipAddr); try{ junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoAsyncClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(100); } @AfterClass public void teardown() { //System.out.println("Calling teardown"); sfxRegistry.close(); simpleMeterRegistry.close(); } @BeforeMethod public void beforeEach() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //System.out.println("Calling BeforeEach"); simpleMeterRegistry = new SimpleMeterRegistry(); Metrics.globalRegistry.add(simpleMeterRegistry); } @AfterMethod public void afterEach() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //System.out.println("Calling AfterEach"); simpleMeterRegistry.clear(); simpleMeterRegistry.close(); Metrics.globalRegistry.remove(simpleMeterRegistry); } @Test public void testSingleOperations() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); URL url1 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.MAX_CONNECTION_POOL_SIZE, "100"); pConfig1.setProperty(JunoProperties.CONNECTION_POOL_SIZE, "100"); JunoClient junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoClient1.delete("test_key".getBytes()); for(int i=0; i< loop; i++){ byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); //Create operation try{ junoClient1.create(key,data); junoClient1.create(key,data); }catch (Exception e){ } //Create operation try{ junoClient1.get(key); junoClient1.get("test_key".getBytes()); }catch (Exception e){ } //Create operation try{ junoClient1.set(key,data); }catch (Exception e){ } //Create operation try{ junoClient1.update(key,data); junoClient1.update("test_key".getBytes(),data); }catch (Exception e){ } //Create operation try{ junoClient1.delete(key); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","SUCCESS").timer(); Counter successEvtCnt = registry.find(JunoMetrics.CONNECT_METRIC).tag("endpoint", ipAddr+":"+port).tag(JunoMetrics.STATUS, "SUCCESS").counter(); Counter uniqueErrCnt = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag(JunoMetrics.STATUS, "Duplicate key").tag(JunoMetrics.STATUS, OperationStatus.UniqueKeyViolation.getErrorText()).counter(); Counter keyNotFoundCnt = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag(JunoMetrics.STATUS, "Key not found").tag(JunoMetrics.STATUS, OperationStatus.NoKey.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(100, (int)successEvtCnt.count(), 98); //this value relates to connection pool and take time to get value AssertJUnit.assertEquals(loop, (int)uniqueErrCnt.count()); AssertJUnit.assertEquals(loop, (int)keyNotFoundCnt.count()); } } } // @Test public void testNullEmptyKeyNullPayload() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); byte[] data1 = null; byte[] key2 = "".getBytes(); for(int i=0; i<loop; i++){ byte[] key1 = DataGenUtils.genBytes(10); //Create operation try{ junoClient.create(key,data); //null key }catch (Exception e){ } try{ junoClient.create(key1, data1); //null payload }catch (Exception e){ } try{ junoClient.create(key2, data); //empty key }catch (Exception e){ } //Get operation try{ junoClient.get(key); }catch (Exception e){ } try{ junoClient.get(key2); }catch (Exception e){ } //Update operation try{ junoClient.update(key, data); }catch (Exception e){ } try{ junoClient.update(key1, data1); }catch (Exception e){ } try{ junoClient.update(key2, data); }catch (Exception e){ } //Set operation try{ junoClient.set(key, data); }catch (Exception e){ } try{ junoClient.set(key1, data1); }catch (Exception e){ } try{ junoClient.set(key2, data); }catch (Exception e){ } //Destroy operation try{ junoClient.delete(key2); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer createErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","ERROR").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer setErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","ERROR").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer updateErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","ERROR").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","ERROR").timer(); Counter createErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "DESTROY").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Thread.sleep(1000); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)createErrTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)setTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)setErrTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)updateErrTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)createErr.count()); AssertJUnit.assertEquals(loop*2, (int)getErr.count()); AssertJUnit.assertEquals(loop*2, (int)setErr.count()); AssertJUnit.assertEquals(loop*2, (int)updateErr.count()); AssertJUnit.assertEquals(loop, (int)destroyErr.count()); } } } @Test public void testExceedsSize() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = DataGenUtils.genBytes(257); byte[] data = DataGenUtils.genBytes(10); byte[] key1 = DataGenUtils.genBytes(25); byte[] data1 = DataGenUtils.genBytes(2048011); for(int i=0; i<loop; i++){ //Create operation try{ junoClient.create(key,data); }catch (Exception e){ } try{ junoClient.create(key1,data1); }catch (Exception e){ } //Get operation try{ junoClient.get(key); }catch (Exception e){ } //Update operation try{ junoClient.update(key, data); }catch (Exception e){ } try{ junoClient.update(key1, data1); }catch (Exception e){ } //Set operation try{ junoClient.set(key,data); }catch (Exception e){ } try{ junoClient.set(key1,data1); }catch (Exception e){ } //Destroy operation try{ junoClient.delete(key); }catch (Exception e){ } Thread.sleep(200); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","ERROR").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","ERROR").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","ERROR").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","ERROR").timer(); Counter createKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updatePayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "DESTROY").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)getTimer.count(), 2); AssertJUnit.assertEquals(loop*2, (int)setTimer.count(), 2); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)createKeyErr.count()); AssertJUnit.assertEquals(loop, (int)createPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)getKeyErr.count()); AssertJUnit.assertEquals(loop, (int)setKeyErr.count()); AssertJUnit.assertEquals(loop, (int)setPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)updateKeyErr.count()); AssertJUnit.assertEquals(loop, (int)updatePayloadErr.count()); AssertJUnit.assertEquals(loop, (int)destroyKeyErr.count()); } } } @Test public void testInvalidLifetime() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); for(int i=0; i<loop; i++){ //Create operation try{ junoClient.create(key, data, (long)0); }catch (Exception e){ } try{ junoClient.create(key, data, (long)-1); }catch (Exception e){ } try{ junoClient.create(key, data, (long)7770000); //exceeds max lifetime }catch (Exception e){ } //Get operation try{ junoClient.create(key, data, (long)5); junoClient.get(key, (long)0); ////this is allowed for update, so successful }catch (Exception e){ } try{ junoClient.get(key, (long)-1); }catch (Exception e){ } try{ junoClient.get(key, (long)7770000); }catch (Exception e){ } //Update operation try{ junoClient.update(key, data, (long)0); //this is allowed for update, so successful }catch (Exception e){ } try{ junoClient.update(key, data, (long)-1); }catch (Exception e){ } try{ junoClient.update(key, data, (long)7770000); }catch (Exception e){ } //Set operation try{ junoClient.set(key, data, (long)0); //this is allowed for set, so successful }catch (Exception e){ } try{ junoClient.set(key, data, (long)-1); }catch (Exception e){ } try{ junoClient.set(key, data, (long)7770000); }catch (Exception e){ } //Destroy operation try{ junoClient.delete(key); }catch (Exception e){ } Thread.sleep(100); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","SUCCESS").timer(); Counter createInvalidTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)getTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)setTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 1); AssertJUnit.assertEquals(2 * loop, (int)createInvalidTTLErr.count()); AssertJUnit.assertEquals(loop, (int)createExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)getNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)getExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)setNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)setExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)updateNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)updateExceedsTTLErr.count()); } } } // @Test public void testTimeoutMetric() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); //response timeout config URL url2 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "MetricNS2"); pConfig2.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoClient junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); for(int i=0; i<loop; i++){ byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); //Create operation, response timeout try{ junoClient2.create(key, data); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Counter createRespTimeoutErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Response Timed out").tag("status", OperationStatus.ResponseTimeout.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)createRespTimeoutErr.count()); } } } @Test public void testAsyncSingleOperations() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); junoAsyncClient.delete("test_key".getBytes()).subscribe(); for(int i=0; i<loop; i++){ byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); //Create operation try{ junoAsyncClient.create(key,data).subscribe(); Thread.sleep(300); junoAsyncClient.create(key,data).subscribe(); }catch (Exception e){ } //Create operation try{ junoAsyncClient.get(key).subscribe(); junoAsyncClient.get("test_key".getBytes()).subscribe(); }catch (Exception e){ } //Create operation try{ Thread.sleep(300); junoAsyncClient.set(key,data).subscribe(); }catch (Exception e){ } //Create operation try{ Thread.sleep(300); junoAsyncClient.update(key,data).subscribe(); junoAsyncClient.update("test_key".getBytes(),data).subscribe(); }catch (Exception e){ } //Create operation try{ Thread.sleep(300); junoAsyncClient.delete(key).subscribe(); }catch (Exception e){ } Thread.sleep(300); } //Thread.sleep(10000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","SUCCESS").timer(); Counter uniqueErrCnt = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("status", OperationStatus.UniqueKeyViolation.getErrorText()).counter(); Counter keyNotFoundCnt = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("status", "Key not found").tag("status", OperationStatus.NoKey.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop, (int)keyNotFoundCnt.count(),1); AssertJUnit.assertEquals(loop, (int)uniqueErrCnt.count()); } } } // @Test public void testAsyncNullEmptyKeyNullPayload() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); byte[] data1 = null; byte[] key2 = "".getBytes(); for(int i=0; i<loop; i++){ byte[] key1 = DataGenUtils.genBytes(10); //Create operation try{ junoAsyncClient.create(key,data).subscribe(); //null key }catch (Exception e){ } try{ junoAsyncClient.create(key1, data1).subscribe(); //null payload }catch (Exception e){ } try{ junoAsyncClient.create(key2, data).subscribe(); //empty key }catch (Exception e){ } //Get operation try{ junoAsyncClient.get(key).subscribe(); }catch (Exception e){ } try{ junoAsyncClient.get(key2).subscribe(); }catch (Exception e){ } //Update operation try{ junoAsyncClient.update(key, data).subscribe(); }catch (Exception e){ } try{ Thread.sleep(100); junoAsyncClient.update(key1, data1).subscribe(); }catch (Exception e){ } try{ junoAsyncClient.update(key2, data).subscribe(); }catch (Exception e){ } //Set operation try{ junoAsyncClient.set(key, data).subscribe(); }catch (Exception e){ } try{ junoAsyncClient.set(key1, data1).subscribe(); }catch (Exception e){ } try{ junoAsyncClient.set(key2, data).subscribe(); }catch (Exception e){ } //Destroy operation try{ junoAsyncClient.delete(key).subscribe(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer createErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","ERROR").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer setErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","ERROR").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer updateErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","ERROR").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","ERROR").timer(); Counter createErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "DESTROY").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Thread.sleep(2000); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)createErrTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)setTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)setErrTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)updateErrTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)createErr.count()); AssertJUnit.assertEquals(loop*2, (int)getErr.count()); AssertJUnit.assertEquals(loop*2, (int)setErr.count()); AssertJUnit.assertEquals(loop*2, (int)updateErr.count()); } } } @Test public void testAsyncExceedsSize() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = DataGenUtils.genBytes(257); byte[] data = DataGenUtils.genBytes(10); byte[] key1 = DataGenUtils.genBytes(25); byte[] data1 = DataGenUtils.genBytes(2048011); for(int i=0; i<loop; i++){ //Create operation try{ junoAsyncClient.create(key,data).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.create(key1,data1).subscribe(); Thread.sleep(300); }catch (Exception e){ } //Get operation try{ junoAsyncClient.get(key).subscribe(); }catch (Exception e){ } //Update operation try{ Thread.sleep(300); junoAsyncClient.update(key, data).subscribe(); }catch (Exception e){ } try{ Thread.sleep(300); junoAsyncClient.update(key1, data1).subscribe(); }catch (Exception e){ } //Set operation try{ Thread.sleep(300); junoAsyncClient.set(key,data).subscribe(); }catch (Exception e){ } try{ Thread.sleep(300); junoAsyncClient.set(key1,data1).subscribe(); }catch (Exception e){ } //Destroy operation try{ junoAsyncClient.delete(key).subscribe(); }catch (Exception e){ } Thread.sleep(300); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","ERROR").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","ERROR").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","ERROR").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","ERROR").timer(); Counter createKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updatePayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "DESTROY").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)getTimer.count(), 2); AssertJUnit.assertEquals(loop*2, (int)setTimer.count(), 2); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)createKeyErr.count()); AssertJUnit.assertEquals(loop, (int)createPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)getKeyErr.count()); AssertJUnit.assertEquals(loop, (int)setKeyErr.count()); AssertJUnit.assertEquals(loop, (int)setPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)updateKeyErr.count()); AssertJUnit.assertEquals(loop, (int)updatePayloadErr.count()); AssertJUnit.assertEquals(loop, (int)destroyKeyErr.count()); } } } @Test public void testAsyncInvalidLifetime() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); for(int i=0; i<loop; i++){ //Create operation try{ junoAsyncClient.create(key, data, (long)0).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.create(key, data, (long)-1).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.create(key, data, (long)7770000).subscribe(); //exceeds max lifetime Thread.sleep(300); }catch (Exception e){ } //Get operation try{ junoAsyncClient.create(key, data, (long)5).subscribe(); junoAsyncClient.get(key, (long)0).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.get(key, (long)-1).subscribe(); }catch (Exception e){ } try{ junoAsyncClient.get(key, (long)7770000).subscribe(); Thread.sleep(300); }catch (Exception e){ } //Update operation try{ junoAsyncClient.update(key, data, (long)0).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.update(key, data, (long)-1).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.update(key, data, (long)7770000).subscribe(); Thread.sleep(300); }catch (Exception e){ } //Set operation try{ junoAsyncClient.set(key, data, (long)0).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.set(key, data, (long)-1).subscribe(); Thread.sleep(300); }catch (Exception e){ } try{ junoAsyncClient.set(key, data, (long)7770000).subscribe(); Thread.sleep(300); }catch (Exception e){ } //Destroy operation try{ junoAsyncClient.delete(key).subscribe(); Thread.sleep(300); }catch (Exception e){ } Thread.sleep(100); } // Thread.sleep (10000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","SUCCESS").timer(); Counter createInvalidTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)getTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)setTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 1); AssertJUnit.assertEquals(2 * loop, (int)createInvalidTTLErr.count()); AssertJUnit.assertEquals(loop, (int)createExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)getNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)getExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)setNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)setExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)updateNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)updateExceedsTTLErr.count()); } } } @Test public void testAsyncTimeoutMetric() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); //response timeout config URL url2 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "MetricNS2"); pConfig2.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoAsyncClient junoAsyncClient2 = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); for(int i=0; i<loop; i++){ byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); //Create operation, response timeout try{ junoAsyncClient2.create(key, data).subscribe(); }catch (Exception e){ } Thread.sleep(300); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Counter createRespTimeoutErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Response Timed out").tag("status", OperationStatus.ResponseTimeout.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)createRespTimeoutErr.count()); } } } @Test public void testAsyncBlockBatchOp() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Iterable<JunoResponse> batchResp = null; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 2047); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ batchResp = junoAsyncClient.doBatch(createList).toBlocking().toIterable(); for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } }catch (Exception e){ } //Get operation try{ batchResp = junoAsyncClient.doBatch(getList).toBlocking().toIterable(); for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } }catch (Exception e){ } //Set operation try{ batchResp = junoAsyncClient.doBatch(setList).toBlocking().toIterable(); for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } }catch (Exception e){ } //Update operation try{ batchResp = junoAsyncClient.doBatch(updateList).toBlocking().toIterable(); for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } }catch (Exception e){ } //Destroy operation try{ Iterable<JunoResponse> delResp = junoAsyncClient.doBatch(deleteList).toBlocking().toIterable(); for (JunoResponse mResponse: delResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); AssertJUnit.assertEquals(numKeys*loop, (int)createTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)getTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)setTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)updateTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)deleteTimer.count(),1); } } } @Test public void testAsyncNonBlockBatchOp() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 2047); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ BatchTestSubscriber.async_dobatch(junoAsyncClient, createList); }catch (Exception e){ } //Get operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, getList); }catch (Exception e){ } //Set operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, setList); }catch (Exception e){ } //Update operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, updateList); }catch (Exception e){ } //Destroy operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, deleteList); }catch (Exception e){ } Thread.sleep(300); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); AssertJUnit.assertEquals(numKeys*loop, (int)createTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)getTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)setTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)updateTimer.count(),1); AssertJUnit.assertEquals(numKeys*loop, (int)deleteTimer.count(),1); } } } @Test public void testAsyncZeroNullPayloadBatch() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { payload[i] = DataGenUtils.createKey(10).getBytes(); if ( i <= 1 ) { key[i] = DataGenUtils.createKey(25).getBytes(); } else { if ( i % 2 == 0 ) { key[i] = "".getBytes(); } else { key[i] = null; } } try { createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); } catch (Exception e) {} try { getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); } catch (Exception e) {} try { setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); } catch (Exception e) {} try { updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); } catch (Exception e) {} try { deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } catch (Exception e) {} } for(int i=0; i<loop; i++){ //Create operation try{ BatchTestSubscriber.async_dobatch(junoAsyncClient, createList); }catch (Exception e){ } //Get operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, getList); }catch (Exception e){ } //Set operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, setList); }catch (Exception e){ } //Update operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, updateList); }catch (Exception e){ } //Destroy operation try{ Thread.sleep(100); BatchTestSubscriber.async_dobatch(junoAsyncClient, deleteList); }catch (Exception e){ } Thread.sleep(300); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter createErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_DESTROY").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys-2), (int)createErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)getErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)setErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)updateErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)destroyErr.count()); } } } @Test public void testAsyncMoreThan200PayloadBatch() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = DataGenUtils.createKey(25); payload[i] = DataGenUtils.genBytes(204801); payload[numKeys-1] = DataGenUtils.genBytes(20); createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ BatchTestSubscriber.async_dobatch(junoAsyncClient, createList); }catch (Exception e){ } //Get operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, getList); }catch (Exception e){ } //Set operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, setList); }catch (Exception e){ } //Update operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, updateList); }catch (Exception e){ } //Destroy operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, deleteList); }catch (Exception e){ } Thread.sleep(300); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter createExceedsPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys-1), (int)createExceedsPayloadErr.count()); AssertJUnit.assertEquals(loop*(numKeys-1), (int)updateExceedsPayloadErr.count()); AssertJUnit.assertEquals(loop*(numKeys-1), (int)setExceedsPayloadErr.count()); } } } @Test public void testAsyncTTLMoreThan3DaysBatch() throws IOException, InterruptedException {//BUG, same as previous one LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; long[] ttl = new long[numKeys]; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); payload[i] = DataGenUtils.genBytes(20); if ( i < 5 ) { ttl[i] = 100; } else { if ( i % 3 == 0 ) { ttl[i] = 0; } else if ( i % 3 == 1 ) { ttl[i] = -1; } else { ttl [i] = 259201; } } createList.add(new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, ttl[i], JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ BatchTestSubscriber.async_dobatch(junoAsyncClient, createList); }catch (Exception e){ } //Get operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, getList); }catch (Exception e){ } //Set operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, setList); }catch (Exception e){ } //Update operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, updateList); }catch (Exception e){ } //Destroy operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient, deleteList); }catch (Exception e){ } Thread.sleep(300); } Thread.sleep(500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter createExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createInvalidTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*5, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys/2), (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys/2), (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys/2), (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop*5, (int)createExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)updateExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)setExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)getExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5*2, (int)createInvalidTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)updateNegTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)setNegTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)getNegTTLErr.count()); } } } // @Test public void testAsyncZeroNullKeyBatch() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); URL url1 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.MAX_CONNECTION_POOL_SIZE, "100"); pConfig1.setProperty(JunoProperties.CONNECTION_POOL_SIZE, "100"); JunoAsyncClient junoAsyncClient1 = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { payload[i] = DataGenUtils.createKey(10).getBytes(); String str = DataGenUtils.createKey(25); if ( i <= 1 ) { key[i] = DataGenUtils.createKey(25).getBytes(); } else { if ( i % 2 == 0 ) { key[i] = "".getBytes(); } else { key[i] = null; } } try{ createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); }catch (Exception e) { } try { getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); }catch (Exception e) { } try { setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); }catch (Exception e) { } try { updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); }catch (Exception e) { } try { deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); }catch (Exception e) { } } for(int i=0; i<loop; i++){ //Create operation try{ BatchTestSubscriber.async_dobatch(junoAsyncClient1, createList); }catch (Exception e){ } //Get operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient1, getList); }catch (Exception e){ } //Set operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient1, setList); }catch (Exception e){ } //Update operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient1, updateList); }catch (Exception e){ } //Destroy operation try{ Thread.sleep(300); BatchTestSubscriber.async_dobatch(junoAsyncClient1, deleteList); }catch (Exception e){ } Thread.sleep(300); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter successEvtCnt = registry.find(JunoMetrics.CONNECT_METRIC).tag("endpoint", ipAddr+":"+port).tag("status", "SUCCESS").counter(); Counter createErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_DESTROY").tag("status", "Illegal argument").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(100, (int)successEvtCnt.count(), 98); //this value relates to connection pool and take time to get value AssertJUnit.assertEquals(loop*(numKeys-2), (int)createErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)getErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)setErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)updateErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)destroyErr.count()); } } } @Test public void testReactSingleOperation() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); junoReactClient.delete("test_key".getBytes()); for(int i=0; i<loop; i++){ byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); //Create operation try{ junoReactClient.create(key,data).block(); junoReactClient.create(key,data).block(); }catch (Exception e){ } //Create operation try{ junoReactClient.get(key).block(); junoReactClient.get("test_key".getBytes()).block(); }catch (Exception e){ } //Create operation try{ junoReactClient.set(key,data).block(); }catch (Exception e){ } //Create operation try{ junoReactClient.update(key,data).block(); junoReactClient.update("test_key".getBytes(),data).block(); }catch (Exception e){ } //Create operation try{ junoReactClient.delete(key).block(); }catch (Exception e){ } Thread.sleep(300); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","SUCCESS").timer(); Counter uniqueErrCnt = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("status", "Duplicate key").tag("status", OperationStatus.UniqueKeyViolation.getErrorText()).counter(); Counter keyNotFoundCnt = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("status", "Key not found").tag("status", OperationStatus.NoKey.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop, (int)uniqueErrCnt.count(), 1); AssertJUnit.assertEquals(loop, (int)keyNotFoundCnt.count(), 1); } } } // @Test public void testReactNullEmptyKeyNullPayload() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); byte[] data1 = null; byte[] key2 = "".getBytes(); for(int i=0; i<loop; i++){ byte[] key1 = DataGenUtils.genBytes(10); //Create operation try{ junoReactClient.create(key,data).block(); //null key }catch (Exception e){ } try{ junoReactClient.create(key1, data1).block(); //null payload }catch (Exception e){ } try{ junoReactClient.create(key2, data).block(); //empty key }catch (Exception e){ } Thread.sleep(300); //Get operation try{ junoReactClient.get(key).block(); }catch (Exception e){ } try{ junoReactClient.get(key2).block(); }catch (Exception e){ } //Update operation try{ junoReactClient.update(key, data).block(); }catch (Exception e){ } try{ junoReactClient.update(key1, data1).block(); }catch (Exception e){ } try{ junoReactClient.update(key2, data).block(); }catch (Exception e){ } Thread.sleep(300); //Set operation try{ junoReactClient.set(key, data).block(); }catch (Exception e){ } try{ junoReactClient.set(key1, data1).block(); }catch (Exception e){ } try{ junoReactClient.set(key2, data).block(); }catch (Exception e){ } Thread.sleep(300); //Destroy operation try{ junoReactClient.delete(key2).block(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer createErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","ERROR").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer setErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","ERROR").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer updateErrTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","ERROR").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","ERROR").timer(); Counter createErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "DESTROY").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)createErrTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)setTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)setErrTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)updateErrTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 1); AssertJUnit.assertEquals(loop*2, (int)createErr.count()); AssertJUnit.assertEquals(loop*2, (int)getErr.count()); AssertJUnit.assertEquals(loop*2, (int)setErr.count()); AssertJUnit.assertEquals(loop*2, (int)updateErr.count()); AssertJUnit.assertEquals(loop, (int)destroyErr.count()); } } } // @Test public void testReactExceedsSize() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); URL url1 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.MAX_CONNECTION_POOL_SIZE, "100"); pConfig1.setProperty(JunoProperties.CONNECTION_POOL_SIZE, "100"); JunoReactClient junoReactClient1 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); byte[] key = DataGenUtils.genBytes(257); byte[] data = DataGenUtils.genBytes(10); byte[] key1 = DataGenUtils.genBytes(25); byte[] data1 = DataGenUtils.genBytes(2048011); for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient1.create(key,data).block(); //key exceeds size }catch (Exception e){ } try{ junoReactClient1.create(key1,data1).block(); //payload exceeds size }catch (Exception e){ } //Get operation try{ junoReactClient1.get(key).block(); }catch (Exception e){ } //Update operation try{ junoReactClient1.update(key, data).block(); }catch (Exception e){ } try{ junoReactClient1.update(key1, data1).block(); }catch (Exception e){ } //Set operation try{ junoReactClient1.set(key,data).block(); }catch (Exception e){ } try{ junoReactClient1.set(key1,data1).block(); }catch (Exception e){ } //Destroy operation try{ junoReactClient1.delete(key).block(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","ERROR").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","ERROR").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","ERROR").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","ERROR").timer(); Counter successEvtCnt = registry.find(JunoMetrics.CONNECT_METRIC).tag("endpoint", ipAddr+":"+port).tag("status", "SUCCESS").counter(); Counter createKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updatePayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "key_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyKeyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "DESTROY").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Thread.sleep(2000); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)getTimer.count(), 2); AssertJUnit.assertEquals(loop*2, (int)setTimer.count(), 2); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(), 2); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 2); AssertJUnit.assertEquals(100, (int)successEvtCnt.count(), 98); //this value relates to connection pool and take time to get value AssertJUnit.assertEquals(loop, (int)createKeyErr.count()); AssertJUnit.assertEquals(loop, (int)createPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)getKeyErr.count()); AssertJUnit.assertEquals(loop, (int)setKeyErr.count()); AssertJUnit.assertEquals(loop, (int)setPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)updateKeyErr.count()); AssertJUnit.assertEquals(loop, (int)updatePayloadErr.count()); AssertJUnit.assertEquals(loop, (int)destroyKeyErr.count()); } } } @Test public void testReactInvalidLifetime() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient.create(key, data, (long)0).block(); }catch (Exception e){ } try{ junoReactClient.create(key, data, (long)-1).block(); }catch (Exception e){ } try{ junoReactClient.create(key, data, (long)7770000).block(); //exceeds max lifetime }catch (Exception e){ } //Get operation try{ junoReactClient.create(key, data, (long)5).block(); junoReactClient.get(key, (long)0).block(); }catch (Exception e){ } try{ junoReactClient.get(key, (long)-1).block(); }catch (Exception e){ } try{ junoReactClient.get(key, (long)7770000).block(); }catch (Exception e){ } //Update operation try{ junoReactClient.update(key, data, (long)0).block(); }catch (Exception e){ } try{ junoReactClient.update(key, data, (long)-1).block(); }catch (Exception e){ } try{ junoReactClient.update(key, data, (long)7770000).block(); }catch (Exception e){ } //Set operation try{ junoReactClient.set(key, data, (long)0).block(); }catch (Exception e){ } try{ junoReactClient.set(key, data, (long)-1).block(); }catch (Exception e){ } try{ junoReactClient.set(key, data, (long)7770000).block(); }catch (Exception e){ } //Destroy operation try{ junoReactClient.delete(key).block(); }catch (Exception e){ } Thread.sleep(100); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","DESTROY").tag("status","SUCCESS").timer(); Counter createInvlidTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "GET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "SET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "UPDATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)getTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)setTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)updateTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)deleteTimer.count(), 1); AssertJUnit.assertEquals(2 * loop, (int)createInvlidTTLErr.count()); AssertJUnit.assertEquals(loop, (int)createExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)getNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)getExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)setNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)setExceedsTTLErr.count()); AssertJUnit.assertEquals(loop, (int)updateNegTTLErr.count()); AssertJUnit.assertEquals(loop, (int)updateExceedsTTLErr.count()); } } } // @Test public void testReactTimeoutMetric() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); //response timeout config URL url2 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "MetricNS2"); pConfig2.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoReactClient junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); for(int i=0; i<loop; i++){ byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); //Create operation, response timeout try{ junoReactClient2.create(key, data).block(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(25000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","ERROR").timer(); Thread.sleep(1500); Counter createRespTimeoutErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "CREATE").tag("status", "Response Timed out").tag("status", OperationStatus.ResponseTimeout.getErrorText()).counter(); Counter createEventErr = registry.find(JunoMetrics.ERROR_METRIC).tag("type", "JUNO_LATE_RESPONSE").tag("cause", "ERROR").counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(), 1); AssertJUnit.assertEquals(loop, (int)createEventErr.count()); AssertJUnit.assertEquals(loop, (int)createRespTimeoutErr.count()); } } } @Test public void testReactWrongIpPortMetric() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); //Wrong ip port test config URL url3 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig3 = new Properties(); pConfig3.load(url3.openStream()); pConfig3.setProperty(JunoProperties.APP_NAME, "QATestApp3"); pConfig3.setProperty(JunoProperties.RECORD_NAMESPACE, "MetricWrongIpPort"); pConfig3.setProperty(JunoProperties.HOST, "123.456.789.000"); pConfig3.setProperty(JunoProperties.PORT, "6080"); pConfig3.setProperty(JunoProperties.MAX_CONNECTION_POOL_SIZE, "200"); pConfig3.setProperty(JunoProperties.CONNECTION_POOL_SIZE, "200"); JunoReactClient junoReactClient3 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); for(int i=0; i<loop; i++){ byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); //Create operation, response timeout try{ junoReactClient3.create(key, data).block(); }catch (Exception e){ } Thread.sleep(300); } Thread.sleep(300); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("pool","123.456.789.000:6080").tag("status","ERROR").timer(); Counter createConnTimeoutOpStatusErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool", "123.456.789.000:6080").tag("type","CREATE").tag("status", "Connection Error").tag("status", OperationStatus.ConnectionError.getErrorText()).counter(); Counter createConnTimeoutEventErr = registry.find(JunoMetrics.CONNECT_METRIC).tag("endpoint","123.456.789.000:6080").tag("status", JunoMetrics.ERROR).tag("cause", "java.net.UnknownHostException").counter(); AssertJUnit.assertEquals(loop, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop, (int)createConnTimeoutOpStatusErr.count(),1); //1200 is related to the time, it does not related to numKeys or loop, it's ok as long as we see error AssertJUnit.assertEquals(1200, (int)createConnTimeoutEventErr.count(), 200); } } } @Test public void testReactDownIpPortMetrics() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); //Wrong ip port test config URL url3 = MetricTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig3 = new Properties(); pConfig3.load(url3.openStream()); pConfig3.setProperty(JunoProperties.APP_NAME, "QATestApp3"); pConfig3.setProperty(JunoProperties.RECORD_NAMESPACE, "MetricWrongIpPort"); pConfig3.setProperty(JunoProperties.HOST, "10.176.18.190"); pConfig3.setProperty(JunoProperties.PORT, "5080"); pConfig3.setProperty(JunoProperties.MAX_CONNECTION_POOL_SIZE, "200"); pConfig3.setProperty(JunoProperties.CONNECTION_POOL_SIZE, "200"); String ip3 = pConfig3.getProperty("juno.server.host"); String port3 = pConfig3.getProperty("juno.server.port"); JunoReactClient junoReactClient3 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); Thread.sleep(300); for(int i=0; i< 100; i++){ byte[] key = DataGenUtils.genBytes(25); byte[] data = DataGenUtils.genBytes(10); //Create operation, response timeout try{ junoReactClient3.create(key, data).block(); }catch (Exception e){ } Thread.sleep(100); } Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("pool","10.176.18.190:5080").tag("status","ERROR").timer(); //Timer createSuccessTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","CREATE").tag("status","SUCCESS").timer(); Counter createTimeoutOpStatusErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool", ip3+":"+port3).tag("type","CREATE").tag("status", "Connection Error").tag("status", OperationStatus.ConnectionError.getErrorText()).counter(); //System.out.println(" Create Success Count:"+createSuccessTimer.count()); AssertJUnit.assertEquals(100, (int)createTimer.count(),1); AssertJUnit.assertEquals(100, (int)createTimeoutOpStatusErr.count(),1); } } } @Test public void testReactBatchOperations() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 2047); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient.doBatch(createList).blockLast(); }catch (Exception e){ } //Get operation try{ junoReactClient.doBatch(getList).blockLast(); }catch (Exception e){ } //Set operation try{ junoReactClient.doBatch(setList).blockLast(); }catch (Exception e){ } //Update operation try{ junoReactClient.doBatch(updateList).blockLast(); }catch (Exception e){ } //Destroy operation try{ junoReactClient.doBatch(deleteList).blockLast(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(1000); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); AssertJUnit.assertEquals(loop*numKeys, createTimer.count(),10); AssertJUnit.assertEquals(loop*numKeys, getTimer.count(),10); AssertJUnit.assertEquals(loop*numKeys, setTimer.count(),10); AssertJUnit.assertEquals(loop*numKeys, updateTimer.count(),10); AssertJUnit.assertEquals(loop*numKeys, deleteTimer.count(),10); } } } @Test public void testReactZeroNullPayloadBatch() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = DataGenUtils.createKey(25); payload[i] = str.getBytes(); payload[5] = "".getBytes(); payload[19]=null; createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient.doBatch(createList).blockLast(); }catch (Exception e){ } //Get operation try{ junoReactClient.doBatch(getList).blockLast(); }catch (Exception e){ } //Set operation try{ junoReactClient.doBatch(setList).blockLast(); }catch (Exception e){ } //Update operation try{ junoReactClient.doBatch(updateList).blockLast(); }catch (Exception e){ } //Destroy operation try{ junoReactClient.doBatch(deleteList).blockLast(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); AssertJUnit.assertEquals(loop*numKeys, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)deleteTimer.count(),1); } } } @Test public void testReactMoreThan200PayloadBatch() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = DataGenUtils.createKey(25); payload[i] = DataGenUtils.genBytes(20); payload[numKeys-1] = DataGenUtils.genBytes(204801); createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient.doBatch(createList).blockLast(); }catch (Exception e){ } //Get operation try{ junoReactClient.doBatch(getList).blockLast(); }catch (Exception e){ } //Set operation try{ junoReactClient.doBatch(setList).blockLast(); }catch (Exception e){ } //Update operation try{ junoReactClient.doBatch(updateList).blockLast(); }catch (Exception e){ } //Destroy operation try{ junoReactClient.doBatch(deleteList).blockLast(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter createExceedsPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsPayloadErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "payload_size_exceeded").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*(numKeys-1), (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys-1), (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys-1), (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop, (int)createExceedsPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)updateExceedsPayloadErr.count()); AssertJUnit.assertEquals(loop, (int)setExceedsPayloadErr.count()); } } } @Test public void testReactTTLMoreThan3DaysBatch() throws IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); int numKeys = 20; long[] ttl = new long[numKeys]; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); payload[i] = DataGenUtils.genBytes(20); if ( i < 5 ) { ttl[i] = 100; } else { if ( i % 3 == 0 ) { ttl[i] = 0; } else if ( i % 3 == 1 ) { ttl[i] = -1; } else { ttl [i] = 259201; } } createList.add(new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create)); getList.add(new JunoRequest(key[i], 0, ttl[i], JunoRequest.OperationType.Get)); setList.add(new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Set)); updateList.add(new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Update)); deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); } for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient.doBatch(createList).blockLast(); }catch (Exception e){ } //Get operation try{ junoReactClient.doBatch(getList).blockLast(); }catch (Exception e){ } //Set operation try{ junoReactClient.doBatch(setList).blockLast(); }catch (Exception e){ } //Update operation try{ junoReactClient.doBatch(updateList).blockLast(); }catch (Exception e){ } //Destroy operation try{ junoReactClient.doBatch(deleteList).blockLast(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter createExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getExceedsTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("cause", "ttl_exceeded_max").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createInvalidTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getNegTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter createZeroTTLErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "invalid_ttl").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*5, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*10, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*10, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*10, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*numKeys, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop*5, (int)createExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)updateExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)setExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)getExceedsTTLErr.count()); AssertJUnit.assertEquals(loop*5*2, (int)createInvalidTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)updateNegTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)setNegTTLErr.count()); AssertJUnit.assertEquals(loop*5, (int)getNegTTLErr.count()); } } } @Test public void testReactZeroNullKeyBatch() throws IOException, InterruptedException { int numKeys = 20; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> createList = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); List<JunoRequest> setList = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); List<JunoRequest> deleteList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { payload[i] = DataGenUtils.createKey(10).getBytes(); if ( i <= 1 ) { key[i] = DataGenUtils.createKey(25).getBytes(); } else { if ( i % 2 == 0 ) { key[i] = "".getBytes(); } else { key[i] = null; } } try{ createList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create)); }catch (Exception e) { } try { getList.add(new JunoRequest(key[i], 0, 100, JunoRequest.OperationType.Get)); }catch (Exception e) { } try { setList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Set)); }catch (Exception e) { } try { updateList.add(new JunoRequest(key[i], payload[i], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Update)); }catch (Exception e) { } try { deleteList.add(new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy)); }catch (Exception e) { } } for(int i=0; i<loop; i++){ //Create operation try{ junoReactClient.doBatch(createList).blockLast(); }catch (Exception e){ } //Get operation try{ junoReactClient.doBatch(getList).blockLast(); }catch (Exception e){ } //Set operation try{ junoReactClient.doBatch(setList).blockLast(); }catch (Exception e){ } //Update operation try{ junoReactClient.doBatch(updateList).blockLast(); }catch (Exception e){ } //Destroy operation try{ junoReactClient.doBatch(deleteList).blockLast(); }catch (Exception e){ } Thread.sleep(100); } Thread.sleep(1500); Iterator<MeterRegistry> registryIterator = Metrics.globalRegistry.getRegistries().iterator(); while(registryIterator.hasNext()){ MeterRegistry registry = registryIterator.next(); if(registry instanceof SimpleMeterRegistry){ Timer createTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_CREATE").tag("status","SUCCESS").timer(); Timer getTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_GET").tag("status","SUCCESS").timer(); Timer setTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_SET").tag("status","SUCCESS").timer(); Timer updateTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_UPDATE").tag("status","SUCCESS").timer(); Timer deleteTimer = registry.find(JunoMetrics.JUNO_LATENCY_METRIC).tag("operation","B_DESTROY").tag("status","SUCCESS").timer(); Counter createErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_CREATE").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter setErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_SET").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter updateErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_UPDATE").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter getErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_GET").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); Counter destroyErr = registry.find(JunoMetrics.JUNO_OPERATION_METRIC).tag("pool",ip+":"+port).tag("type", "B_DESTROY").tag("status", "Illegal argument").tag("cause", "null_or_empty_key").tag("status", OperationStatus.IllegalArgument.getErrorText()).counter(); AssertJUnit.assertEquals(loop*2, (int)createTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)getTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)setTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)updateTimer.count(),1); AssertJUnit.assertEquals(loop*2, (int)deleteTimer.count(),1); AssertJUnit.assertEquals(loop*(numKeys-2), (int)createErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)getErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)setErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)updateErr.count()); AssertJUnit.assertEquals(loop*(numKeys-2), (int)destroyErr.count()); } } } }
73
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchReactCreateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xerial.snappy.Snappy; public class BatchReactCreateTest{ private JunoReactClient junoActClient; private JunoReactClient junoReactClient; private JunoReactClient junoReactClient3; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Properties pConfig3; private enum syncFlag {reactAsync, reactSync}; private int flag; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchCreateTest.class); URL url = BatchCreateTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); LOGGER.debug("Read syncFlag"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); flag = Integer.parseInt(sync_flag.trim()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); URL url2 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); pConfig3 = new Properties(); pConfig3.load(url2.openStream()); pConfig3.setProperty(JunoProperties.ENABLE_RETRY, "true"); pConfig3.setProperty(JunoProperties.RESPONSE_TIMEOUT, "10"); try{ junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoActClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); junoReactClient3 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); } catch (Exception e ){ throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } @Test public void testBatchRetry() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 50; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); payload[i] = DataGenUtils.createKey(1024).getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, 180, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoReactClient3.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoReactClient3, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertTrue (OperationStatus.Success.getCode() == mResponse.getStatus().getCode() || OperationStatus.ResponseTimeout.getCode() == mResponse.getStatus().getCode()); if (OperationStatus.Success.getCode() == mResponse.getStatus().getCode()) { AssertJUnit.assertTrue(1 == mResponse.getVersion()); } } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } } /** * Create and get multiple keys using batch create * @throws JunoException */ @Test public void testBatchCreate() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); key[numKeys-1] = DataGenUtils.createKey(128).getBytes(); payload[numKeys-1] = DataGenUtils.createKey(204700).getBytes(); ttl[numKeys-1] = 100; hmap.put(new String(key[numKeys-1]), payload[numKeys-1]); hmapTTL.put(new String(key[numKeys-1]), String.valueOf(ttl[numKeys-1])); JunoRequest item = new JunoRequest(key[numKeys-1], payload[numKeys-1], (long)0, 100, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); Random r = new Random(); for (int i = 0; i < numKeys-1; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); int payloadlen = DataGenUtils.rand(r, 200, 204700); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); ttl[i] = 100; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call LOGGER.debug("come into sync batch create"); batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call LOGGER.debug("come into async batch create"); batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { String mKey=new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals (hmapTTL.get(mKey), String.valueOf(mResponse.getTtl())); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); for (int i = 0; i < numKeys; i ++) { item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } Iterable<JunoResponse> getBatchResp = null; try { LOGGER.debug("before blocking mode batch get " + System.currentTimeMillis()); if (syncFlag.reactSync.ordinal() == flag) { //sync react call LOGGER.debug("come into sync batch create"); getBatchResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call LOGGER.debug("come into async batch get"); getBatchResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } LOGGER.debug("after batch get " + System.currentTimeMillis()); int i = 0; for (JunoResponse response: getBatchResp) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey))-16 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); AssertJUnit.assertEquals (new String(hmap.get(mkey)), new String(response.getValue())); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException ex) { LOGGER.debug("Exception occured:" + ex.getMessage() ); AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with 1 key duplicated * Verify the batch create give correct errror for duplicated key * Verify other keys are successful * @throws JunoException */ @Test public void testBatchCreateDuplicateKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Create a key first "); byte[] new_key = DataGenUtils.createKey(64).getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse resp = junoReactClient.create(new_key,data).block(); AssertJUnit.assertEquals (OperationStatus.Success, resp.getStatus()); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with key 7 a duplicated key"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, Integer> hmapVersion = new HashMap<String, Integer>(); HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(20).getBytes(); key[7] = new_key; hmapStatus.put (new String(key[i]), OperationStatus.Success ); hmapStatus.put (new String(key[7]), OperationStatus.UniqueKeyViolation); hmapVersion.put(new String(key[i]), 1); hmapVersion.put(new String(key[7]), 0); String str = "Hello Testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; //Expected status; hmap.put(new String(key[i]), payload[i]); hmap.put(new String(key[7]),data); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoReactClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } int j=0; for (JunoResponse mResponse: batchResp) { String mKey=new String(mResponse.getKey()); AssertJUnit.assertEquals (hmapStatus.get(mKey), mResponse.getStatus()); AssertJUnit.assertEquals ((long)hmapVersion.get(mKey), mResponse.getVersion()); j++; } AssertJUnit.assertEquals(j, numKeys); } catch (JunoException mex) { //LOGGER.debug("Error code: " + mex.getOperationStatus().getCode()); LOGGER.debug("Exception occurs: " + mex.getMessage()); } LOGGER.debug("\n===Batch Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getResp = null; for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } if (syncFlag.reactSync.ordinal() == flag) { //sync react call getResp = junoReactClient.doBatch(list1).toIterable(); } else { //async react call getResp = BatchReactSubscriber.async_dobatch(junoReactClient, list1); } int j=0; for (JunoResponse mResponse: getResp) { String mKey=new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue (1 == mResponse.getVersion()); AssertJUnit.assertEquals(hmap.get(mKey), mResponse.getValue()); j++; } AssertJUnit.assertEquals(j, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with 1 empty key * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateEmptyKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with one zero-length key"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(127).getBytes(); key[4] = "".getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try{ Iterable<JunoResponse> batchResp; LOGGER.error( "\n===Batch Create is sent "); if (syncFlag.reactSync.ordinal() == flag) { batchResp=junoActClient.doBatch(list).toIterable(); } else { batchResp=BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with 2 NULL keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[3] = null; key[9] = null; String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try{ Iterable<JunoResponse> batchResp; LOGGER.error( "\n===Batch Create is sent "); if (syncFlag.reactSync.ordinal() == flag) { batchResp=junoActClient.doBatch(list).toIterable(); } else { batchResp=BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with keys >=257 keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreate129BytesKeys() throws JunoException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with more than 1 key >= 129 bytes"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long> (); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(128).getBytes(); key[9] = DataGenUtils.createKey(129).getBytes(); payload[i] = DataGenUtils.createKey(30).getBytes(); ttl[i] = 20; hmap.put(new String(key[i]),payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable <JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse response: resp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[9]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); i++; } } AssertJUnit.assertEquals(i, numKeys-1); //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[9]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with keys having 0 or null payload * Verify JunoException does not throw * @throws JunoException */ @Test public void testBatchCreateZeroPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with some keys having zero payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; ArrayList <JunoRequest> list = new ArrayList <JunoRequest>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); payload[5] = "".getBytes(); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { int i = 0; Iterable <JunoResponse> resp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse mResponse: resp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not throw for zero payload", false); } ArrayList <JunoRequest> list1 = new ArrayList<JunoRequest>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); LOGGER.debug("value get is " + new String(response.getValue())); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } AssertJUnit.assertEquals(i, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (Exception ex) { AssertJUnit.assertTrue(false); } } /** * Create batch keys with keys having 0 or null payload * Verify JunoException does not throw * @throws JunoException */ @Test public void testBatchCreateNullPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with some keys having null payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap <String, Long> hmapTTL = new HashMap<String, Long>(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); payload[0] = null; payload[4] = "".getBytes(); ttl[i] = 20; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable <JunoResponse> batchResp = null; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue("batch create for one item null payload shouldn't fail", false); } int i = 0; for (JunoResponse response: batchResp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); i++; } } AssertJUnit.assertEquals(i, numKeys-1); //Batch Get ArrayList <JunoRequest> list1 = new ArrayList<JunoRequest>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3); i++; } } AssertJUnit.assertEquals(i, numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with a key having > 200KB payload * Verify JunoException does not throw * @throws JunoException */ @Test public void testBatchCreateMoreThan200KPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with a key having > 200KB payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.genBytes(30); byte[] data = DataGenUtils.genBytes(204801); payload[8] = data; ttl[i] = 20; LOGGER.debug("key " + i + " is " + new String(key[i])); hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { Iterable <JunoResponse> resp = null; resp = BatchReactSubscriber.async_dobatch(junoActClient, list); for (JunoResponse mResponse: resp) { String mkey = new String(mResponse.getKey()); if ( mkey.equals(new String(key[8]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); }else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); } } } catch (Exception mex) { AssertJUnit.assertTrue("batch create shouldn't fail", false); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[8]))) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with a key having TTL more than 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateTTLmorethan3days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > lifetime > 3 days"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap<String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.createKey(40).getBytes(); ttl[i] = 20; ttl[1] = 259201; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); LOGGER.error( " added ttl " + ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); LOGGER.error( " added ttl " + ttl[i]); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { int i=0; Iterable <JunoResponse> resp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse mResponse: resp) { String mkey = new String(mResponse.getKey()); if ( mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); } else { //System.out.println("Record version:"+mResponse.getVersion()); //AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for one item exceeds max lifetime", false); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with different TTL and payload * This test is used to test connection error * @throws JunoException */ @Test public void testBatchCreateDiffLifeTimePayloads(){ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); LOGGER.debug("ttl1: " + ttl1); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 2048)); payload[5] = DataGenUtils.genBytes(500); ttl[i] = DataGenUtils.rand(r, 200, 8600); ttl[5] = 800; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue (i == numKeys); } catch (JunoException mex) { //LOGGER.debug(String.valueOf(mex.getOperationStatus().getCode())); //LOGGER.debug(mex.getOperationStatus().getErrorText()); //LOGGER.debug(mex.getOperationStatus().name()); LOGGER.debug("Exception: " + mex.getMessage()); AssertJUnit.assertTrue (false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } try { Iterable<JunoResponse> getBatchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey))-10 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); } LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { AssertJUnit.assertTrue (false); } } /** * Create batch keys without TTL * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask is there anyway to passin default TTL */ @Test public void testBatchCreateNoLifeTime() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; HashMap<String, Long> hmapTTL = new HashMap<String, Long>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); payload[5] = DataGenUtils.genBytes(204800); ttl[i]=100; ttl[8] = 0; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } Iterable<JunoResponse> batchResp = null; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue("create without 0 ttl for one item shouldn't fail", false); } int i = 0; for (JunoResponse response: batchResp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[8]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); i++; } } AssertJUnit.assertEquals(i, numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch create"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> batchResp = null; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); LOGGER.info("0"); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); //AssertJUnit.assertTrue(OperationStatus.IllegalArgument == mex.getOperationStatus()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys, many params passed to Juno Request Item list * Verify keys are created successfully * @throws JunoException */ @Test public void testBatchCreateManyParams() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap <String, String> hmapTTL = new HashMap <String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); LOGGER.debug("ttl1: " + ttl1); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 2048)); payload[5] = DataGenUtils.genBytes(5000); ttl[i] = DataGenUtils.rand(r, 200, 86400); ttl[5] = 259200; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); //Passing version in the Juno Request Item list JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key" + i + ": "+ mResponse.getKey()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue ( i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue (false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey)) - 10 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Check response Timeout exception * @throws JunoException */ //@Test public void testBatchCreateResponseTimeout() throws IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url1 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); pConfig1.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoReactClient junoReactClient1 = null; try { junoReactClient1 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } int numKeys = 100; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(204800); ttl[i] = DataGenUtils.rand(r, 200, 86400); ttl[5] = 259200; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable <JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoReactClient1.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoReactClient1, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.ResponseTimeout,mResponse.getStatus()); i++; } AssertJUnit.assertTrue ( i == numKeys); } catch (JunoException mex) { //mex.printStackTrace(); AssertJUnit.assertTrue(false); LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Response Timed out")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Check Connection Timeout exception * @throws JunoException */ //@Test public void testBatchCreateConnectionError() throws IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url1 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); pConfig1.setProperty(JunoProperties.CONNECTION_TIMEOUT, "1"); JunoReactClient junoReactClient1 = null; try { junoReactClient1 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } int numKeys = 100; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); payload[i] = DataGenUtils.genBytes(204000); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)20, JunoRequest.OperationType.Create); list.add(item); } try { Iterable <JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoReactClient1.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoReactClient1, list); } AssertJUnit.assertTrue("Connection Error Exception not happening", false); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("connection timed out")); } } /** * This is negative test case only enable when junoserv config and juno property set to * allow 10M payload and we'd like to see how large payload batch behave * Verify appropriate JunoException is thrown * @throws JunoException */ //@Test public void testBatchCreateMoreThan8MPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with a key having > 8MB payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.genBytes(30); byte[] data = DataGenUtils.genBytes(88480100); payload[8] = data; ttl[i] = 20; LOGGER.debug("key " + i + " is " + new String(key[i])); hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { Iterable <JunoResponse> resp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } } catch (Exception mex) { LOGGER.debug("Exception occured: batch create fail due to large payload"); AssertJUnit.assertTrue("batch create shouldn't fail", true); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[8]))) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { LOGGER.debug("Exception occured: batch get fail due to large payload?, shouldn't"); AssertJUnit.assertTrue(false); LOGGER.info("2"); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch and update with compressed payload larger than max 2048000 * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateExceedsCompressMax() throws Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, String> hmapTTL2 = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Set"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); payload[5] = DataGenUtils.createCompressablePayload(100000).getBytes(); ttl[i]=1200; hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mKey)) - 10 <= mResponse.getTtl() && mResponse.getTtl() <= Integer.parseInt(hmapTTL.get(mKey))); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); String str = "Update Hello Testing, Happy Friday" + i; upayload[i] = str.getBytes(); if (i == 6) { upayload[i] = DataGenUtils.createCompressablePayload(800000).getBytes(); } ttl[i] = 1200; hmap.put(new String(key[i]), upayload[i]); hmapTTL2.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest uitem = new JunoRequest(key[i], upayload[i], (long)1, ttl[i], JunoRequest.OperationType.Update); ulist.add(uitem); } int dataLength = Snappy.compress(upayload[6]).length; LOGGER.info("upayload6 original length is " + upayload[6].length + "compressed length is " + dataLength); Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(ulist).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, ulist); } for (JunoResponse mResponse: batchResp) { String mKey=new String(mResponse.getKey()); String upayloadStr = new String(upayload[6]); String mkeyStr = new String(hmap.get(mKey)); if ( new String(hmap.get(mKey)).equals(new String(upayload[6])) ) { LOGGER.info("enter into if, value is " + upayloadStr.length() + ", payload6 is " + mkeyStr.length()); AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); LOGGER.info("2"); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals (hmapTTL2.get(mKey), String.valueOf(mResponse.getTtl())); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.info("0"); } } LOGGER.info("Completed"); } }
74
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchUpdateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import rx.observables.BlockingObservable; public class BatchUpdateTest{ private JunoAsyncClient junoClient; private JunoAsyncClient asyncJunoClient; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig2; private Logger LOGGER; private int syncFlag; @BeforeClass public void setup() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER = LoggerFactory.getLogger(BatchUpdateTest.class); URL url = BatchUpdateTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); LOGGER.debug("Read syncFlag test to findout what needs to be run"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); junoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); asyncJunoClient = JunoClientFactory.newJunoAsyncClient(url); URL url2 = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Batch Create and Batch Update to update lifetime and payload * @throws JunoException */ @Test public void testBatchUpdatePayloadLifetime() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, Long> hmapVersion = new HashMap<String, Long>(); HashMap<String, String> hmapTTL2 = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Set"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i]=50; hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion() || 2 == mResponse.getVersion()); hmapVersion.put(mKey, mResponse.getVersion()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mKey)) - 5 <= mResponse.getTtl() && mResponse.getTtl() <= Integer.parseInt(hmapTTL.get(mKey))); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); upayload[i] = DataGenUtils.createKey(payloadlen).getBytes(); upayload[numKeys-1] = DataGenUtils.createKey(204800).getBytes(); ttl[i] = 100; hmap.put(new String(key[i]), upayload[i]); hmapTTL2.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest uitem = new JunoRequest(key[i], upayload[i], hmapVersion.get(new String(key[i])), ttl[i], JunoRequest.OperationType.Update); ulist.add(uitem); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(ulist).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, ulist); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is thrown for batch update", false); } LOGGER.debug("Get key using exisitng exising Juno read()"); for (int i = 0; i < numKeys; i ++) { JunoResponse junoResponse = junoClient2.get(key[i]); String mKey = new String(junoResponse.getKey()); AssertJUnit.assertEquals(key[i], junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion() || 3 == junoResponse.getVersion() || 4 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(upayload[i]), new String(junoResponse.getValue())); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL2.get(mKey)) - 10 <= junoResponse.getTtl() && junoResponse.getTtl() <= Integer.parseInt(hmapTTL2.get(mKey))); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Verify appropriate JunoException is thrown when doing Batch Update with a key having zero length * @throws JunoException */ @Test public void testBatchUpdateEmptyKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create request item with 1 key having zero length"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 1028)); key[4] = "".getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); JunoRequest updateItem = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Update); list.add(item); updateList.add(updateItem); } try{ Iterable<JunoResponse> batchResp; LOGGER.debug("Update " + numKeys + " keys using batch Set first"); if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try{ Iterable<JunoResponse> updateResp; LOGGER.debug("Update " + numKeys + " keys using batch update"); if (syncFlag == 1) { updateResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { updateResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: updateResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(2, response.getVersion()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with 2 NULL keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; key[3] = null; key[9] = "".getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); JunoRequest updateItem = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list.add(item); updateList.add(updateItem); } try { Iterable<JunoResponse> batchResp; LOGGER.debug("\n===Batch Set is sent "); if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try { Iterable<JunoResponse> updateResp; LOGGER.debug("\n===Batch Update is sent "); if (syncFlag == 1) { updateResp=junoClient.doBatch(updateList).toBlocking().toIterable(); } else { updateResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, updateList); } for (JunoResponse response: updateResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys with keys >=257 keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdate257BytesKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with more than 1 key >= 257 bytes"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(256).getBytes(); key[1] = DataGenUtils.createKey(259).getBytes(); key[4] = DataGenUtils.createKey(127).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i],System.currentTimeMillis(), JunoRequest.OperationType.Update); list.add(item); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for key with > 256 key length happened for only one item", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[4])) ) { AssertJUnit.assertEquals(OperationStatus.NoKey,response.getStatus()); } else { AssertJUnit.assertTrue(OperationStatus.IllegalArgument == response.getStatus()); } i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys with keys having 0 or null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateZeroPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 6; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long ttl[] = new long[numKeys]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 50; JunoRequest item = new JunoRequest(key[i], payload[i],(long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> batchResp = junoClient.doBatch(list).toBlocking().toIterable(); LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); if (syncFlag == 1) { BlockingObservable<JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } List<JunoRequest> list1 = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { String str = "New Hello Testing testing " + i; payload[i] = str.getBytes(); payload[5] = "".getBytes(); hmap.put(new String(key[i]), payload[i]); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)1, (long)0, JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); if (syncFlag == 1) { BlockingObservable<JunoResponse> resp = junoClient.doBatch(list1).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } List<JunoRequest> list2 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item2 = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list2.add(item2); } Iterable <JunoResponse> getBatchResponse; if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(list2).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, list2); } int j = 0; for (JunoResponse response: getBatchResponse) { byte[] mkey=response.getKey(); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(new String(mkey)), response.getValue()); j++; } AssertJUnit.assertEquals(j, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Update batch keys with keys having null payload * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask if 0 can be considered as default ttl */ @Test public void testBatchUpdateNullPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 50; hmap.put(new String(key[i]), payload[i]); LOGGER.debug("key " + i + " is " + new String(key[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "New Hello Testing testing " + i; payload[i] = str.getBytes(); payload[2] = null; payload[4] = null; ttl[i] = 20; if ( i != 2 && i != 4) { hmap.put(new String(key[i]), payload[i]); } JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list1).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for null payload happened only for one item", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); if ( mkey.equals(new String(key[2])) || mkey.equals(new String(key[4])) ) { AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals ( 0, response.getValue().length); } else { LOGGER.debug("mkey is " + mkey + " version is " + response.getVersion()); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); } i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys with keys having > 200KB payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateMoreThan200KPayLoad() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i]=30; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "New Hello Testing testing " + i; payload[i] = str.getBytes(); byte[] data = DataGenUtils.genBytes(204801); payload[3] = data; ttl[i]=50; hmapTTL.put(new String(key[i]), ttl[i]); hmapTTL.put(new String(key[3]), (long)30); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list1).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for > 200K payload happened only on one item", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); if ( mkey.equals(new String(key[3])) ) { AssertJUnit.assertTrue(1 == response.getVersion()); } else { LOGGER.debug("mkey is " + mkey + " version is " + response.getVersion()); AssertJUnit.assertTrue(2 == response.getVersion()); } AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= response.getTtl()-5); i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys TTL > 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateMoreThan3Days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = (i + 11) * 2; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "New Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 100; ttl[0] = 259201; if ( i != 0 ) { hmapTTL.put(new String(key[i]), ttl[i]); } JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)1, ttl[i], JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list1).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for TTL > 3days happened on one item ", false); } //Batch Get ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); if ( mkey.equals(new String(key[0])) ) { AssertJUnit.assertTrue(1 == response.getVersion()); } else { AssertJUnit.assertTrue(2 == response.getVersion()); } AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= response.getTtl()-5); i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create and get multiple keys using batch create * @throws JunoException //TODO: so updte with empty lifetime is fine? */ @Test public void testBatchUpdateNoLifetime() throws JunoException , InterruptedException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; Long[] ttl = new Long[numKeys]; long[] updatettl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using existing Juno Create"); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = 9L; JunoResponse mResponse = junoClient2.create(key[i], payload[i], ttl[i]); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys without lifetime using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday! Testing again" + i; upayload[i] = str.getBytes(); hmap.put(new String(key[i]), upayload[i]); JunoRequest uitem = new JunoRequest(key[i], upayload[i], (long)1, updatettl[i], JunoRequest.OperationType.Update); ulist.add(uitem); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(ulist).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, ulist); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.debug("ttl for item " + i + " is " + mResponse.getTtl()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch update", false); } Thread.sleep (5000); LOGGER.debug("Get key using existing Juno read(), keys still exist"); for (int i = 0; i < numKeys; i ++) { try { JunoResponse junoResponse = junoClient2.get(key[i]); AssertJUnit.assertEquals(key[i], junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(upayload[i]), new String(junoResponse.getValue())); } catch (JunoException ex) { LOGGER.debug("Exception occured at get " + ex.getMessage()); } } LOGGER.debug("Sleep for keys to expire"); Thread.sleep (10000); for (int i = 0; i < numKeys; i ++) { try { JunoResponse response = junoClient2.get(key[i]); } catch (JunoException mex) { LOGGER.debug("why exception occured here? " + mex.getMessage()); } } List<JunoRequest> glist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest gitem = new JunoRequest(key[i], upayload[i], (long)1, updatettl[i], JunoRequest.OperationType.Update); glist.add(gitem); } Iterable<JunoResponse> getBatchResponse; if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(glist).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, glist); } int i = 0; for (JunoResponse response: getBatchResponse) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update on non existing keys * Verify batch update returns correct status for non-key * @throws JunoException */ @Test public void testBatchUpdateKeyNotExists() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; byte[][] upayload = new byte[numKeys][]; long ttl[] = new long[numKeys]; HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); Random r = new Random(); LOGGER.debug("Create request items and create keys"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 100)); ttl[i] = 30; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue( i == numKeys); }catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } //Juno Request Item for update List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[3] = "12345".getBytes(); hmapStatus.put(new String(key[i]), OperationStatus.Success); hmapStatus.put(new String(key[3]), OperationStatus.NoKey); upayload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 20)); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)1, (long)0, JunoRequest.OperationType.Update); list1.add(item1); } try { LOGGER.debug("Update " + numKeys + " keys with version 0 using batch Update"); Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); AssertJUnit.assertEquals (hmapStatus.get(mkey), mResponse.getStatus()); if (mResponse.getStatus() == OperationStatus.Success) { AssertJUnit.assertTrue(2 == mResponse.getVersion()); } } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update with version = 0 * Verify batch update is successful and return the next version * @throws JunoException //TODO: TTL 0 for set is allowable and will set default ttl 3600? * //TODO: so update does not have response value back? */ @Test public void testBatchUpdateVersion0() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; byte[][] upayload = new byte[numKeys][]; HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); int[] version = new int [numKeys]; Random r = new Random(); LOGGER.debug("Create request item and create items using batch create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 100)); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp= null; batchResp = junoClient.doBatch(list).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); }catch (JunoException mex) { AssertJUnit.assertTrue(false); } //Juno Request Item for update List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { version[i] = 0; upayload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 20)); hmap.put(new String(key[i]), upayload[i]); JunoRequest item1 = new JunoRequest(key[i], upayload[i], version[0], (long)0, JunoRequest.OperationType.Update); list1.add(item1); } try { LOGGER.debug("Update " + numKeys + " keys with version 0 using batch Update"); Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertTrue(1800 - 8 <= mResponse.getTtl() && mResponse.getTtl() <= 1800); } } catch (JunoException mex) { AssertJUnit.assertTrue(false); } List<JunoRequest> list2 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list2.add(item); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list2).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list2); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertEquals (hmap.get(mKey), mResponse.getValue()); LOGGER.debug("ttl of " + mKey + " is " + mResponse.getTtl()); AssertJUnit.assertTrue(1800 - 11 <= mResponse.getTtl() && mResponse.getTtl() <= 1800); } } catch (JunoException mex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update with version < current version * Verify batch update is successful and return the next version * @throws JunoException //TODO: check with Stephane should version update behave like that? * //TODO: check with Joseph, update seems just ignore the pass in version number but 1?? * //ask update doesn't get value back? * */ @Test public void testBatchUpdateInvalidVersion() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; byte[][] upayload = new byte[numKeys][]; byte[][] udate_payload = new byte[numKeys][]; int[] version = new int [numKeys]; long[] ttl = new long [numKeys]; for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = 20L; JunoResponse mResponse = junoClient2.create(key[i], payload[i], ttl[i]); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } LOGGER.debug("Calling batch update to update keys without passing version"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday, Try again" + i; upayload[i] = str.getBytes(); version[i] = 5; JunoRequest item1 = new JunoRequest(key[i], upayload[i], version[i], (long)0, JunoRequest.OperationType.Update); list1.add(item1); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); LOGGER.debug("version is " + mResponse.getVersion()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); } } catch (JunoException mex) { LOGGER.debug("Exception occurs for update without version passing: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.debug("Calling batch update to update keys, some having invalid version"); List<JunoRequest> list2 = new ArrayList<>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday, Try again. Have a good weekend" + i; udate_payload[i] = str.getBytes(); ttl[i] = 30; version[i] = 6; //next version should be 7 version[3] = 4; version[4] = 0; //OK version[5] = -1; //OK version[6] = 65535; //OK version[7] = 1; hmapStatus.put(new String(key[i]), OperationStatus.Success); hmapStatus.put(new String(key[7]), OperationStatus.ConditionViolation); hmap.put(new String(key[i]), udate_payload[i]); hmap.put(new String(key[7]), upayload[7]); JunoRequest item2 = new JunoRequest(key[i], udate_payload[i], version[i], ttl[i], JunoRequest.OperationType.Update); list2.add(item2); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list2).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); LOGGER.debug("=======Status: for " + mkey + " is " + mResponse.getStatus() + " - Version: " + mResponse.getVersion()); AssertJUnit.assertEquals(hmapStatus.get(mkey), mResponse.getStatus()); if (mResponse.getStatus() == OperationStatus.Success) { AssertJUnit.assertTrue(3 == mResponse.getVersion()); i++; } } AssertJUnit.assertTrue ( i == numKeys - 1); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } List<JunoRequest> list3 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list3.add(item); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list3).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); AssertJUnit.assertEquals (new String (hmap.get(mkey)), new String (mResponse.getValue())); i++; } AssertJUnit.assertTrue ( i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: aost realsed */ //@Test public void testBatchUpdateZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch Update"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag == 1) { junoClient.doBatch(list).toBlocking().toIterable(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Batch Create and Batch Update to update lifetime and payload * @throws JunoException */ @Test public void testBatchUpdatePayloadLifetimeVersion() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); //int numKeys = 100; int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; long[]creationTime = new long[numKeys]; long[]getTime = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Set"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); creationTime[i] = System.currentTimeMillis(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday! Testing again" + i; upayload[i] = str.getBytes(); ttl[i] = 100; hmap.put(new String(key[i]), upayload[i]); JunoResponse gResponse = junoClient2.get(key[i]); AssertJUnit.assertEquals (OperationStatus.Success,gResponse.getStatus()); JunoRequest uitem = new JunoRequest(key[i], upayload[i], ttl[i], gResponse.getVersion(), JunoRequest.OperationType.Update); ulist.add(uitem); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(ulist).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, ulist); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch update", false); } LOGGER.debug("Get key using existing Juno read()"); for (int i = 0; i < numKeys; i ++) { getTime[i] = System.currentTimeMillis(); JunoResponse junoResponse = junoClient2.get(key[i]); AssertJUnit.assertEquals(key[i], junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(upayload[i]), new String(junoResponse.getValue())); AssertJUnit.assertTrue(1800 - ((getTime[i] - creationTime[i])/1000)-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= 1800 -((getTime[i]-creationTime[i])/1000)); } LOGGER.info("0"); LOGGER.info("Completed"); } }
75
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchGetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BatchGetTest{ private JunoAsyncClient junoClient; private JunoAsyncClient asyncJunoClient; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; private int syncFlag; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchGetTest.class); URL url = BatchGetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); LOGGER.debug("Read syncFlag test to findout what needs to be run"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); URL url1 = BatchGetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); URL url2 = BatchGetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); try { junoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); asyncJunoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); } catch (Exception e){ throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Create and get multiple keys * @throws JunoException */ @Test public void testBatchGet() throws JunoException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[numKeys-1] = DataGenUtils.createKey(20).getBytes(); LOGGER.debug("key" + i + " is " + new String(key[i])); payload[i] = DataGenUtils.createKey(100).getBytes();; payload[9] = DataGenUtils.createKey(204800).getBytes(); ttl[i] = 200; ttl[6] = 259200; hmap.put(new String(key[i]), payload[i]); long createTime = System.currentTimeMillis(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i],createTime, JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is thrown for batch Create", false); } List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item; LOGGER.debug("key " + i + " at get is " + new String(key[i])); item = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list1.add(item); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create and get multiple keys with two keys expired * @throws JunoException */ @Test public void testBatchGetExpiredRecord() throws JunoException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing " + i; payload[i] = str.getBytes(); ttl[i] = 20000; ttl[3] = 3; ttl[8] = 4; hmap.put(new String(key[i]), payload[i]); long createTime = System.currentTimeMillis(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i],createTime, JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 1; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch Create", false); } LOGGER.debug("Sleep for key to expire"); Thread.sleep (5000); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list1.add(item); } LOGGER.debug("Read " + numKeys + " keys using batch Get(), no lifetime"); Iterable<JunoResponse> getBatchResp = null; if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); if (mkey.equals (new String(key[3])) || mkey.equals(new String(key[8]))) { LOGGER.debug("Check for key to expire"); if (response.getStatus() != OperationStatus.NoKey ) { AssertJUnit.assertTrue ("Key not expired", false); } else { LOGGER.debug("Key expired as expected"); } } else { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Get batch keys with lifetime extended * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testGetWithLifeTimeExtented() throws JunoException, InterruptedException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = 4; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int j = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + j + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertTrue(ttl[j] == mResponse.getTtl()); j++; } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); } List<JunoRequest> list1 = new ArrayList<>(); LOGGER.debug("Set and passing lifetime, some will have lifetime 0 passing"); for (int i = 0; i < numKeys; i ++) { ttl[i] = 0; ttl[2] = 30; ttl[9] = 20; hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); LOGGER.debug("Key: " + key[i]); JunoRequest item1 = new JunoRequest(key[i], null, 0, ttl[i], JunoRequest.OperationType.Get); list1.add(item1); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } Thread.sleep (5000); //Most keys will expired LOGGER.debug("Verify keys have lifetime=0 passing are expired"); Iterable<JunoResponse> getBatchResp1 = junoClient.doBatch(list1).toBlocking().toIterable(); for (JunoResponse response: getBatchResp1) { String mkey = new String(response.getKey()); if (!mkey.equals (new String(key[2])) && !mkey.equals(new String(key[9]))) { if (response.getStatus() != OperationStatus.NoKey ) { AssertJUnit.assertTrue ("Key not expired", false); } else { LOGGER.debug("Key expired as expected"); } } else { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmapTTL.get(mkey), String.valueOf(response.getTtl())); } } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Verify appropriate JunoException is thrown when getting a key with zero length * @throws JunoException */ @Test public void testBatchGetEmptyKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with 1 key having zero length"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); key[9] = "".getBytes(); ttl[i]=10; payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); JunoRequest getItem = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Get); list.add(item); getList.add(getItem); } try{ Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try { Iterable<JunoResponse> getResp; LOGGER.debug("\n===Batch Get is sent "); if (syncFlag == 1) { getResp=junoClient.doBatch(getList).toBlocking().toIterable(); } else { getResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } for (JunoResponse response: getResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Verify appropriate JunoException is thrown when keys not exist * @throws JunoException //TODO: check So we will still have key info in response even we didn't insert at all? */ @Test public void testBatchGetNotExist() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 4; long[] ttl = new long[numKeys]; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create 2 keys using Existing Juno Sync Client"); LOGGER.debug("Two keys are created with NS1, two key created with different Namespace"); key[0] = "56789".getBytes(); //key not exist in Juno key[1] = DataGenUtils.createKey(20).getBytes(); key[2] = "23456".getBytes(); //key not exist in Juno key[3] = DataGenUtils.createKey(10).getBytes(); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); payload[1] = data; payload[3] = data1; payload[0] = data1; payload[2] = data1; for (int i = 0; i < numKeys; i ++) { ttl[i]=(long)20; LOGGER.debug("initial key " + i + "put is " + new String(key[i])); } junoClient1.delete("23456".getBytes()); junoClient1.delete("56789".getBytes()); try { Thread.sleep(2000); } catch (Exception ex) { LOGGER.debug(ex.getMessage()); } try { junoClient2.create(key[1], payload[1], ttl[1]); junoClient2.create(key[3], payload[3], ttl[3]); junoClient1.create(key[0], payload[0]); junoClient1.create(key[2], payload[2]); } catch (JunoException ex) { AssertJUnit.assertEquals("shouldn't come here ", false); } LOGGER.debug("Create Juno request items "); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { hmapStatus.put(new String(key[i]), OperationStatus.Success); hmapStatus.put(new String(key[0]), OperationStatus.NoKey); hmapStatus.put(new String(key[2]), OperationStatus.NoKey); hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); LOGGER.info("hmapstatus key " + i + "is " + new String(key[i])); JunoRequest item = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list.add(item); } Iterable<JunoResponse> getBatchResp1 = null; if (syncFlag == 1) { getBatchResp1 = junoClient.doBatch(list).toBlocking().toIterable(); } else { getBatchResp1 = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: getBatchResp1) { String mkey = new String(response.getKey()); LOGGER.info("Key is??: " + mkey + "response status " + response.getStatus() + "hmap get key " + hmapStatus.get(mkey)); AssertJUnit.assertEquals (hmapStatus.get(mkey), response.getStatus()); if (response.getStatus() == OperationStatus.Success) { AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey)) - 10 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); AssertJUnit.assertTrue(1 == response.getVersion()); } } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Verify appropriate JunoException is thrown when batch get to read key=null * @throws JunoException */ @Test public void testBatchGetNullKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create request item with key = null"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[0] = null; String str = "Hello testBatchGetNullKey " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); JunoRequest getItem = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Get); list.add(item); getList.add(getItem); } try{ Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try { Iterable<JunoResponse> getResp; LOGGER.debug("\n===Batch Get is sent "); if (syncFlag == 1) { getResp=junoClient.doBatch(getList).toBlocking().toIterable(); } else { getResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } for (JunoResponse response: getResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Get batch keys to pass TTL > 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchGetLifetimeLongerThan3Days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; Random r = new Random(); LOGGER.debug("Create request item with key = null"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); ttl[i] = 100; ttl[4] = 259201; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)ttl[i], JunoRequest.OperationType.Get); list.add(item); } Iterable <JunoResponse> gResp = new ArrayList<>(); try { LOGGER.debug("Read " + numKeys + " keys using batch Get()"); if (syncFlag == 1) { gResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for one item with NULL key", false); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Get batch keys with keys >=256 bytes * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchGetKey257Bytes() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with key = null"); key[9] = DataGenUtils.createKey(258).getBytes(); key[4] = DataGenUtils.createKey(129).getBytes(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { if ( i != 4 && i != 9 ) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); } payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list.add(item); } Iterable <JunoResponse> gResp = new ArrayList<>(); try { LOGGER.debug("Read " + numKeys + " keys using batch Get()"); if (syncFlag == 1) { gResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for only one item key with long length", false); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[9])) || mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-2); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask no exception for empty list? test case has real failure for now */ //@Test public void testBatchGetZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch create"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); try { junoClient.doBatch(list).toBlocking().toIterable(); AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with a key having TTL more than 3 days * Verify get correct response for each item including long TTL one */ @Test public void testBatchSetTTLmorethan3days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > lifetime > 3 days"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; ttl[1] = 259201; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], null, (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Get); list.add(item); } LOGGER.debug("\n===Batch Get is sent "); Iterable <JunoResponse> resp = new ArrayList<JunoResponse>(); try { if (syncFlag == 1) { resp = junoClient.doBatch(list).toBlocking().toIterable(); } else { resp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is not thrown for TTL > 3 days", false); } int i = 0; for (JunoResponse response: resp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertTrue(OperationStatus.NoKey == response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } }
76
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ReactorGetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger;import com.paypal.juno.client.JunoClient; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ReactorGetTest{ private JunoClient junoClient; private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoReactClient junoReactClient2; private JunoReactClient cryptClient2; private Properties pConfig; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(GetTest.class); URL url = GetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); URL url1 = GetTest.class.getResource("/com/paypal/juno/Juno.properties"); junoReactClient1 = JunoClientFactory.newJunoReactClient(url1); URL url2 = GetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try{ junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); junoClient=JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(1000); } /** * Send a get request with key to the Juno 2.0 server and should not generate * exception * @throws JunoException * @throws IOException */ @Test public void testGetWithKey() throws IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 220000; JunoResponse mResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); JunoResponse junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); junoResponse = junoReactClient.get(key, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.get(key, 10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request with empty key and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testGetWithEmptyKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); try{ JunoResponse junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); AssertJUnit.assertEquals (OperationStatus.NoKey,junoResponse.getStatus()); }catch(Exception mex){ LOGGER.debug("Exception: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with null key and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testGetWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); try{ JunoResponse junoResponse = junoReactClient.get(null).block(); AssertJUnit.assertTrue ("Exception is not seen for null key", false); }catch(Exception mex){ LOGGER.debug("Exception: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with no key exists on the server and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testGetNoKeyExists() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); try { JunoResponse mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request after five seconds of creation of a record and should not * generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ @Test public void testGetAfterFiveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); Thread.sleep(3000); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 5-3 && junoResponse.getTtl() > 0); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request after twelve seconds after creation of a record and should * generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ @Test public void testGetAfterTwelveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data, (long)5).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); LOGGER.debug("default ttl is " + junoResponse.getTtl()); Thread.sleep(3000); LOGGER.debug("Read should not extend lilfetime"); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 5-3 && junoResponse.getTtl() > 0); AssertJUnit.assertTrue (junoResponse.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(3000); try { JunoResponse mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey, mResponse.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } LOGGER.info("Completed"); } /** * Send a get request with 128bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse =junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request with 130 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); try{ JunoResponse junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertTrue ("Exception is not seen for key > 128 bytes length", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with lifetime and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testGetWithLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key, (long)5).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 5 && junoResponse.getTtl() > 5-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(3000); LOGGER.debug("Update key with new timeline add" ); JunoResponse junoResponse1; try { junoResponse1 = junoReactClient.get(key, (long)5).block(); } catch (JunoException mex) { AssertJUnit.assertTrue("\"get time out Exception?", false); } Thread.sleep(3000); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); LOGGER.debug("Sleep for key to expire"); Thread.sleep(3000); try { JunoResponse junoResponse2 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey,junoResponse2.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request with zero life time and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithZeroLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(junoResponse1.getTtl() <= 5 && junoResponse1.getTtl() > 5-3); Thread.sleep(6000); try { JunoResponse junoResponse2 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey,junoResponse2.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request with zero life time and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithoutLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() > lifetime-3 && junoResponse.getTtl() <= lifetime); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() > lifetime-3 && junoResponse.getTtl() <= lifetime); Thread.sleep(6000); try { JunoResponse junoResponse2 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey,junoResponse2.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request with max lifetime 3days and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithMaxLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse mResponse = junoReactClient.create(key, data, (long)10).block(); AssertJUnit.assertTrue(10 == mResponse.getTtl()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(10-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= 10); junoResponse = junoReactClient.get(key, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-2 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.get(key, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request with more than max lifetime and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithMoreThanMaxLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; long lifetime1 = 777000; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); try{ junoResponse = junoReactClient.get(key, lifetime1).block(); AssertJUnit.assertTrue ("Exception is not seen for big lifetime = 777000", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=777000, max configured lifetime=259200")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with negative lifetime and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithNegativeLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try{ JunoResponse junoResponse1 = junoReactClient.get(key, (long)-1).block(); AssertJUnit.assertTrue ("Exception is not seen for negative lifetime", false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /*********************************************** * insert 2 client objects with different * application names but same namespace. insert * record with key k1 using one client object. * Do a get for record with k1 using the second * client object. * ************************************************/ @Test public void testGetWithSameNameSpaceDiffAPP_NAME() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); LOGGER.debug("response ttl is " + junoResponse.getTtl() + " respnose1 ttl is " + junoResponse1.getTtl()); AssertJUnit.assertTrue(junoResponse.getTtl() <= junoResponse1.getTtl() && junoResponse.getTtl() >= junoResponse1.getTtl()-3); AssertJUnit.assertEquals(junoResponse.getVersion(), junoResponse1.getVersion()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /*********************************************** * insert 2 client objects with namespaces NS1 & * NS2. insert records with different keys and * payloads under both clients. Perform 'Get' * for key insertd under NS1 using NS2's client * object and vice-versa. * Result: Should get "key not found" * ************************************************/ @Test public void testGetWithDiffNameSpaceAndDiffKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(64); long lifetime = 3600; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient1.create(key1, data1, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); //client1 get key from a different name space NS junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue (junoResponse.getTtl() <= lifetime && junoResponse.getTtl() > lifetime-3); try { junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } //client get key from a different name space try { junoResponse = junoReactClient.get(key1).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, junoResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } junoResponse1 = junoReactClient1.get(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue (junoResponse1.getTtl() <= lifetime && junoResponse1.getTtl() > lifetime-3); LOGGER.info("0"); LOGGER.info("Completed"); } /*********************************************** * insert 2 client objects with namespaces NS1 & * NS2. insert records with same key but different * payloads under both clients. Perform a 'Get' * for the key under NS1 and NS2. * ************************************************/ @Test public void testGetWithDiffNameSpaceDiffPayloadSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); try { Thread.sleep(2000); } catch (Exception ex) { LOGGER.debug(ex.getMessage()); } junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); try { JunoResponse res = junoReactClient1.create(key, data1).block(); AssertJUnit.assertEquals(OperationStatus.Success,res.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for duplicate key", false); } junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertTrue(junoResponse.getVersion() == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse.getValue().length < junoResponse1.getValue().length); AssertJUnit.assertTrue(new String(junoResponse.getValue()) != new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testinsertChineseKeyForCpp() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); //byte[] key = "123456"; byte[] key = "Q:������������A:���������. Q:�������������".getBytes(); byte[] key_utf8 = new String("UTF-8,UTF-8").getBytes(); byte[] data = "Q:������������A:���������".getBytes("UTF-8"); byte[] data2 = "Q:������������A:���������. Q:���������������123".getBytes("UTF-8"); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.delete(key_utf8).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(1, junoResponse.getVersion()); junoResponse = junoReactClient.get(key, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(1, junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 100 && junoResponse.getTtl() > 100-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.get(key, (long)115).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(1, junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 115 && junoResponse.getTtl() > 115-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("\nUpdate key: "); byte[] data1 = "Q:������������A:���������. Q:���������������".getBytes("UTF8"); long lifetime1 = 120L; JunoResponse junoResponse1 = junoReactClient.update(key, data1, lifetime1).block(); LOGGER.debug("Version: " + junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); LOGGER.debug("New Data1: " + new String(junoResponse1.getValue())); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoResponse junoResponse2 = junoReactClient.create(key_utf8, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(1, junoResponse2.getVersion()); AssertJUnit.assertTrue(junoResponse2.getTtl() <= prop.getDefaultLifetime() && junoResponse2.getTtl() > prop.getDefaultLifetime()-3); junoResponse2 = junoReactClient2.get(key_utf8).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse2.getValue())); //conditional update old response will fail, ttl etc. shouldn't be updated LOGGER.debug("\nConditional Update: "); try { JunoResponse junoResponse3 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data2, (long)600).block(); AssertJUnit.assertEquals(OperationStatus.ConditionViolation, junoResponse3.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for Condition Violation", false); } JunoResponse gResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, gResponse.getStatus()); AssertJUnit.assertEquals(2, gResponse.getVersion()); LOGGER.debug("junoResponse3 lifetime is " + gResponse.getTtl()); AssertJUnit.assertTrue(gResponse.getTtl() <= lifetime1 && gResponse.getTtl() > lifetime1 - 5); AssertJUnit.assertEquals(data1.length, gResponse.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(gResponse.getValue())); //conditional update successful junoResponse = junoReactClient.compareAndSet(junoResponse1.getRecordContext(), data2, (long)600).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); gResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, gResponse.getStatus()); AssertJUnit.assertEquals(key, gResponse.key()); AssertJUnit.assertEquals(3, gResponse.getVersion()); AssertJUnit.assertTrue(gResponse.getTtl() <= 600 && gResponse.getTtl() > 600-3); AssertJUnit.assertEquals(new String(data2), new String(gResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } //@Test public void testGetEncrypt() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "Thisisanewkey".getBytes(); LOGGER.debug("Crypt client1 inserts key"); //cryptClient1.delete (key); //cryptClient1.insert(key, data, 7200L); LOGGER.debug("Crypt client2 gets key"); JunoResponse junoResponse = cryptClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); LOGGER.debug("Data from Infra: " + new String(junoResponse.getValue())); // LOGGER.debug("Crypt client1 updates key"); // byte[] data1 = "Hello testing data".getBytes(); // JunoResponse junoResponse2 = cryptClient1.update (key, data1); // assertEquals (junoResponse2.getStatus(), OperationStatus.Success); // // junoResponse = cryptClient2.get(key); // assertEquals (new String(data1), new String(junoResponse.getValue())); // LOGGER.debug("Data: " + new String(junoResponse.getValue())); // // LOGGER.debug("Crypt client2 do a Conditional Update on key"); // // JunoResponse junoResponse3 = cryptClient1.cas (junoResponse, data2, (long)15); // assertEquals (junoResponse3.getStatus(), OperationStatus.Success); // assertEquals (new String(data2), new String(junoResponse3.getValue())); // LOGGER.debug("Data: " + new String(junoResponse3.getValue())); // LOGGER.debug("Crypt client1 delete key"); // cryptClient1.delete(key); // junoResponse = cryptClient2.get(key); // assertEquals (junoResponse.getStatus(), OperationStatus.NoKey); } @Test public void testGetWithKey3() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "EbZaSXjUi3IHef52XSCe".getBytes(); byte[] data2 = "This is a new test data testing".getBytes(); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse res = junoReactClient.create(key,data2,(long)160).block(); AssertJUnit.assertEquals (OperationStatus.Success, res.getStatus()); AssertJUnit.assertTrue(res.getTtl() == 160); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); LOGGER.info("0"); LOGGER.info("Completed"); } }
77
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ReactorCreateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.Properties; import java.util.Random; import org.slf4j.Logger;import com.paypal.juno.client.JunoReactClient; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xerial.snappy.Snappy; public class ReactorCreateTest { private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoReactClient junoReactClient2; private JunoReactClient junoReactClient3; private JunoReactClient junoReactClient4; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Properties pConfig3; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(ReactorCreateTest.class); URL url = ReactorCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "JunoReactTestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoReactNS1"); URL url1 = ReactorCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); junoReactClient1 = JunoClientFactory.newJunoReactClient(url1); URL url2 = ReactorCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "false"); pConfig2.setProperty(JunoProperties.APP_NAME, "JunoReactTestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoReactNS1"); pConfig3 = new Properties(); pConfig3.load(url1.openStream()); pConfig3.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoReactNS3"); pConfig3.setProperty(JunoProperties.DEFAULT_LIFETIME, "2900"); pConfig3.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "false"); pConfig3.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "true"); try{ junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); junoReactClient3 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); junoReactClient4 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(1000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Send a insert request to the Juno 2.0 server with specified key. * It should not generate any exception, if there is no problem on server side. * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithKey() throws JunoException, IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoPropertiesProvider prop3 = new JunoPropertiesProvider(pConfig3); LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); try { for(int i=0; i < 3; i++){ //create(key, data) LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); JunoResponse mResponse3 = junoReactClient3.create(key, data1).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertTrue(mResponse3.getTtl() <= prop3.getDefaultLifetime() && mResponse3.getTtl() >= prop3.getDefaultLifetime()-3); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse.getValue())); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); mResponse3 = junoReactClient3.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals (new String(data1), new String(mResponse3.getValue())); AssertJUnit.assertTrue(mResponse3.getTtl() <= 2900 && mResponse3.getTtl() >= 2900-3); LOGGER.info("0"); LOGGER.info("Completed"); } for(int i=0; i < 3; i++){ //create(key,data,ttl) LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoReactClient.create(key, data, (long)20).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); JunoResponse mResponse3 = junoReactClient3.create(key, data1, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals (mResponse.getVersion(), 1); AssertJUnit.assertEquals (new String(data), new String(mResponse.getValue())); AssertJUnit.assertTrue(mResponse.getTtl() <= 20 && mResponse.getTtl() > 20-3); mResponse3 = junoReactClient3.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals (mResponse3.getVersion(), 1); AssertJUnit.assertEquals (new String(data1), new String(mResponse3.getValue())); AssertJUnit.assertTrue(mResponse3.getTtl() <= 100 && mResponse3.getTtl() > 100-3); LOGGER.info("0"); LOGGER.info("Completed"); } }catch(Exception e) { LOGGER.debug("Exception.."); AssertJUnit.assertFalse("Exception :"+e.getMessage(),true); } } /** * Send a insert request twice with same key to Juno 2.0 server * It should generate UniqueKeyViolation or JunoException exception. * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithSameKey() throws JunoException, IOException{ LOGGER.info( "TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); //It should have used the configured default TTL AssertJUnit.assertTrue( junoResponse.getTtl() >= (prop.getDefaultLifetime() -3) && junoResponse.getTtl() <= prop.getDefaultLifetime()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse mResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (mResponse.getStatus(), OperationStatus.UniqueKeyViolation); JunoResponse mResponse2 = junoReactClient2.create(key, data).block(); AssertJUnit.assertEquals (mResponse2.getStatus(), OperationStatus.UniqueKeyViolation); LOGGER.info("DupKey"); LOGGER.info("0"); } catch (JunoException ex) { AssertJUnit.assertTrue ("Exception seen for Duplicate key", false); } finally { LOGGER.info("Completed"); } } /** * Send a insert request with empty key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithEmptyKey() throws JunoException, IOException{//TODO: reevaluate LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse mResponse = null; try{ junoReactClient.create(key, data).block(); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); }catch(Exception mex){ Assert.assertEquals("The Document key must not be null or empty", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } key = "Test_key".getBytes(); try{ junoReactClient.create(key, data,(long)0).block(); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); }catch(Exception mex){ Assert.assertEquals("The Document's TTL cannot be 0 or negative.", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with Null key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithNullKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.create(key, data).block(); AssertJUnit.assertTrue ("Exception is not seen for null key", false); } catch (JunoException mex) { AssertJUnit.assertEquals("The Document key must not be null or empty", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with 128bytes key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testReactCreateWith128BytesKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with 256bytes key and should generate IllegalArgumentException * with "Invalid key length. current length=257, max length=256" * @throws JunoException * @throws IOException */ @Test public void testReactCreateWith129BytesKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.create(key, data).block(); Assert.assertTrue(false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); Assert.assertEquals("The Document key must not be larger than 128 bytes", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request special characters key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "Q:������������������A:����@@#$%^&*()_+?>,<|}{[]~abc780=.__?|".getBytes(); byte[] data = "Q:������������������������������������A:���������������������������".getBytes(); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 100 && junoResponse.getTtl() >= 100-3); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with normal lifetime and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testReactCreateWith10SecLifetime() throws JunoException, IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() > lifetime-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with zero lifetime, default lifetime should be used * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithZeroLifetime() throws JunoException, Exception{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.create(key, data, (long)0).block(); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be 0 or negative.")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with Negative lifetime and should generate an * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithNegativeLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.create(key, data, (long)-1).block(); AssertJUnit.assertTrue ("Exception is NOT seen for negative lifetime", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative. ")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with null lifetime and should generate an * IllegalArgumentException //TODO: should 0 lifetime for create throw exception?? * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithNullLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.create(key, data, (long)0).block(); AssertJUnit.assertTrue(false); }catch(JunoException mex) { AssertJUnit.assertEquals("The Document's TTL cannot be 0 or negative.",mex.getCause().getMessage()); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with max lifetime 3 days and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testReactCreateWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with more than max lifetime 3 days and should * generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertTrue ("Exception is not seen for TTL > 3 days", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with null payload and should create successfully * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithNullPayload() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse res = junoReactClient.create(key, null).block(); AssertJUnit.assertEquals(OperationStatus.Success,res.getStatus()); AssertJUnit.assertEquals(1,res.getVersion()); //AssertJUnit.assertTrue ("Exception is NOT seen for Null payload", false); }catch(Exception mex){ AssertJUnit.assertFalse(true); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with zero size payload and should create successfully * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithZeroPayload() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(0); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success , mResponse.getStatus()); AssertJUnit.assertEquals(1, mResponse.getVersion()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(1, mResponse.getVersion()); AssertJUnit.assertEquals(key, mResponse.getKey()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with 100KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testReactCreateWith100KBPayload() throws JunoException, Exception{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(100200); byte[] key = DataGenUtils.genBytes(64); long lifetime = 4; JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Sleep 3 seconds to expire daata"); Thread.sleep (5000); try { JunoResponse mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is not seen for empty key", false); } finally { LOGGER.info("0"); LOGGER.info("Completed"); } } /** * Send a insert request with 200KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testReactCreateWith200KBPayload() throws IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204800); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with more than 200KB payload and should generate * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoReactClient.create(key, data).block(); AssertJUnit.assertTrue ("Exception is not seen for payload > 200KB", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with more than 1KB payload and see if its compressed * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testReactCreateWithAndWithoutCompression() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = new String("Couchbase stores data as key value pairs where the value is a JSON document and the key is an identifier for retrieving that document. By default cbexport will only export the value portion of the document. If you wish to include the key in the exported document then this option should be specified. The value passed to this option should be the field name that the key is stored under.Skips the SSL verification phase. Specifying this flag will allow a connection using SSL encryption, but will not verify the identity of the server you connect to. You are vulnerable to a man-in-the-middle attack if you use this flag. Either this flag or the --cacert flag must be specified when using an SSL encrypted connection Specifies a CA certificate that will be used to verify the identity of the server being connecting to. Either this flag or the --no-ssl-verify flag must be specified when using an SSL encrypted connection. Specifies the number of concurrent clients to use when exporting data. Fewer clients means exports will take longer, but there will be less cluster resources used to complete the export. More clients means faster exports, but at the cost of more cluster resource usage. This parameter defaults to 1 if it is not specified and it is recommended that this parameter is not set to be higher than the number of CPUs on the machine where the export is taking place. Exports JSON data from Couchbase. The cbexport-json command supports exporting JSON docments to a file with a document on each line or a file that contain a JSON list where each element is a document. The file format to export to can be specified with the --format flag. See the DATASET FORMATS section below for more details on the supported file formats.").getBytes(); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(64); try{ //Write with payload compression enabled client and read it via client without compression enabled. JunoResponse junoResponse = junoReactClient4.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient3.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(Arrays.equals(data, junoResponse.getValue())); //Write with out compression and read using compression enabled. junoResponse = junoReactClient3.create(key1, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient4.get(key1).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(Arrays.equals(data, junoResponse.getValue())); LOGGER.info("1"); LOGGER.info("Completed"); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /************************************************* * Send a insert request with same key for two different name spaces and should not * generate exceptions * *************************************************/ @Test public void testReactCreateWithSameKeyInDifferentNS() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); byte[] key = "TestKey1".getBytes(); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient1.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient1.create(key, data1).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); junoResponse = junoReactClient1.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); try { junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for No key", false); } junoResponse1 = junoReactClient1.create(key, data, (long)30).block(); //insert same key/value with different ttl AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertEquals(junoResponse.getVersion(), junoResponse1.getVersion()); AssertJUnit.assertNotSame(junoResponse.getTtl(), junoResponse1.getTtl()); junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two records with same key and name space. * The 2nd insert fails and should generate an exception *************************************************/ @Test public void testReactCreateWithSameKeysInSameNS() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(10); JunoResponse junoResponse =junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create with same key, different data try { JunoResponse mResponse = junoReactClient.create(key, data2).block(); AssertJUnit.assertEquals (OperationStatus.UniqueKeyViolation,mResponse.getStatus()); LOGGER.info("DupKey"); LOGGER.info("0"); } catch (JunoException ex) { AssertJUnit.assertTrue ("Exception is seen for Duplicate key", false); } JunoResponse gResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, gResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(gResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two clients with same ns but diff app name * Create 1 record each using clients1 and client2. * The 2nd insert will fail. *************************************************/ @Test public void testReactCreateWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create same key try { JunoResponse mResponse = junoReactClient2.create(key, data).block(); AssertJUnit.assertEquals (mResponse.getStatus(), OperationStatus.UniqueKeyViolation); LOGGER.info("DupKey"); LOGGER.info("0"); } catch (JunoException ex) { AssertJUnit.assertTrue(false); } finally { LOGGER.info("Completed"); } } //Need to rewrite the below test cases /********************************************** * app_name length > 32 (MF_APP_NAME_MAX_LEN) *********************************************/ @Test public void testValidateAppnameLength() throws JunoException, IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); String appname = DataGenUtils.genString(32); String appname1 = DataGenUtils.genString(33); URL url = ReactorCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, appname); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse result = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, result.getStatus()); AssertJUnit.assertEquals(data.length, result.getValue().length); AssertJUnit.assertEquals(new String(data), new String(result.getValue())); pConfig.setProperty(JunoProperties.APP_NAME, "JunoTestApp"); //set back to orig junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); try{ pConfig.setProperty(JunoProperties.APP_NAME, appname1); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient.create(key, data).block(); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Application Name length exceeds MAX LENGTH of 32 bytes")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } finally { pConfig.setProperty(JunoProperties.APP_NAME, "JunoTestApp"); // set back to orig junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } } /***************************************************** * namespace_name lenght > 64 (MF_NAMESPACE_MAX_LEN) *****************************************************/ @Test public void testValidateNamespaceLength() throws JunoException, IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(64); String namespace = DataGenUtils.genString(64); String namespace1 = DataGenUtils.genString(65); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, namespace); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse result = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, result.getStatus()); AssertJUnit.assertEquals(data.length, result.getValue().length); AssertJUnit.assertEquals(new String(data), new String(result.getValue())); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS1"); //set back to orig junoReactClient junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); try{ pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, namespace1); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertEquals("Namespace length exceeds MAX LENGTH of 64 bytes", mex.getMessage()); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } finally { pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS1"); //set back to orig junoReactClient1 junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } } /***************************************************************** * m_max_lifetime > Juno_CONFIG_DEFAULT_MAX_LIFETIME (259200) *****************************************************************/ @Test public void testValidateByChangingMaxLifeTime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ junoReactClient2.create(key, data, (long)259201).block(); AssertJUnit.assertTrue ("Exception is NOT seen for invalid lifetime", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=259201, max configured lifetime=259200")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /*********************************************************************** * m_max_payload_size > Juno_CONFIG_DEFAULT_MAX_PAYLOAD_SIZE (204800) ***********************************************************************/ @Test public void testValidateByChangingMaxPayloadSize() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoReactClient2.create(key, data).block(); AssertJUnit.assertTrue ("Exception is NOT seen for invalid payload", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than ")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } @Test public void testReactCreateWithChineseKey() throws JunoException, Exception { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); String key = "Q:������������������������A:������. Q:����� A:����"; String key1 = DataGenUtils.createKey(127); byte[] data = "New data testing".getBytes(); byte[] data1 = "New data111111111111".getBytes(); byte [] keybyte = key.getBytes(); LOGGER.debug(new String (keybyte) + "length is: " + keybyte.length); JunoResponse junoResponse = junoReactClient.delete(keybyte).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(keybyte, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient.create(key1.getBytes(), data1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); junoResponse = junoReactClient.get(keybyte).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse1 = junoReactClient.get(key1.getBytes()).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); LOGGER.debug("Status: " + junoResponse1.getStatus()); LOGGER.debug("Data: " + new String (junoResponse.getValue())); LOGGER.debug("Data1: " + new String (junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testReactCreateWithChineseKeyBigThan128() throws JunoException, Exception { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); String key = "Q:������������������������A:������. Q:������������������������� A:������������B:�����B:�����B:������������������������� AQ:������������������������� "; byte[] data = "New data testing".getBytes(); try{ byte [] keybyte = key.getBytes(); LOGGER.debug(new String (keybyte) + "length is: " + keybyte.length); JunoResponse junoResponse = junoReactClient.delete(keybyte).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(keybyte, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(keybyte).block(); LOGGER.debug("Data: " + new String (junoResponse.getValue())); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than " + prop.getMaxKeySize())); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } //@Test public void testReactCreateResponseTimeout() throws IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url3 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig3 = new Properties(); pConfig3.load(url3.openStream()); pConfig3.setProperty(JunoProperties.APP_NAME, "QATestApp3"); pConfig3.setProperty(JunoProperties.RECORD_NAMESPACE, "NS3"); pConfig3.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoReactClient junoReactClient3 = null; try { junoReactClient3 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } byte[] key = DataGenUtils.genBytes(128); byte[] payload = DataGenUtils.genBytes(204700); long ttl = (long)10000; try { JunoResponse junoResponse = junoReactClient3.create(key, payload).block(); AssertJUnit.assertTrue("should hit response timeout exception", false); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Response Timed out")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } //@Test /** * This test case will run successfully only after shutdown proxy, so either disable * this test case or shutdown proxy and then run this test * @throws JunoException //TODO: it doesn't throw connection timeout, but only response timeout */ //TODO: BUG? exception is not connection timeout but response timeout //@Test public void testReactCreateConnectionTimeout() throws IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url1 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); pConfig1.setProperty(JunoProperties.CONNECTION_TIMEOUT, "1"); JunoReactClient junoReactClient3 = null; try { junoReactClient3 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } byte[] key = DataGenUtils.genBytes(12); byte[] payload = DataGenUtils.genBytes(20); long ttl = (long)10000; try { JunoResponse junoResponse = junoReactClient3.create(key, payload).block(); AssertJUnit.assertTrue("should hit connection timeout exception", false); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Connection Timedout")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Test client call won't be disrupted after server timeout */ @Test public void testReactCreateServerIdletimeout() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoPropertiesProvider prop3 = new JunoPropertiesProvider(pConfig3); try { for(int i=0; i < 10; i++){ //create(key, data) LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); JunoResponse mResponse3 = junoReactClient3.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals(mResponse3.getTtl(), prop3.getDefaultLifetime().longValue()); AssertJUnit.assertTrue(mResponse3.getTtl() <= prop3.getDefaultLifetime() && mResponse3.getTtl() >= prop3.getDefaultLifetime()-3); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse.getValue())); AssertJUnit.assertTrue (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); LOGGER.debug("default ttl is " + mResponse.getTtl()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); mResponse3 = junoReactClient3.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse3.getValue())); AssertJUnit.assertTrue (mResponse3.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertTrue(mResponse3.getTtl() <= prop3.getDefaultLifetime() && mResponse3.getTtl() >= prop3.getDefaultLifetime()-3); LOGGER.info("0"); LOGGER.info("Completed"); } }catch(Exception e) { AssertJUnit.assertTrue("shouldn't throw exception here", false); } } @Test public void testOrigSizeExceedsNotAfterCompress() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(300000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testExceedsCompressLimit").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is:" + data.length + "compressed length is " + dataLength); JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); }}
78
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchSetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import rx.observables.BlockingObservable; public class BatchSetTest{ private JunoAsyncClient junoClient; private JunoAsyncClient asyncJunoClient; private JunoAsyncClient asyncJunoClient1; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; private int syncFlag; @BeforeClass public void setup() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER = LoggerFactory.getLogger(BatchSetTest.class); URL url = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); LOGGER.debug("Read syncFlag test to findout what needs to be run"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); junoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); asyncJunoClient = JunoClientFactory.newJunoAsyncClient(url); URL url1 = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); URL url2 = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Create and get multiple keys using batch create * @throws JunoException //TODO: Ask so during set, what version passed in doesn't matter? */ @Test public void testBatchCreateSet() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; Long[] ttl = new Long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using existing Juno Create, no lifetime"); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[numKeys-1] = DataGenUtils.createKey(128).getBytes(); Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); payload[numKeys-1] = DataGenUtils.createKey(204800).getBytes(); JunoResponse mResponse = junoClient2.create(key[i], payload[i]); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } Long[] ttl1 = new Long[numKeys]; byte[][] payload1 = new byte[numKeys][]; LOGGER.debug("Calling Batch set with lifetime"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); payload1[i] = DataGenUtils.createKey(payloadlen).getBytes(); payload1[numKeys-1] = DataGenUtils.createKey(204800).getBytes(); ttl1[i] = 20L; hmap.put(new String(key[i]), payload1[i]); JunoRequest item1 = new JunoRequest(key[i], payload1[i], (long)0, ttl1[i], System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item1); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(junoClient, list); } int i = 1; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); i++; } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); } //Read Item List List<JunoRequest> list2 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item2 = new JunoRequest(key[i],(long)0, (long)0, JunoRequest.OperationType.Get ); list2.add(item2); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = junoClient.doBatch(list2).toBlocking().toIterable(); if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list2).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(junoClient, list2); } int i = 0; for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); LOGGER.debug("Key: " + i + ": "+ response.getKey()); LOGGER.debug("Data: " + new String(response.getValue())); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Set batch keys with 1 empty key * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetEmptyKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Batch set " + numKeys + " keys with one zero-length key"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(127).getBytes(); ttl[i] = 20; key[9] = "".getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); //System.out.println(" i is " + i + ", key[i] is " + new String(key[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try{ for (int i = 0; i < numKeys; i ++) { //System.out.println(" i is " + i + ", key[i] is " + new String(key[i])); } LOGGER.debug("\n===Batch Set is sent "); Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { //System.out.println(" mkey is " + new String(response.getKey())); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with 2 NULL keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Batch Set " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[3] = null; key[9] = null; String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; //intentionally use below value for set JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try{ Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with keys >=257 keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSet257BytesKeys() throws JunoException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Batch set " + numKeys + " keys with more than 1 key >= 257 bytes"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); key[1] = DataGenUtils.createKey(259).getBytes(); key[9] = DataGenUtils.createKey(257).getBytes(); for (int i = 0; i < numKeys; i ++) { if ( i != 1 && i != 9 ) { key[i] = DataGenUtils.createKey(128).getBytes(); } String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for key with > 256 bytes long happen on one item only", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[1])) || mkey.equals(new String(key[9]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); i++; } } AssertJUnit.assertEquals(i,numKeys-2); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with keys having 0 or null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetZeroPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with some keys having zero payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = DataGenUtils.createKey(25); payload[i] = str.getBytes(); payload[5] = "".getBytes(); ttl[i] = 20; hmap.put(new String(new String(key[i])), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); if (syncFlag == 1) { BlockingObservable<JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item1 = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list1.add(item1); } Iterable <JunoResponse> getBatchResponse; if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int j = 0; for (JunoResponse response: getBatchResponse) { byte[] mkey=response.getKey(); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(new String(mkey)), response.getValue()); j++; } AssertJUnit.assertEquals(j, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Set batch keys with keys having null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetNullPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Set " + numKeys + " keys with some keys having null payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); payload[0] = null; payload[4] = "".getBytes(); hmap.put(new String(key[i]), payload[i]); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try { if (syncFlag == 1) { BlockingObservable <JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for null payload on just one item", false); } for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list1.add(item); } Iterable<JunoResponse> setBatchResponse; try { if (syncFlag == 1) { setBatchResponse = junoClient.doBatch(list1).toBlocking().toIterable(); } else { setBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int i = 0; for (JunoResponse response: setBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); LOGGER.info("0"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); } for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); LOGGER.debug("hmap value is " + hmap.get(mkey) + " " + "response value is " + response.getValue() + " i is " + i); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with a key having > 200KB payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetMoreThan200KPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Set " + numKeys + " keys with a key having > 200KB payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.genBytes(204801); payload[numKeys-1] = DataGenUtils.genBytes(20); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for big payload happened on one item", false); } ArrayList <JunoRequest> getList = new ArrayList<JunoRequest>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag == 1) { getBatchResponse = junoClient.doBatch(getList).toBlocking().toIterable(); } else { getBatchResponse = BatchTestSubscriber.async_dobatch(asyncJunoClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[numKeys-1]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); } else { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with a key having TTL more than 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetTTLmorethan3days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > lifetime > 3 days"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.createKey(25).getBytes(); ttl[i] = 20; ttl[1] = 259201; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is not thrown for TTL > 3 days", false); } ArrayList <JunoRequest> list1 = new ArrayList<> (); LOGGER.debug("Read " + numKeys + " keys using batch Get()"); for (int i = 0; i < numKeys; i ++) { JunoRequest item1 = new JunoRequest(key[i], null, (long)0, ttl[i], JunoRequest.OperationType.Get); list1.add(item1); } Iterable<JunoResponse> getBatchResp = null; try { if (syncFlag == 1) { LOGGER.debug("before blocking mode batch get " + System.currentTimeMillis()); getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { LOGGER.debug("before non-blocking mode batch get " + System.currentTimeMillis()); getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } LOGGER.debug("after batch get " + System.currentTimeMillis()); int i = 0; for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertTrue(OperationStatus.Success == response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(hmapTTL.get(mkey)-3 <= response.getTtl() && response.getTtl() <= hmapTTL.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (JunoException ex) { LOGGER.debug("Exception occured:" + ex.getMessage() ); AssertJUnit.assertTrue(false); } } /** * Create batch keys with different TTL and payload * One key has max payload and TTL * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetDiffLifeTimePayloads() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); LOGGER.debug("ttl1: " + ttl1); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 2048)); payload[5] = DataGenUtils.genBytes(204800); ttl[i] = DataGenUtils.rand(r, 200, 86400); ttl[5] = 259200; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { //LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { //LOGGER.debug("Error code: " + mex.getOperationStatus().getCode()); LOGGER.debug("Exception occurs: " + mex.getMessage()); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, 0, JunoRequest.OperationType.Get); list1.add(item); } Iterable<JunoResponse> getBatchResp; if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform set batch keys without TTL * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask create can not have 0 TTL while set can? Why it's 3600 not 1800?? */ @Test public void testBatchSetNoLifeTime() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(junoClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue (false); } LOGGER.debug("Read " + numKeys + " keys using existing Juno read()"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i++) { JunoResponse response = junoClient2.get(key[i]); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (new String(payload[i]), new String (response.getValue())); //System.out.println("TTL in Response :"+response.getTtl()); AssertJUnit.assertTrue (1800 - 8 <= response.getTtl() && response.getTtl() <= 1800); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform batch set keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: same question as testBatchGetZeroItem */ //@Test public void testBatchSetZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch create"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); try { junoClient.doBatch (list).toBlocking().toIterable(); AssertJUnit.assertTrue ("Exception is not thrown for no key in the Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); } } }
79
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ReactorSetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xerial.snappy.Snappy; public class ReactorSetTest{ private JunoClient junoClient; private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoReactClient junoReactClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(SetTest.class); URL url = SetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); pConfig.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "true"); URL url1 = SetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); URL url2 = JunoClientFactory.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try{ junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient1 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleansetup() throws Exception{ } /** * Send a set request to the juno 2.0 server with specified key which does not exist. * It should not generate any exception, if there is no problem on server side. * @throws JunoException */ @Test public void testsetWithKey() throws IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] data2 = DataGenUtils.genBytes(20); byte[] data3 = DataGenUtils.genBytes(40); byte[] data4 = DataGenUtils.genBytes(800); long lifetime = 22000; JunoResponse mResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); LOGGER.debug("set ttl is " + mResponse.getTtl()); AssertJUnit.assertTrue(mResponse.getTtl() == prop.getDefaultLifetime()); mResponse = junoReactClient.set(key, data1).block(); //ttl won't be updated AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); JunoResponse junoResponse = junoReactClient.set(key,data2, lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(3 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); junoResponse = junoClient.set(key, data3, (long)10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(4 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); junoResponse = junoReactClient.set(key, data4, (long)0).block(); AssertJUnit.assertTrue(OperationStatus.Success == junoResponse.getStatus()); AssertJUnit.assertTrue(5 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-3); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(5 == junoResponse.getVersion()); AssertJUnit.assertEquals(data4.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data4), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-3); key = DataGenUtils.genBytes(64); data = DataGenUtils.genBytes(10); JunoResponse junoResponse1 = junoReactClient1.set(key, data, (long)0).block(); //it gets default time from server side which is 3600 AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request twice with same key to juno 2.0 server * It should be successfull. * @throws JunoException * @throws IOException */ @Test public void testsetWithSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); long lifetime = 100; JunoResponse junoResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoReactClient1.set(key, data2, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(key == junoResponse.getKey()); mResponse = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request twice with same key to juno 2.0 server * It should be successfull. * @throws JunoException * @throws IOException */ @Test public void testsetWithoutTTL() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object() {}.getClass().getEnclosingMethod().getName()); LOGGER.info(new Object() {}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoResponse junoResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } junoResponse = junoReactClient.get(key).block(); // It will show that 10 sec has elapsed from original TTL AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(junoResponse.getTtl() >= (prop.getDefaultLifetime()-14) && (junoResponse.getTtl() <= prop.getDefaultLifetime()-10)); junoResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); // It will show that 1800 sec as TTL. AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() >= (prop.getDefaultLifetime() - 4) && junoResponse.getTtl() <= prop.getDefaultLifetime()); //System.out.println("TTL now is:"+junoResponse.getTtl()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with empty key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testSetWithEmptyKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse mResponse = null; try{ mResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with Null key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testsetWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); try{ long lifetime = 100; junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertTrue ("Exception is not seen for null key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with 128bytes key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = new String(DataGenUtils.createKey(128)).getBytes(); byte[] data = DataGenUtils.genBytes(10); long lifetime = 100; JunoResponse junoResponse = null; try { junoResponse = junoReactClient.set(key, data, lifetime).block(); } catch (JunoException ex) { LOGGER.debug("Exception Occured: " + ex.getMessage()); AssertJUnit.assertTrue(false); } AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Call insert() to create a record with same key, verify DupKey error"); try { JunoResponse mResponse = junoReactClient2.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.UniqueKeyViolation,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for duplicate key", false); LOGGER.info("0"); } LOGGER.info("Completed"); } /** * Send a set request with 129bytes key and should generate IllegalArgumentException * with "Invalid key length. current length=257, max length=256" * @throws JunoException * @throws IOException */ @Test public void testsetWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.set(key, data, (long)100).block(); AssertJUnit.assertTrue ("Exception is NOT seen for Key = 129 bytes length", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request special characters key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "@@#$%^&*()_+?>,<|}{[]~abc780=.__?|".getBytes(); byte[] key1 = "Q:������������A:����. Q:������������������ A:��� Q:".getBytes(); byte[] data = "Q:你好嗎?A:我很好".getBytes(); byte[] data1 = "Q:������������A:���������. Q:������������������ A:������������������ Q:������������������ A:������������������ Ok ���������".getBytes(); LOGGER.debug("key length is " + key.length + " key1 length is " + key1.length); try { JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.delete(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); Thread.sleep(5000); } catch (Exception e) { LOGGER.debug(e.getMessage()); } JunoResponse junoResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.set(key1, data1).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key1, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); JunoResponse junoResponse2 = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertEquals(key, junoResponse2.key()); AssertJUnit.assertTrue(1 == junoResponse2.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse2.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with normal lifetime and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWith10SecLifetime() throws JunoException, IOException, InterruptedException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = new String(DataGenUtils.createKey(40) + "SETWith10SecLifetime").getBytes(); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoReactClient.set(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); Thread.sleep (2000); junoResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Sleep more for the key to expire"); Thread.sleep (4000); try { JunoResponse mResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a set request with zero lifetime, default lifetime should be used * Call insert() to insert same key, should get Duplicate error * @throws JunoException //TODO: ask why get default 3600 not 1800? * @throws IOException */ @Test public void testsetWithZeroLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); byte[] key = new String(DataGenUtils.createKey(30) + "set").getBytes(); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse mResponse = junoReactClient.set(key, data, (long)15).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getTtl() == 15); mResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); mResponse = junoReactClient.set(key, data, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); AssertJUnit.assertEquals(3,mResponse.getVersion()); mResponse = junoReactClient2.set(key, data2).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(4,mResponse.getVersion()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(4,mResponse.getVersion()); AssertJUnit.assertEquals(data2.length,mResponse.getValue().length); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); mResponse = junoReactClient1.set(key, data, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); JunoResponse mResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, mResponse1.getStatus()); //System.out.println("lifetime for junoReactClient1 is " + mResponse1.getTtl()); LOGGER.debug("lifetime for junoReactClient1 is " + mResponse1.getTtl() + ", default is " + prop.getDefaultLifetime()); AssertJUnit.assertEquals(1,mResponse1.getVersion()); AssertJUnit.assertEquals(data.length, mResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(mResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with Negative lifetime and should generate an * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithNegativeLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.set(key, data, (long)-1).block(); AssertJUnit.assertTrue ("Exception is NOT seen for negative lifetime", false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative.")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with max lifetime 3 days and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = new String(DataGenUtils.createKey(50) + "SETWith3DaysLifetime").getBytes(); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient2.get(key, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with more than max lifetime 3 days and should * generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertTrue ("Exception is not seen for TTL > 3 days", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime.")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with null payload and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithNullPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse res = junoReactClient.set(key, null, (long)50).block(); AssertJUnit.assertEquals (OperationStatus.Success,res.getStatus()); AssertJUnit.assertEquals(key, res.key()); AssertJUnit.assertTrue(1 == res.getVersion()); AssertJUnit.assertEquals(0 , res.getValue().length); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertFalse(true); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with zero size payload and should be successfull * @throws JunoException * @throws IOException //TODO: ask set can not be zero payload but create allows zero payload? */ @Test public void testsetWithZeroPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(0); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.set(key, data, (long)20).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); LOGGER.info("0"); }catch(Exception mex){ AssertJUnit.assertTrue("should be able to set empty payload, why come here?", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a set request with 100KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testsetWith100KBPayload() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(102400); byte[] key = new String(DataGenUtils.createKey(50) + "SETWith100KBPayload").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); LOGGER.debug("property config in 100K is :" + prop.getRecordNamespace() + " " + prop.getAppName()); prop = new JunoPropertiesProvider(pConfig); LOGGER.debug("property config1 in 100K is :" + prop.getRecordNamespace() + " " + prop.getAppName()); JunoResponse junoResponse = junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Sleep 3 seconds before geting daata"); JunoResponse mResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with 200KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testsetWith200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204800); byte[] key = new String(DataGenUtils.createKey(64) + "SETWith200KBPayload").getBytes(); JunoResponse junoResponse = junoReactClient.set(key, data, (long)15).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with more than 200KB payload and should generate * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoReactClient.set(key, data, (long)10).block(); AssertJUnit.assertTrue ("Exception is not seen for payload > 200KB", false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /************************************************* * Send a insert request with same key for two different name spaces and should not * generate exceptions * *************************************************/ @Test public void testsetWithSameKeyInDifferentNameSpaces() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(100); JunoResponse junoResponse = junoReactClient.set(key, data, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient1.set(key, data1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertEquals(junoResponse.getVersion(), junoResponse1.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two records using set() with same key and name space. * The 2nd set call should succeed *************************************************/ @Test public void testsetWithSameKeysInSameNameSpace() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); byte[] key = new String(DataGenUtils.createKey(6) + "SETWithSameKeysInSameNameSpace").getBytes(); JunoResponse junoResponse = junoReactClient.set(key, data, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create with same key, different data JunoResponse mResponse = junoReactClient2.set(key, data2, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two clients using insert() then set() with same ns but diff app name * The 2nd set() should succeed *************************************************/ @Test public void testsetWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.createKey(10).getBytes(); LOGGER.debug("key is " + new String(key)); JunoResponse junoResponse = junoReactClient.create(key, data, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create same key using set() should be OK junoResponse = junoReactClient2.set(key, data2, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse mResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * Do a set(), update, conditionalUpdate() * delete() *************************************************/ @Test public void testSetWithOtherOps() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); byte[] data3 = DataGenUtils.genBytes(15); byte[] key = new String(DataGenUtils.createKey(60) + "SETWithOtherOps").getBytes(); JunoResponse junoResponse = junoReactClient.set(key, data, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoReactClient2.update(key, data2, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.debug("\nUpdate the key using conditional update"); long lifetime = 100L; JunoResponse junoResponse1 = junoReactClient.compareAndSet(mResponse.getRecordContext(), data3, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(3 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(new String(data3), new String(junoResponse1.getValue())); junoResponse = junoReactClient2.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); try { JunoResponse result1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, result1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } @Test public void testCompareAndTestWithWrongVersion()throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data1 = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); byte[] key = new String(DataGenUtils.createKey(60) + "SETWithOtherOps").getBytes(); JunoResponse junoResponse = junoReactClient.set(key, data1, (long)100).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse.getValue())); RecordContext reqCtx = new RecordContext(key,0,0,120); try{ junoReactClient.compareAndSet(reqCtx, data2, (long)240).block(); AssertJUnit.assertTrue ("Exception should happen for version = 0", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document version cannot be less than 1")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /*********************************************************************** * m_max_payload_size > JUNO_CONFIG_DEFAULT_MAX_PAYLOAD_SIZE (204800) ***********************************************************************/ @Test public void testValidateByChangingMaxPayloadSize() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); pConfig.setProperty("MAX_PAYLOAD_SIZE", "204809"); JunoReactClient junoReactClient2 = null; try { junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoReactClient2.set(key, data, (long)10).block(); AssertJUnit.assertTrue ("Exception is NOT seen for invalid payload", false); }catch(Exception mex){ LOGGER.debug("\nException occur: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } @Test public void testsetWithChineseKey() throws JunoException, Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "Q:你好嗎?A:我很好. Q:你�?去哪裡? A:我�?去迪斯尼 Q:�?�什麼想看? A:米奇米尼�?鼠ok".getBytes(); byte[] key1 = DataGenUtils.createKey(127).getBytes(); byte[] data = "New data testing".getBytes(); byte[] data1 = "New data111111111111".getBytes(); LOGGER.debug("Key length: " + key.length); LOGGER.debug("Key1 length: " + key1.length); LOGGER.debug("\nKey length without UTF-8: " + key.length); LOGGER.debug("Key1 length without UTF-8: " + key1.length); byte [] tmp = key; LOGGER.debug(new String (tmp) + " " + tmp.length); try { junoReactClient.delete(key); Thread.sleep(5000); } catch (Exception e) { LOGGER.debug("Exception Occured: " + e.getMessage()); } long lifetime = 100; JunoResponse junoResponse = junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient.set(key1, data1, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse1 = junoReactClient.get(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testSetWithCompression() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(100000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testSetWithCompression").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is " + data.length + "compressed length is " + dataLength); JunoResponse junoResponse = junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with 150K byte payload which will trigger compression, data can be read * by mayfly java client testGetFromJunoInsert func or junocli, junocli command is: * ./junocli -s host:port -ssl -c config.toml get -ns "NS1" _testSetWithCompressionCrossRead * exception * @throws Exception */ @Test public void testSetWithCompressionCrossMayfly() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(150000).getBytes(); byte[] key = new String("_testSetWithCompressionCrossRead").getBytes(); long lifetime = 2500; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is " + data.length + ", compressed length is " + dataLength); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); Thread.sleep (2000); junoResponse = junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); //System.out.println (" version is " + junoResponse.getVersion()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testExceedsCompressLimit() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(800000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testExceedsCompressLimit").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is:" + data.length + "compressed length is " + dataLength); try { junoReactClient.set(key, data, (long)lifetime).block(); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } @Test public void testUpdateExceedsMax() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(300000).getBytes(); byte[] updateD = DataGenUtils.createCompressablePayload(800000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testExceedsCompressLimit").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; int updateDLength = Snappy.compress(updateD).length; LOGGER.info("data original length is:" + data.length + "compressed length is " + dataLength); LOGGER.info("updatedata original length is:" + data.length + "compressed length is " + updateDLength); JunoResponse junoResponse = junoReactClient.set(key, data, (long)lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse junoResponse1 = junoReactClient.update(key, updateD).block(); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } // @Test // public void testSetExceedsVersion() throws Exception { // LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); // update(key, data1, lifetime1) // LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); // byte[] data = DataGenUtils.genBytes(2000); // byte[] key = DataGenUtils.createKey(50).getBytes(); // long lifetime = 25; // // try { // for (int i=0; i<40000; i++) { // JunoResponse junoResponse = junoReactClient.set(key, data, lifetime); // AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); // // JunoResponse junoResponse1 = junoReactClient.get(key); // AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); // LOGGER.info("get version is " + junoResponse1.getVersion()); // } // }catch(Exception mex){ // LOGGER.debug(mex.getMessage()); // LOGGER.info("Exception", mex.getMessage()); // LOGGER.info("2"); // LOGGER.info("Completed"); // } // } }
80
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchCreateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xerial.snappy.Snappy; import rx.Observable; import rx.observables.BlockingObservable; public class BatchCreateTest{ private JunoAsyncClient junoClient; private JunoAsyncClient asyncJunoClient; private JunoClient junoClient2; private JunoClient junoClient3; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Properties pConfig3; private int syncFlag; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchCreateTest.class); URL url = BatchCreateTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); LOGGER.debug("Read syncFlag test to findout what needs to be run"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); URL url2 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); pConfig3 = new Properties(); pConfig3.load(url2.openStream()); pConfig3.setProperty(JunoProperties.ENABLE_RETRY, "true"); pConfig3.setProperty(JunoProperties.RESPONSE_TIMEOUT, "10"); try { junoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); asyncJunoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); junoClient3 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); } catch (Exception e) { LOGGER.debug("Exception occured : " + e.getMessage()); } Thread.sleep(1000); } @Test public void testBatchRetry() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); payload[i] = DataGenUtils.createKey(1024).getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, 180, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; batchResp = junoClient3.doBatch(list); int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertTrue (OperationStatus.Success.getCode() == mResponse.getStatus().getCode() || OperationStatus.ResponseTimeout.getCode() == mResponse.getStatus().getCode()); if(OperationStatus.Success.getCode() == mResponse.getStatus().getCode()) AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } } /** * Create and get multiple keys using batch create * @throws JunoException */ @Test public void testBatchCreate() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[numKeys-1] = DataGenUtils.createKey(128).getBytes(); Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204700); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); payload[numKeys-1] = DataGenUtils.createKey(204700).getBytes(); ttl[i] = 100; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { String mKey=new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals (hmapTTL.get(mKey), String.valueOf(mResponse.getTtl())); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } Iterable<JunoResponse> getBatchResp = null; try { if (syncFlag == 1) { LOGGER.debug("before blocking mode batch get " + System.currentTimeMillis()); getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { LOGGER.debug("before non-blocking mode batch get " + System.currentTimeMillis()); getBatchResp = BatchTestSubscriber.async_dobatch(junoClient, list1); } LOGGER.debug("after batch get " + System.currentTimeMillis()); int i = 0; for (JunoResponse response: getBatchResp) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey))-16 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); AssertJUnit.assertEquals (new String(hmap.get(mkey)), new String(response.getValue())); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException ex) { LOGGER.debug("Exception occured:" + ex.getMessage() ); AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with 1 key duplicated * Verify the batch create give correct errror for duplicated key * Verify other keys are successful * @throws JunoException */ @Test public void testBatchCreateDuplicateKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Create a key first "); byte[] new_key = DataGenUtils.createKey(64).getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse resp = asyncJunoClient.create(new_key, data).toBlocking().value(); AssertJUnit.assertEquals (OperationStatus.Success, resp.getStatus()); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with key 7 a duplicated key"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, Integer> hmapVersion = new HashMap<String, Integer>(); HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(20).getBytes(); key[7] = new_key; hmapStatus.put (new String(key[i]), OperationStatus.Success ); hmapStatus.put (new String(key[7]), OperationStatus.UniqueKeyViolation); hmapVersion.put(new String(key[i]), 1); hmapVersion.put(new String(key[7]), 0); String str = "Hello Testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; //Expected status; hmap.put(new String(key[i]), payload[i]); hmap.put(new String(key[7]),data); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { Iterable<JunoResponse> batchResp = null; Iterable<JunoResponse> synBatchResp = null; if (syncFlag == 1) { synBatchResp = junoClient2.doBatch(list); int j=0; for (JunoResponse mResponse: synBatchResp) { String mKey=new String(mResponse.getKey()); AssertJUnit.assertEquals (hmapStatus.get(mKey), mResponse.getStatus()); AssertJUnit.assertEquals ((long)hmapVersion.get(mKey), mResponse.getVersion()); j++; } AssertJUnit.assertEquals(j, numKeys); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); int i = 0; for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals ((long)hmapVersion.get(mkey), mResponse.getVersion()); AssertJUnit.assertEquals (hmapStatus.get(mkey), mResponse.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); } } catch (JunoException mex) { //LOGGER.debug("Error code: " + mex.getOperationStatus().getCode()); LOGGER.debug("Exception occurs: " + mex.getMessage()); } LOGGER.debug("\n===Batch Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; Iterable<JunoResponse> getSynBatchResp = null; for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } if (syncFlag == 1) { getSynBatchResp = junoClient2.doBatch(list1); int j=0; for (JunoResponse mResponse: getSynBatchResp) { String mKey=new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue (1 == mResponse.getVersion()); AssertJUnit.assertEquals(hmap.get(mKey), mResponse.getValue()); j++; } AssertJUnit.assertEquals(j, numKeys); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); int i = 0; for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue (1 == response.getVersion()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); i++; } AssertJUnit.assertEquals(i, numKeys); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with 1 empty key * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateEmptyKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with one zero-length key"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(127).getBytes(); key[4] = "".getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try{ LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with 2 NULL keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[3] = null; key[9] = null; String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp; LOGGER.error( "\n===Batch Create is sent "); if (syncFlag == 1) { batchResp=junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with keys >=257 keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreate129BytesKeys() throws JunoException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with more than 1 key >= 129 bytes"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long> (); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(128).getBytes(); key[4] = DataGenUtils.createKey(129).getBytes(); payload[i] = DataGenUtils.createKey(30).getBytes(); ttl[i] = 20; hmap.put(new String(key[i]),payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable <JunoResponse> resp; if (syncFlag == 1) { resp = junoClient.doBatch(list).toBlocking().toIterable(); } else { resp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 0; for (JunoResponse response: resp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); i++; } } AssertJUnit.assertEquals(i, numKeys-1); //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with keys having 0 or null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateZeroPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with some keys having zero payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; ArrayList <JunoRequest> list = new ArrayList <JunoRequest>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); payload[4] = "".getBytes(); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag == 1) { BlockingObservable <JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not throw for zero payload", false); } ArrayList <JunoRequest> list1 = new ArrayList<JunoRequest>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); LOGGER.debug("value get is " + new String(response.getValue())); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } AssertJUnit.assertEquals(i, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (Exception ex) { AssertJUnit.assertTrue(false); } } /** * Create batch keys with keys having 0 or null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateNullPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with some keys having null payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap <String, Long> hmapTTL = new HashMap<String, Long>(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); payload[0] = null; payload[4] = "".getBytes(); ttl[i] = 20; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable <JunoResponse> batchResp = null; try { if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue("batch create for one item null payload shouldn't fail", false); } int i = 0; for (JunoResponse response: batchResp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); i++; } } AssertJUnit.assertEquals(i, numKeys-1); //Batch Get ArrayList <JunoRequest> list1 = new ArrayList<JunoRequest>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3); i++; } } AssertJUnit.assertEquals(i, numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with a key having > 200KB payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateMoreThan200KPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > 200KB payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.genBytes(30); byte[] data = DataGenUtils.genBytes(204801); payload[4] = data; ttl[i] = 20; LOGGER.debug("key " + i + " is " + new String(key[i])); hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag == 1) { BlockingObservable <JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (Exception mex) { AssertJUnit.assertTrue("batch create shouldn't fail", false); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with a key having TTL more than 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateTTLmorethan3days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > lifetime > 3 days"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap<String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.createKey(40).getBytes(); ttl[i] = 20; ttl[1] = 259201; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag == 1) { BlockingObservable resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for one item exceeds max lifetime", false); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with different TTL and payload * This test is used to test connection error * @throws JunoException */ @Test public void testBatchCreateDiffLifeTimePayloads(){ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); LOGGER.debug("ttl1: " + ttl1); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 2048)); payload[4] = DataGenUtils.genBytes(500); ttl[i] = DataGenUtils.rand(r, 200, 8600); ttl[4] = 800; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue (i == numKeys); } catch (JunoException mex) { //LOGGER.debug(String.valueOf(mex.getOperationStatus().getCode())); //LOGGER.debug(mex.getOperationStatus().getErrorText()); //LOGGER.debug(mex.getOperationStatus().name()); LOGGER.debug("Exception: " + mex.getMessage()); AssertJUnit.assertTrue (false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } try { Iterable<JunoResponse> getBatchResp = null; if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey))-10 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); } LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { AssertJUnit.assertTrue (false); } } /** * Create batch keys without TTL * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask is there anyway to passin default TTL */ @Test public void testBatchCreateNoLifeTime() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; HashMap<String, Long> hmapTTL = new HashMap<String, Long>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); payload[3] = DataGenUtils.genBytes(204800); ttl[i]=100; ttl[4] = 0; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } Iterable<JunoResponse> batchResp = null; try { if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue("create without 0 ttl for one item shouldn't fail", false); } int i = 0; for (JunoResponse response: batchResp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { if(OperationStatus.ResponseTimeout != response.getStatus()) { AssertJUnit.assertTrue(OperationStatus.Success == response.getStatus() || OperationStatus.UniqueKeyViolation == response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey) - 3); } i++; } } AssertJUnit.assertEquals(i, numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchCreateZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch create"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> batchResp = null; try { if (syncFlag == 1) { BlockingObservable <JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); LOGGER.info("0"); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); //AssertJUnit.assertTrue(OperationStatus.IllegalArgument == mex.getOperationStatus()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys, many params passed to Juno Request Item list * Verify keys are created successfully * @throws JunoException */ @Test public void testBatchCreateManyParams() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap <String, String> hmapTTL = new HashMap <String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); LOGGER.debug("ttl1: " + ttl1); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 2048)); payload[4] = DataGenUtils.genBytes(5000); ttl[i] = DataGenUtils.rand(r, 200, 86400); ttl[4] = 259200; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); //Passing version in the Juno Request Item list JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key" + i + ": "+ mResponse.getKey()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue ( i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue (false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } if (syncFlag == 1) { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { getBatchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey)) - 8 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Temporally create test to try understand async toblocking behavior, will remove later * @throws JunoException */ @Test public void testBatchCreateToBlocking() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(100).getBytes(); payload[i] = DataGenUtils.createKey(2000).getBytes(); ttl[i] = 100; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { BlockingObservable<JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } catch (JunoException e) { AssertJUnit.assertTrue("batchcreate shouldn't get juno exception", false); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item); } Iterable<JunoResponse> getBatchResp = null; try { getBatchResp = junoClient.doBatch(list1).toBlocking().toIterable(); } catch (JunoException e) { AssertJUnit.assertTrue("batchget shouldn't get juno exception", false); } int i = 0; for (JunoResponse response: getBatchResp) { LOGGER.debug("in get response step " + System.currentTimeMillis()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Check response Timeout exception * @throws JunoException */ //@Test public void testBatchCreateResponseTimeout() throws IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url1 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); pConfig1.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoAsyncClient asyncJunoClient1 = null; try { asyncJunoClient1 = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); } catch (Exception e) { LOGGER.debug("Exception occured : " + e.getMessage()); } int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(204800); ttl[i] = DataGenUtils.rand(r, 200, 86400); ttl[4] = 259200; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable <JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = asyncJunoClient1.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient1, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.ResponseTimeout,mResponse.getStatus()); i++; } AssertJUnit.assertTrue ( i == numKeys); } catch (JunoException mex) { //mex.printStackTrace(); AssertJUnit.assertTrue(false); LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Response Timed out")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Check Connection Timeout exception * @throws JunoException */ //@Test public void testBatchCreateConnectionError() throws IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url1 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); pConfig1.setProperty(JunoProperties.CONNECTION_TIMEOUT, "1"); JunoAsyncClient asyncJunoClient1 = null; try { asyncJunoClient1 = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); } catch (Exception e) { LOGGER.debug("Exception occured : " + e.getMessage()); } int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); payload[i] = DataGenUtils.genBytes(204000); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)20, JunoRequest.OperationType.Create); list.add(item); } try { Observable<JunoResponse> batchResp = null; batchResp = asyncJunoClient1.doBatch(list); //TODO: ASK AssertJUnit.assertTrue("Connection Error Exception not happening", false); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("connection timed out")); } } /** * This is negative test case only enable when junoserv config and juno property set to * allow 10M payload and we'd like to see how large payload batch behave * Verify appropriate JunoException is thrown * @throws JunoException */ //@Test public void testBatchCreateMoreThan8MPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > 8MB payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.genBytes(30); byte[] data = DataGenUtils.genBytes(88480100); payload[8] = data; ttl[i] = 20; LOGGER.debug("key " + i + " is " + new String(key[i])); hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag == 1) { BlockingObservable <JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (Exception mex) { LOGGER.debug("Exception occured: batch create fail due to large payload"); AssertJUnit.assertTrue("batch create shouldn't fail", true); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); LOGGER.debug("mkey in get is " + mkey); if ( mkey.equals(new String(key[8]))) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= hmapTTL.get(mkey)-3 ); AssertJUnit.assertEquals(response.getValue(), hmap.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { LOGGER.debug("Exception occured: batch get fail due to large payload?, shouldn't"); AssertJUnit.assertTrue(false); LOGGER.info("2"); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch and update with compressed payload larger than max 2048000 * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateExceedsCompressMax() throws Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, String> hmapTTL2 = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Set"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); payload[4] = DataGenUtils.createCompressablePayload(100000).getBytes(); ttl[i]=1200; hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = junoClient.doBatch(list).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mKey)) - 5 <= mResponse.getTtl() && mResponse.getTtl() <= Integer.parseInt(hmapTTL.get(mKey))); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); String str = "Update Hello Testing, Happy Friday" + i; upayload[i] = str.getBytes(); if (i == 4) { upayload[i] = DataGenUtils.createCompressablePayload(800000).getBytes(); } ttl[i] = 1200; hmap.put(new String(key[i]), upayload[i]); hmapTTL2.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest uitem = new JunoRequest(key[i], upayload[i], (long)1, ttl[i], JunoRequest.OperationType.Update); ulist.add(uitem); } int dataLength = Snappy.compress(upayload[4]).length; LOGGER.info("upayload6 original length is " + upayload[4].length + "compressed length is " + dataLength); Iterable<JunoResponse> batchResp= null; if (syncFlag == 1) { batchResp = junoClient.doBatch(ulist).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, ulist); } for (JunoResponse mResponse: batchResp) { String mKey=new String(mResponse.getKey()); String upayloadStr = new String(upayload[4]); String mkeyStr = new String(hmap.get(mKey)); if ( new String(hmap.get(mKey)).equals(new String(upayload[4])) ) { LOGGER.info("enter into if, value is " + upayloadStr.length() + ", payload6 is " + mkeyStr.length()); AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); LOGGER.info("2"); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals (hmapTTL2.get(mKey), String.valueOf(mResponse.getTtl())); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.info("0"); } } LOGGER.info("Completed"); } }
81
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ReactorUpdateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ReactorUpdateTest{ private JunoClient junoClient; private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoReactClient junoReactClient2; private Properties pConfig; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException { URL url = JunoClientFactory.class.getResource("/com/paypal/juno/Juno.properties"); LOGGER = LoggerFactory.getLogger(UpdateTest.class); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoReactClient1 = JunoClientFactory.newJunoReactClient(url); URL url2 = JunoClientFactory.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try { Thread.sleep(3000); junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } catch (Exception ex) { LOGGER.debug(ex.getMessage()); } } @Test public void testUpdateWithoutTTL() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info(new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data).block(); // It uses the default TTL 1800sec AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } JunoResponse junoResponse1 = junoReactClient.update(key, data).block(); // Update without TTL AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertFalse(1800 == junoResponse1.getTtl()); // It cannot be 1800 as we waited for 10sec LOGGER.info("Completed"); } /** * Send a update request with different payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithDiffPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] data2 = DataGenUtils.genBytes(20); byte[] data3 = DataGenUtils.genBytes(40); byte[] data4 = DataGenUtils.genBytes(800); long lifetime = 22000; JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoReactClient.update(key, data1).block(); //ttl won't be updated AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); assert (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); junoResponse = junoReactClient.update(key,data2, (long)lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(3 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); junoResponse = junoClient.update(key, data3, (long)10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(4 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); junoResponse = junoReactClient.update(key, data4, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(5 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-5); JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(5 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data4.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data4), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with same payload * @throws JunoException * @throws IOException */ @Test public void testUpdateWithSamePayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient.update(key, data).block(); AssertJUnit.assertTrue(OperationStatus.Success == junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertTrue(OperationStatus.Success == junoResponse.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(1800-8 <= junoResponse1.getTtl() && junoResponse1.getTtl() <= 1800); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update with empty key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithEmptyKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.update(key, data).block(); AssertJUnit.assertTrue ("Exception should happen for empty key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a update request with null key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.update(key, data).block(); AssertJUnit.assertTrue ("Exception should happen for null key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a update request with no key exists on server and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testUpdateKeyWhichDoesNotExist() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); try { JunoResponse mResponse = junoReactClient.update(key, data).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a update request with 128 bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key1, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.update(key1, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key1, junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with 130 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ junoReactClient.update(key1, data).block(); AssertJUnit.assertTrue ("Exception should happen for key > 128 bytes", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); } } /** * Send a update request with mix of special chars and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = "@@#$%^&*()_+?>,<|}{[]~abc780=.".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.delete(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key1, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.update(key1, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key1, junoResponse.key()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); junoResponse = junoReactClient.get(key1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with zero lifetime, the original lifetime for the * object will be retained. * @throws JunoException * @throws IOException */ @Test public void testUpdateWithZeroLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data, (long)3).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.update(key, data2, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); Thread.sleep (4000); try { JunoResponse mResponse = junoReactClient.update(key, data).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a update request with negative lifetime, exception will be throw * @throws JunoException * @throws IOException */ @Test public void testUpdateWithNegativeLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data, (long)3).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); try { junoReactClient.update(key, data2, (long)-1).block(); AssertJUnit.assertTrue(false); } catch (JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative")); LOGGER.info("0"); LOGGER.info("Completed"); } } /** * Send a update request without lifetime, default lifetime will be updated for existing Juno * @throws JunoException * @throws IOException */ @Test public void testUpdateWithoutLifetime() throws JunoException, Exception{ //TODO: ??? LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data, (long)3).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse=junoReactClient.update(key, data2).block(); // This should not update the Life time AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); Thread.sleep (4000); // Sleep for 2 sec so that the key expires mResponse = junoReactClient.update(key, data).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); mResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with 3 days lifetime and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoReactClient.create(key, data, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.update(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with more than 3 days lifetime and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ JunoResponse junoResponse = junoReactClient.create(key, data, (long)10).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoReactClient.update(key, data, lifetime).block(); AssertJUnit.assertTrue ("Exception should happen for life time > 3 days", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=259201, max configured lifetime=259200")); } } /** * Send a update request with null payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithNullPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoReactClient.update(key, null).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(0, junoResponse1.getValue().length); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertFalse(true); } } /** * Send a update request with empty payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithEmptyPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(64); byte[] key = DataGenUtils.genBytes(64); byte[] data1 = "".getBytes(); try{ JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.update(key, data1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); LOGGER.info("0"); }catch(Exception mex){ AssertJUnit.assertTrue("empty payload should be allowed, why come to exception?", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a update request with 200KB payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204800); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = null; try { junoResponse1 = junoReactClient.update(key, data1).block(); } catch (JunoException ex) { LOGGER.debug("Exception occured: " + ex.getMessage()); AssertJUnit.assertTrue(false); } AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); } /** * Send a update request with more than 200KB payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse =junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoReactClient.update(key, data1).block(); AssertJUnit.assertTrue ("Exception should happen for big payload > 200KB", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a update request with Lifetime and payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithLifeTimeAndPayload() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(1000); long lifetime =5; long lifetime1 = lifetime+2; long lifetime2 = lifetime1+5; byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data, lifetime).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoReactClient.update(key, data1, lifetime1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); //Sleep 11 seconds, key should not expired Thread.sleep (6000); JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); Thread.sleep (4000); //Sleep 2 more seconds for a total of 13 seconds try { JunoResponse mResponse = junoReactClient.update(key, data1, lifetime2).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } //Below tests needs to be reviewed This is important. /************************************************* * Create 2 client objects with namespaces NS1 & NS2. * Create records with same key under both clients. * Update the record under NS1 only. *************************************************/ @Test public void testUpdateInOneOfTheNameSpaces() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data, (long)20).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient1.create(key, data).block(); //same appname, different namespace AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertTrue(OperationStatus.Success == junoResponse1.getStatus()); JunoResponse junoResponse2 = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse2.key()); AssertJUnit.assertTrue(2 == junoResponse2.getVersion()); junoResponse2 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse2.getValue())); AssertJUnit.assertTrue(junoResponse.getValue().length < junoResponse2.getValue().length); AssertJUnit.assertTrue(new String(junoResponse.getValue()) != new String(junoResponse2.getValue())); junoResponse2 = junoReactClient1.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertTrue(1 == junoResponse2.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * Create two clients with the same namespaces but * different application names. Create a record * using client1 with key k1.Update the record * with key k1 using client2. *************************************************/ @Test public void testUpdateWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.status()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.status()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoReactClient2.update(key, data1).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * Attempting update expired data * @throws InterruptedException *************************************************/ @Test public void testUpdateExpiredData() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoReactClient.create(key, data, (long)7).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(10000); try { JunoResponse mResponse = junoReactClient1.update(key, data1).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } }
82
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchReactDestroyTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import com.paypal.juno.client.JunoClient; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BatchReactDestroyTest{ private JunoReactClient junoActClient; private JunoReactClient JunoReactClient; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig2; private enum syncFlag {reactAsync, reactSync}; private int flag; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchDestroyTest.class); URL url = BatchDestroyTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); LOGGER.debug("Read syncFlag"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); flag = Integer.parseInt(sync_flag.trim()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); URL url2 = BatchDestroyTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try { junoActClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); JunoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Batch Create and Batch Update to update lifetime and payload * @throws JunoException */ @Test public void testBatchCreateDestroy() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = (i+10) *20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call LOGGER.debug("enter into sync call" ); batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call LOGGER.debug("enter into async call" ); batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue( i == numKeys); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } List<JunoRequest> dlist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest uitem = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy); dlist.add(uitem); } LOGGER.debug("Destroy key using batch destroy in async mode"); try { Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(dlist).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, dlist); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue( i == numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is thrown for batch destroy", false); } LOGGER.debug("Get key using existing Juno read()"); for (int i = 0; i < numKeys; i ++) { try { JunoResponse junoResponse = junoClient2.get(key[i]); } catch (JunoException mex) { //AssertJUnit.assertEquals (OperationStatus.NoKey,mex.getOperationStatus()); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } } /** * Verify appropriate JunoException is thrown when doing Batch Destroy with a key having zero length * @throws JunoException */ @Test public void testBatchDestroyEmptyKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with 1 key having zero length"); //Juno Request Item for update List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 1028)); key[4] = "".getBytes(); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Destroy); list1.add(item1); } try{ Iterable<JunoResponse> batchResp; LOGGER.debug("Destroy " + numKeys + " keys using batch destroy"); if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoActClient.doBatch(list1).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Bull Destroy for null keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchDestroyNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[3] = null; key[9] = null; JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Destroy); list1.add(item1); } try{ LOGGER.debug("\n===Batch destroy is sent "); Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoActClient.doBatch(list1).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Verify appropriate JunoException is thrown when doing Batch Destroy a key > 256bytes length * @throws JunoException */ @Test public void testBatchDestroy129BytesKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with 1 key having zero length"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); key[4] = DataGenUtils.createKey(129).getBytes(); //System.out.println("key " + i + "is " + new String(key[i])); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 1028)); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Destroy); list.add(item1); } try { LOGGER.debug("Destroy " + numKeys + " keys using batch destroy"); Iterable <JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse response: resp) { String mkey = new String(response.getKey()); //System.out.println(" mkey is " + mkey + "key 4 is " + (new String(key[4]))); if ( mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for long key happened for one item", false); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int i=0; for (JunoResponse response: gResp) { if (response.getStatus() == OperationStatus.NoKey) { i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update on non existing keys * Verify batch update returns correct status for non-key * @throws JunoException */ @Test public void testBatchDestoryKeyNotExists() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; LOGGER.debug("Create request items and create keys"); Random r = new Random(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Destroy); list.add(item); } try { LOGGER.debug("Destroy non-existent keys"); Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals ( OperationStatus.Success, mResponse.getStatus()); } LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { AssertJUnit.assertTrue(false); } } /** * Create batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: same question as testBatchGetZeroItem */ //@Test public void testBatchDestroyZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch Destroy"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Destroy is sent "); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call junoActClient.doBatch(list).toIterable(); } else { //async react call BatchReactSubscriber.async_dobatch(junoActClient, list); } AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } }
83
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchDestroyTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import rx.observables.BlockingObservable; public class BatchDestroyTest{ private JunoAsyncClient junoClient; private JunoAsyncClient asyncJunoClient; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig2; private Logger LOGGER; private int syncFlag; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchDestroyTest.class); URL url = BatchDestroyTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); LOGGER.debug("Read syncFlag test to findout what needs to be run"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); URL url2 = BatchDestroyTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try { junoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); asyncJunoClient = JunoClientFactory.newJunoAsyncClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Batch Create and Batch Update to update lifetime and payload * @throws JunoException */ @Test public void testBatchCreateDestroy() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = (i+10) *20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue( i == numKeys); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } List<JunoRequest> dlist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest uitem = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Destroy); dlist.add(uitem); } LOGGER.debug("Destroy key using batch destroy in async mode"); try { Iterable<JunoResponse> batchResp = junoClient.doBatch(dlist).toBlocking().toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue( i == numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is thrown for batch destroy", false); } LOGGER.debug("Get key using existing Juno read()"); for (int i = 0; i < numKeys; i ++) { try { JunoResponse junoResponse = junoClient2.get(key[i]); } catch (JunoException mex) { //AssertJUnit.assertEquals (OperationStatus.NoKey,mex.getOperationStatus()); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } } /** * Verify appropriate JunoException is thrown when doing Batch Destroy with a key having zero length * @throws JunoException */ @Test public void testBatchDestroyEmptyKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with 1 key having zero length"); //Juno Request Item for update List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 1028)); key[4] = "".getBytes(); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Destroy); list1.add(item1); } try{ Iterable<JunoResponse> batchResp; LOGGER.debug("\n===Batch destroy is sent "); if (syncFlag == 1) { batchResp=junoClient.doBatch(list1).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Bull Destroy for null keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchDestroyNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[3] = null; key[9] = "".getBytes(); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Destroy); list1.add(item1); } try{ Iterable<JunoResponse> batchResp; LOGGER.debug("\n===Batch destroy is sent "); if (syncFlag == 1) { batchResp=junoClient.doBatch(list1).toBlocking().toIterable(); } else { batchResp=BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Verify appropriate JunoException is thrown when doing Batch Destroy a key > 256bytes length * @throws JunoException */ @Test public void testBatchDestroy129BytesKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with 1 key having zero length"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); key[0] = DataGenUtils.createKey(129).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 1028)); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Destroy); list.add(item1); } try { LOGGER.debug("Destroy " + numKeys + " keys using batch destroy"); if (syncFlag == 1) { BlockingObservable<JunoResponse> resp = junoClient.doBatch(list).toBlocking(); resp.subscribe(); } else { BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for long key happened for one item", false); } //batch get List<JunoRequest> list1 = new ArrayList<>(); Iterable <JunoResponse> gResp = new ArrayList<>(); for (int j = 0; j < numKeys; j++) { JunoRequest item1 = new JunoRequest(key[j], (long)0, (long)0, JunoRequest.OperationType.Get); list1.add(item1); } try { if (syncFlag == 1) { gResp = junoClient.doBatch(list1).toBlocking().toIterable(); } else { gResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list1); } int i=0; for (JunoResponse response: gResp) { if (response.getStatus() == OperationStatus.NoKey) { i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (Exception ex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update on non existing keys * Verify batch update returns correct status for non-key * @throws JunoException */ @Test public void testBatchDestoryKeyNotExists() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; LOGGER.debug("Create request items and create keys"); Random r = new Random(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Destroy); list.add(item); } try { LOGGER.debug("Destroy non-existent keys"); Iterable<JunoResponse> batchResp = null; if (syncFlag == 1) { batchResp = junoClient.doBatch(list).toBlocking().toIterable(); } else { batchResp = BatchTestSubscriber.async_dobatch(asyncJunoClient, list); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals ( OperationStatus.Success, mResponse.getStatus()); } LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { AssertJUnit.assertTrue(false); } } /** * Create batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: same question as testBatchGetZeroItem */ //@Test public void testBatchDestroyZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch Destroy"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Destroy is sent "); try { // if (syncFlag == 1) { junoClient.doBatch(list).toBlocking().toIterable(); // } else { // BatchTestSubscriber.async_dobatch(asyncJunoClient, list); // } AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } }
84
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/Juno20ClientConfigurationTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.*; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Juno20ClientConfigurationTest { private Properties pConfig; private JunoClient junoClient5; private Logger LOGGER; @BeforeClass public void setupBC() throws IOException{ LOGGER = LoggerFactory.getLogger(BatchDestroyTest.class); } @BeforeMethod public void setup() throws IOException, InterruptedException { URL url = Juno20ClientConfigurationTest.class.getResource("/com/paypal/juno/Juno.properties"); LOGGER = LoggerFactory.getLogger(Juno20ClientConfigurationTest.class); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); try { junoClient5 = new JunoTestClientImpl(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext(), 0); } catch (Exception e ){ LOGGER.debug(e.getMessage()); } Thread.sleep(3000); } @Test public void testCreateWithKey() throws JunoException, IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); try { LOGGER.info("CorrID : " + Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoClient5.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); }catch(Exception e){ LOGGER.debug(e.getMessage()); } } @Test public void validateEmptyAPP_NAMETest() throws IOException{ pConfig.setProperty(JunoProperties.APP_NAME, ""); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Juno configuration value for property, " + JunoProperties.APP_NAME + " cannot be null or empty")); } } @Test public void validateAPP_NAMEMinSizeTest() throws IOException { pConfig.setProperty(JunoProperties.APP_NAME, DataGenUtils.genAlphaNumString(0)); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Juno configuration value for property, " + JunoProperties.APP_NAME + " cannot be null or empty")); } } @Test public void validateAPP_NAMEMaxSizeTest() throws IOException { pConfig.setProperty(JunoProperties.APP_NAME, DataGenUtils.genAlphaNumString(32)); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); }catch(Exception mex){ mex.getMessage(); Assert.fail("If i reach here"); } } @Test public void validateAPP_NAMEMoreThanMaxSizeTest() throws IOException { pConfig.setProperty(JunoProperties.APP_NAME, DataGenUtils.genAlphaNumString(33)); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Application Name length exceeds MAX LENGTH of 32 bytes")); } } @Test public void validateEmptyNameSpaceTest() throws IOException{ pConfig.setProperty(JunoProperties.RECORD_NAMESPACE , ""); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Juno configuration value for property, " + JunoProperties.RECORD_NAMESPACE + " cannot be null or empty")); } } @Test public void validateNameSpaceMinSizeTest() throws IOException{ pConfig.setProperty(JunoProperties.RECORD_NAMESPACE , DataGenUtils.genAlphaNumString(0)); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Juno configuration value for property, " + JunoProperties.RECORD_NAMESPACE + " cannot be null or empty")); } } @Test public void validateNameSpaceMaxSizeTest() throws IOException{ pConfig.setProperty(JunoProperties.RECORD_NAMESPACE , DataGenUtils.genAlphaNumString(64)); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); }catch(Exception mex){ Assert.fail("I should not be here"); } } @Test public void validateNameSpaceMoreThanMaxSizeTest() throws IOException{ pConfig.setProperty(JunoProperties.RECORD_NAMESPACE , DataGenUtils.genAlphaNumString(65)); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Namespace length exceeds MAX LENGTH of 64 bytes")); } } @Test public void validateEmptyPrimaryIPTest() throws IOException{ pConfig.setProperty(JunoProperties.HOST , ""); pConfig.setProperty(JunoProperties.PORT , ""); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient5.create("emptyPrimaryIP".getBytes(), DataGenUtils.genBytes(10)); AssertJUnit.assertTrue(false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Integer property not valid - Value =")); } } @Test public void validateServerPortTest() throws IOException{ pConfig.setProperty(JunoProperties.PORT , "0"); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient5.create("invalidPort".getBytes(), DataGenUtils.genBytes(10)); AssertJUnit.assertTrue(false); }catch(Exception mex){ //System.out.println("The exception is:"+mex.getMessage()); LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Invalid Juno server port")); } } @Test public void validateEmptyDefaultLifeTimeTest() throws IOException{ pConfig.setProperty(JunoProperties.DEFAULT_LIFETIME , ""); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient5.create("emptyDefaultLifeTime".getBytes(), DataGenUtils.genBytes(10)); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); //assertTrue(mex.getMessage().contains("Invalid property value for the key, default_lifetime")); AssertJUnit.assertTrue(mex.getMessage().contains("Long property not valid - Value")); } } @Test public void validateEmptyConnectionTimeOutTest(){ pConfig.setProperty(JunoProperties.CONNECTION_TIMEOUT , ""); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient5.create("EmptyConnectionTimeOut".getBytes(), DataGenUtils.genBytes(10)); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Integer property not valid - Value")); } } @Test public void validateMaxConnectionTimeOutTest(){ pConfig.setProperty(JunoProperties.CONNECTION_TIMEOUT , "6000"); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient5.create("maxConnectionTimeOut".getBytes(), DataGenUtils.genBytes(10)); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("juno.connection.timeout_msec cannot be greater than")); } } @Test public void validateRetryTest(){ pConfig.setProperty(JunoProperties.ENABLE_RETRY ,"true" ); pConfig.setProperty(JunoProperties.RESPONSE_TIMEOUT,"1"); try { junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient5.create("maxConnectionTimeOut".getBytes(), DataGenUtils.genBytes(10)); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Response Timed out")); } } @Test public void validateNoAPP_NAMEWhenNamePresent() throws FileNotFoundException, IOException{ pConfig.setProperty(JunoProperties.APP_NAME, ""); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); String key = "validateNoAPP_NAMEExist"; JunoResponse junoResponse = junoClient5.delete(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); byte[] data = DataGenUtils.genBytes(10); junoResponse = junoClient5.create(key.getBytes(), data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient5.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, new String(junoResponse.key())); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient5.delete(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); pConfig.clear(); } @Test public void validateValidAPP_NAMENoNamePresent() throws FileNotFoundException, IOException{ pConfig.setProperty(JunoProperties.APP_NAME, "validateNoAPP_NAMEExist"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); String key = "validateNoAPP_NAMEExist"; JunoResponse junoResponse = junoClient5.delete(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); byte[] data = DataGenUtils.genBytes(10); junoResponse = junoClient5.create(key.getBytes(), data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient5.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, new String(junoResponse.key())); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient5.delete(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); pConfig.clear(); } @Test public void validateNameLengthMoreThanAPP_NAMELengthTest() throws FileNotFoundException, IOException{ pConfig.setProperty(JunoProperties.APP_NAME, "validateNameLengthMoreThanAPP_NAMELengthTest"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); String key = "validateNameLengthMoreThanAPP_NAMELengthTest"; JunoResponse junoResponse = junoClient5.delete(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); byte[] data = DataGenUtils.genBytes(10); junoResponse = junoClient5.create(key.getBytes(), data); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient5.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, new String(junoResponse.key())); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); pConfig.clear(); } @Test public void validateNoAPP_NAMENoNamePresent() throws FileNotFoundException, IOException{ pConfig.setProperty(JunoProperties.APP_NAME, ""); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); try{ junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); //if no exception is given }catch(Exception mex){ AssertJUnit.assertTrue(mex.getMessage().contains("Juno configuration value for property, " + JunoProperties.APP_NAME + " cannot be null or empty")); } pConfig.clear(); } }
85
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchReactUpdateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BatchReactUpdateTest{ private JunoReactClient junoActClient; private JunoReactClient junoReactClient; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig2; private enum syncFlag {reactAsync, reactSync}; private int flag; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER = LoggerFactory.getLogger(BatchUpdateTest.class); URL url = BatchUpdateTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); LOGGER.debug("Read syncFlag"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); flag = Integer.parseInt(sync_flag.trim()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); junoActClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient = JunoClientFactory.newJunoReactClient(url); URL url2 = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Batch Create and Batch Update to update lifetime and payload * @throws JunoException */ @Test public void testBatchUpdatePayloadLifetime() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, String> hmapTTL2 = new HashMap<String, String>(); LOGGER.debug("Create " + numKeys + " keys using batch Set"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i]=50; hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mKey)) - 10 <= mResponse.getTtl() && mResponse.getTtl() <= Integer.parseInt(hmapTTL.get(mKey))); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); upayload[i] = DataGenUtils.createKey(payloadlen).getBytes(); upayload[numKeys-1] = DataGenUtils.createKey(204800).getBytes(); ttl[i] = 100; hmap.put(new String(key[i]), upayload[i]); hmapTTL2.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest uitem = new JunoRequest(key[i], upayload[i], (long)1, ttl[i], JunoRequest.OperationType.Update); ulist.add(uitem); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(ulist).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, ulist); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is thrown for batch update", false); } LOGGER.debug("Get key using exisitng exising Juno read()"); for (int i = 0; i < numKeys; i ++) { JunoResponse junoResponse = junoClient2.get(key[i]); String mKey = new String(junoResponse.getKey()); AssertJUnit.assertEquals(key[i], junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(upayload[i]), new String(junoResponse.getValue())); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL2.get(mKey)) - 10 <= junoResponse.getTtl() && junoResponse.getTtl() <= Integer.parseInt(hmapTTL2.get(mKey))); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Verify appropriate JunoException is thrown when doing Batch Update with a key having zero length * @throws JunoException */ @Test public void testBatchUpdateEmptyKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; LOGGER.debug("Create request item with 1 key having zero length"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 1028)); key[4] = "".getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); JunoRequest updateItem = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list.add(item); updateList.add(updateItem); } try{ Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try{ Iterable<JunoResponse> updateResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call updateResp=junoActClient.doBatch(updateList).toIterable(); } else { //async react call updateResp=BatchReactSubscriber.async_dobatch(junoActClient, updateList); } for (JunoResponse response: updateResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(2, response.getVersion()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with 2 NULL keys * Verifyy JunoException does not thrown * @throws JunoException */ @Test public void testBatchUpdateNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> updateList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; key[3] = null; key[9] = null; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); JunoRequest updateItem = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list.add(item); updateList.add(updateItem); } try{ LOGGER.debug("\n===Batch Set is sent "); Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoActClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try{ LOGGER.debug("\n===Batch Update is sent "); Iterable<JunoResponse> updateResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call updateResp=junoActClient.doBatch(updateList).toIterable(); } else { //async react call updateResp=BatchReactSubscriber.async_dobatch(junoActClient, updateList); } for (JunoResponse response: updateResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys with keys >=257 keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdate257BytesKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with more than 1 key >= 257 bytes"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(256).getBytes(); key[1] = DataGenUtils.createKey(259).getBytes(); key[4] = DataGenUtils.createKey(127).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i],System.currentTimeMillis(), JunoRequest.OperationType.Update); list.add(item); } LOGGER.debug("\n===Batch Update is sent "); try { Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for key with > 256 key length happened for only one item", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoActClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoActClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[4])) ) { AssertJUnit.assertTrue(OperationStatus.NoKey == response.getStatus()); } else { AssertJUnit.assertTrue(OperationStatus.IllegalArgument == response.getStatus()); } i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys with keys having 0 or null payload * Verify JunoException does not thrown * @throws JunoException */ @Test public void testBatchUpdateZeroPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 8; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long ttl[] = new long[numKeys]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 50; JunoRequest item = new JunoRequest(key[i], payload[i],(long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int g = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + g + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); g++; } AssertJUnit.assertTrue(g == numKeys); LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); Iterable <JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } List<JunoRequest> list1 = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int h = 0; h < numKeys; h++) { String str = "New Hello Testing testing " + h; payload[h] = str.getBytes(); payload[5] = "".getBytes(); hmap.put(new String(key[h]), payload[h]); JunoRequest item1 = new JunoRequest(key[h], payload[h], (long)1, (long)0, JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list1).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int k = 0; for (JunoResponse mResponse: resp) { String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); k++; } AssertJUnit.assertTrue(k == numKeys); List<JunoRequest> list2 = new ArrayList<>(); for (int h = 0; h < numKeys; h++) { JunoRequest item2 = new JunoRequest(key[h], null, 0, 0, JunoRequest.OperationType.Get); list2.add(item2); } Iterable <JunoResponse> getBatchResponse; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoActClient.doBatch(list2).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoActClient, list2); } int j = 0; for (JunoResponse response: getBatchResponse) { byte[] mkey=response.getKey(); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(new String(mkey)), response.getValue()); j++; } AssertJUnit.assertEquals(j, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Update batch keys with keys having null payload * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask if 0 can be considered as default ttl */ @Test public void testBatchUpdateNullPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 50; hmap.put(new String(key[i]), payload[i]); LOGGER.debug("key " + i + " is " + new String(key[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int h = 0; for (JunoResponse mResponse: resp) { LOGGER.debug("Key: " + h + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); h++; } AssertJUnit.assertTrue(h == numKeys); LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "New Hello Testing testing " + i; payload[i] = str.getBytes(); payload[2] = null; payload[4] = null; ttl[i] = 20; if ( i != 2 && i != 4) { hmap.put(new String(key[i]), payload[i]); } JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list1).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int k = 0; for (JunoResponse mResponse: resp) { LOGGER.debug("Key: " + k + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); k++; } AssertJUnit.assertTrue(k == numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for null payload happened only for one item", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoActClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoActClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); if ( mkey.equals(new String(key[2])) || mkey.equals(new String(key[4])) ) { AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals ( 0, response.getValue().length); } else { LOGGER.debug("mkey is " + mkey + " version is " + response.getVersion()); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); } i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys with keys having > 200KB payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateMoreThan200KPayLoad() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); HashMap <String, String> hmapData = new HashMap <String, String>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i]=30; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int h = 0; for (JunoResponse mResponse: resp) { LOGGER.debug("Key: " + h + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); h++; } AssertJUnit.assertTrue(h == numKeys); LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "New Hello Testing testing " + i; payload[i] = str.getBytes(); byte[] data = DataGenUtils.genBytes(204801); payload[3] = data; ttl[i]=50; hmapData.put(new String(key[i]), new String(payload[i])); hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list1).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int k = 0; for (JunoResponse mResponse: resp) { String mKey = new String(mResponse.getKey()); if ( mKey.equals(new String(key[3]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); k++; } } AssertJUnit.assertTrue(k == numKeys-1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for > 200K payload happened only on one item", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoActClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoActClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); if ( mkey.equals(new String(key[3])) ) { AssertJUnit.assertTrue(1 == response.getVersion()); } else { LOGGER.debug("mkey is " + mkey + " version is " + response.getVersion()); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals(hmapData.get(new String(mkey)), new String(response.getValue())); } AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= response.getTtl()-5); i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Update batch keys TTL > 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchUpdateMoreThan3Days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = (i + 11) * 2; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int a = 0; for (JunoResponse mResponse: resp) { LOGGER.debug("Key: " + a + ": "+ mResponse.getKey()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); a++; } AssertJUnit.assertTrue(a == numKeys); LOGGER.debug("Create Juno request list for Batch Update with some keys having zero payload"); List<JunoRequest> list1 = new ArrayList<>(); for (int g = 0; g < numKeys; g++) { String str = "New Hello Testing testing " + g; payload[g] = str.getBytes(); ttl[g] = 100; ttl[0] = 259201; if ( g != 0 ) { hmapTTL.put(new String(key[g]), ttl[g]); } JunoRequest item1 = new JunoRequest(key[g], payload[g], (long)1, ttl[g], JunoRequest.OperationType.Update); list1.add(item1); } LOGGER.debug("\n===Batch Update is sent "); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoActClient.doBatch(list1).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } int k = 0; for (JunoResponse mResponse: resp) { String mkey = new String(mResponse.getKey()); if ( mkey.equals(new String(key[0])) ) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); k++; } } AssertJUnit.assertTrue(k == numKeys-1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for TTL > 3days happened on one item ", false); } //Batch Get ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoActClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoActClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); if ( mkey.equals(new String(key[0])) ) { AssertJUnit.assertTrue(1 == response.getVersion()); } else { AssertJUnit.assertTrue(2 == response.getVersion()); } AssertJUnit.assertTrue(response.getTtl() <= hmapTTL.get(mkey) && response.getTtl() >= response.getTtl()-5); i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create and get multiple keys using batch create * @throws JunoException //TODO: so updte with empty lifetime is fine? */ @Test public void testBatchUpdateNoLifetime() throws JunoException , InterruptedException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; Long[] ttl = new Long[numKeys]; long[] updatettl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using existing Juno Create"); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = 9L; JunoResponse mResponse = junoClient2.create(key[i], payload[i], ttl[i]); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys without lifetime using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday! Testing again" + i; upayload[i] = str.getBytes(); hmap.put(new String(key[i]), upayload[i]); JunoRequest uitem = new JunoRequest(key[i], upayload[i], (long)1, updatettl[i], JunoRequest.OperationType.Update); ulist.add(uitem); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(ulist).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, ulist); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.debug("ttl for item " + i + " is " + mResponse.getTtl()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch update", false); } Thread.sleep (5000); LOGGER.debug("Get key using existing Juno read(), keys still exist"); for (int i = 0; i < numKeys; i ++) { try { JunoResponse junoResponse = junoClient2.get(key[i]); AssertJUnit.assertEquals(key[i], junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(upayload[i]), new String(junoResponse.getValue())); } catch (JunoException ex) { LOGGER.debug("Exception occured at get " + ex.getMessage()); } } LOGGER.debug("Sleep for keys to expire"); Thread.sleep (10000); for (int i = 0; i < numKeys; i ++) { try { JunoResponse response = junoClient2.get(key[i]); } catch (JunoException mex) { LOGGER.debug("why exception occured here? " + mex.getMessage()); } } List<JunoRequest> glist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest gitem = new JunoRequest(key[i], upayload[i], (long)1, updatettl[i], JunoRequest.OperationType.Update); glist.add(gitem); } Iterable<JunoResponse> getBatchResponse; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoActClient.doBatch(glist).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoActClient, glist); } int i = 0; for (JunoResponse response: getBatchResponse) { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update on non existing keys * Verify batch update returns correct status for non-key * @throws JunoException */ @Test public void testBatchUpdateKeyNotExists() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; byte[][] upayload = new byte[numKeys][]; long ttl[] = new long[numKeys]; HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); Random r = new Random(); LOGGER.debug("Create request items and create keys"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 100)); ttl[i] = 30; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertTrue( i == numKeys); }catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } //Juno Request Item for update List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[3] = "12345".getBytes(); hmapStatus.put(new String(key[i]), OperationStatus.Success); hmapStatus.put(new String(key[3]), OperationStatus.NoKey); upayload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 20)); JunoRequest item1 = new JunoRequest(key[i], payload[i], (long)1, (long)0, JunoRequest.OperationType.Update); list1.add(item1); } try { LOGGER.debug("Update " + numKeys + " keys with version 0 using batch Update"); Iterable<JunoResponse> batchResp= null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); AssertJUnit.assertEquals (hmapStatus.get(mkey), mResponse.getStatus()); if (mResponse.getStatus() == OperationStatus.Success) { AssertJUnit.assertTrue(2 == mResponse.getVersion()); } } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update with version = 0 * Verify batch update is successful and return the next version * @throws JunoException //TODO: TTL 0 for set is allowable and will set default ttl 3600? * //TODO: so update does not have response value back? */ @Test public void testBatchUpdateVersion0() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; byte[][] upayload = new byte[numKeys][]; HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); int[] version = new int [numKeys]; Random r = new Random(); LOGGER.debug("Create request item and create items using batch create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 100)); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp= null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); }catch (JunoException mex) { AssertJUnit.assertTrue(false); } //Juno Request Item for update List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { version[i] = 0; upayload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 20)); hmap.put(new String(key[i]), upayload[i]); JunoRequest item1 = new JunoRequest(key[i], upayload[i], version[0], (long)0, JunoRequest.OperationType.Update); list1.add(item1); } try { LOGGER.debug("Update " + numKeys + " keys with version 0 using batch Update"); Iterable<JunoResponse> batchResp= null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertTrue(1800 - 8 <= mResponse.getTtl() && mResponse.getTtl() <= 1800); } } catch (JunoException mex) { AssertJUnit.assertTrue(false); } List<JunoRequest> list2 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list2.add(item); } try { Iterable<JunoResponse> batchResp=null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list2).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list2); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); String mKey = new String(mResponse.getKey()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertEquals (hmap.get(mKey), mResponse.getValue()); LOGGER.debug("ttl of " + mKey + " is " + mResponse.getTtl()); AssertJUnit.assertTrue(1800 - 11 <= mResponse.getTtl() && mResponse.getTtl() <= 1800); } } catch (JunoException mex) { AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform a batch Update with version < current version * Verify batch update is successful and return the next version * @throws JunoException //TODO: check with Stephane should version update behave like that? * //TODO: check with Joseph, update seems just ignore the pass in version number but 1?? * //ask update doesn't get value back? * */ @Test public void testBatchUpdateInvalidVersion() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; byte[][] upayload = new byte[numKeys][]; byte[][] udate_payload = new byte[numKeys][]; int[] version = new int [numKeys]; long[] ttl = new long [numKeys]; for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = 20L; JunoResponse mResponse = junoClient2.create(key[i], payload[i], ttl[i]); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } LOGGER.debug("Calling batch update to update keys without passing version"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday, Try again" + i; upayload[i] = str.getBytes(); version[i] = 5; JunoRequest item1 = new JunoRequest(key[i], upayload[i], version[i], (long)0, JunoRequest.OperationType.Update); list1.add(item1); } try { Iterable<JunoResponse> batchResp=null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list1).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list1); } for (JunoResponse mResponse: batchResp) { AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); LOGGER.debug("version is " + mResponse.getVersion()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); } } catch (JunoException mex) { LOGGER.debug("Exception occurs for update without version passing: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.debug("Calling batch update to update keys, some having invalid version"); List<JunoRequest> list2 = new ArrayList<>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday, Try again. Have a good weekend" + i; udate_payload[i] = str.getBytes(); ttl[i] = 30; version[i] = 6; //next version should be 7 version[3] = 4; version[4] = 0; //OK version[5] = -1; //OK version[6] = 65535; //OK version[7] = 1; hmapStatus.put(new String(key[i]), OperationStatus.Success); hmapStatus.put(new String(key[7]), OperationStatus.ConditionViolation); hmap.put(new String(key[i]), udate_payload[i]); hmap.put(new String(key[7]), upayload[7]); JunoRequest item2 = new JunoRequest(key[i], udate_payload[i], version[i], ttl[i], JunoRequest.OperationType.Update); list2.add(item2); } try { Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoActClient.doBatch(list2).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoActClient, list2); } int i = 0; for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); LOGGER.debug("=======Status: for " + mkey + " is " + mResponse.getStatus() + " - Version: " + mResponse.getVersion()); AssertJUnit.assertEquals(hmapStatus.get(mkey), mResponse.getStatus()); if (mResponse.getStatus() == OperationStatus.Success) { AssertJUnit.assertTrue(3 == mResponse.getVersion()); i++; } } AssertJUnit.assertTrue ( i == numKeys - 1); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } List<JunoRequest> list3 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list3.add(item); } try { Iterable<JunoResponse> batchResp = junoActClient.doBatch(list3).toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { String mkey = new String(mResponse.getKey()); AssertJUnit.assertEquals (new String (hmap.get(mkey)), new String (mResponse.getValue())); i++; } AssertJUnit.assertTrue ( i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(false); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: aost realsed */ //@Test public void testBatchUpdateZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch Update"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); try { junoActClient.doBatch(list).toIterable(); AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Batch Create and Batch Update to update lifetime and payload * @throws JunoException */ @Test public void testBatchUpdatePayloadLifetimeVersion() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); //int numKeys = 100; int numKeys = 5; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; long[]creationTime = new long[numKeys]; long[]getTime = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Set"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); creationTime[i] = System.currentTimeMillis(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = junoActClient.doBatch(list).toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch create", false); } byte[][] upayload = new byte[numKeys][]; LOGGER.debug("Update " + numKeys + " keys using batch Update()"); List<JunoRequest> ulist = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { String str = "Hello Testing, Happy Friday! Testing again" + i; upayload[i] = str.getBytes(); ttl[i] = 100; hmap.put(new String(key[i]), upayload[i]); JunoResponse gResponse = junoClient2.get(key[i]); AssertJUnit.assertEquals (OperationStatus.Success,gResponse.getStatus()); JunoRequest uitem = new JunoRequest(key[i], upayload[i], ttl[i], gResponse.getVersion(), JunoRequest.OperationType.Update); ulist.add(uitem); } try { Iterable<JunoResponse> batchResp= null; batchResp = junoActClient.doBatch(ulist).toIterable(); int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); i++; } AssertJUnit.assertTrue(i == numKeys); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch update", false); } LOGGER.debug("Get key using existing Juno read()"); for (int i = 0; i < numKeys; i ++) { getTime[i] = System.currentTimeMillis(); JunoResponse junoResponse = junoClient2.get(key[i]); AssertJUnit.assertEquals(key[i], junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(upayload[i]), new String(junoResponse.getValue())); AssertJUnit.assertTrue(1800 - ((getTime[i] - creationTime[i])/1000)-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= 1800 -((getTime[i]-creationTime[i])/1000)); } LOGGER.info("0"); LOGGER.info("Completed"); } }
86
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ConditionalUpdateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Properties; import java.util.Random; import org.slf4j.Logger;import com.paypal.juno.client.JunoClient; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ConditionalUpdateTest{ private JunoClient junoClient; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER = LoggerFactory.getLogger(ConditionalUpdateTest.class); URL url = ConditionalUpdateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS"); junoClient = new JunoTestClientImpl(new JunoPropertiesProvider(pConfig),null,0); URL url1 = ConditionalUpdateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); URL url2 = ConditionalUpdateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS"); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Send a cas request with different payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithDiffPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); JunoResponse junoResponse = junoClient.create(key, data, (long)20); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() >= 20-3 && junoResponse.getTtl() <= 20); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() >= 20-3 && junoResponse.getTtl() <= 20); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with same payload - should be successful * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithSamePayload() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas with empty key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithEmptyKey() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); RecordContext rcx = new RecordContext("".getBytes(),(long)1,(long)5,(long)1); try { junoClient.compareAndSet(rcx, data, (long)5); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); }catch(Exception mex){ LOGGER.debug("Exception :"+mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } } /** * Send a cas request with null key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); RecordContext rcx=null; try { junoClient.compareAndSet(rcx, data, (long)5); AssertJUnit.assertTrue ("Exception is not seen for null key", false); }catch(Exception mex){ LOGGER.debug("Exception :"+mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Record Context cannot be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with no key exists on server and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateKeyWhichDoesNotExist() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); RecordContext rcx = new RecordContext("nonexist".getBytes(), (long)1, (long)5, (long)1); try { JunoResponse mResponse = junoClient.compareAndSet(rcx, data, (long)5); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); } finally { LOGGER.info("Completed"); } } /** * Send a cas request with 128 bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith128BytesKey() throws JunoException, Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with 130 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5); AssertJUnit.assertTrue ("Exception is NOT seen for Key = 129 bytes length", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with mix of special chars and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = "@@#$%^&*()_+?>,<|}{[]~abc780=.".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.delete(key1); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.create(key1, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); junoResponse = junoClient.get(key1); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key1, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); // This TTL (2000) is < 2100 so the TTL will not be updated junoResponse = junoClient.compareAndSet(junoResponse.getRecordContext(), data, (long)2000); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 2000 && junoResponse.getTtl() >= 2000-3); junoResponse = junoClient.get(key1, 2200); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(data, junoResponse.getValue()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 2200 && junoResponse.getTtl() >= 2200-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with zero lifetime and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithZeroNegLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); JunoResponse junoResponse = junoClient.create(key, data, (long)10); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)0); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse1.getTtl() <= 10 && junoResponse1.getTtl() > 10-3); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertTrue(junoResponse1.getTtl() <= 10 && junoResponse1.getTtl() > 10-3); try { junoResponse = junoClient.compareAndSet(junoResponse1.getRecordContext(), data1, (long)-1); AssertJUnit.assertTrue(false); } catch (JunoException mex) { LOGGER.debug("Exception occured: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative")); } LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with 3 days lifetime and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); long lifetime = 259200; JunoResponse junoResponse = junoClient.create(key, data, (long)10); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse1.getTtl() <= lifetime && junoResponse1.getTtl() > lifetime-3); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(junoResponse1.getTtl() <= lifetime && junoResponse1.getTtl() > lifetime-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with more than 3 days lifetime and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ JunoResponse junoResponse = junoClient.create(key, data, (long)10); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data,lifetime); AssertJUnit.assertTrue ("Exception is NOT seen for when lifetime is set to > 3 days", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); //System.out.println("Exception :"+mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=259201, max configured lifetime=259200")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with null payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithNullPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), null, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(0, junoResponse1.getValue().length); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertFalse(true); // Expect no exception LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with 0 payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithZeroPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); byte[] data1 = DataGenUtils.genBytes(0); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); LOGGER.info("SUCCESS"); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertFalse(true); // Expect no exception LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); } finally { LOGGER.info("Completed"); } } /** * Send a cas request with 200KB payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWith200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204800); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); } catch (JunoException mex) { LOGGER.debug("exception get is " + mex.getCause().getMessage()); AssertJUnit.fail(mex.getMessage()); } LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Send a cas request with more than 200KB payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertTrue ("Exception is NOT seen for big payload > 200 KB", false); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("ERROR"); LOGGER.info("Completed"); } } /** * Send a cas request with Lifetime and payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testCUpdateWithLifeTimeAndPayload() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(1000); long lifetime =5; long lifetime1 = lifetime+2; long lifetime2 = lifetime+5; byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, lifetime1); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); Thread.sleep(6000); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); Thread.sleep (2000); //Sleep 2 more seconds for a total of 8 seconds try { JunoResponse mResponse = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, lifetime2); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); } LOGGER.info("Completed"); } //Below tests needs to be reviewed This is important. /************************************************* * Create 2 client objects with namespaces NS & NS1. * Create records with same key under both clients. * Update the record under NS only. *************************************************/ @Test public void testCUpdateInOneOfTheNameSpaces() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data, (long)20); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient1.create(key, data1); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse1.getValue(), data1); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse.getValue() != junoResponse1.getValue()); JunoResponse junoResponse2 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse2.key()); AssertJUnit.assertTrue(2 == junoResponse2.getVersion()); junoResponse2 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertTrue(junoResponse.getValue().length < junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse2.getValue())); AssertJUnit.assertTrue(new String(junoResponse.getValue()) != new String(junoResponse2.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /************************************************* * Create two clients with the same namespaces but * different application names. Create a record * using client1 with key k1.Update the record * with key k1 using client2. *************************************************/ @Test public void testCUpdateWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() > prop.getDefaultLifetime()-3); JunoResponse junoResponse1 = junoClient2.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() > prop.getDefaultLifetime()-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /************************************************* * Attempting cas expired data *************************************************/ @Test public void testCUpdateExpiredData() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(6000); try { JunoResponse mResponse = junoClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); } finally { LOGGER.info("Completed"); } }catch(IllegalArgumentException iaex){ LOGGER.debug(iaex.getMessage()); Assert.fail ("Unexpected exception when calling cas on an expired key"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); Assert.fail ("Unexpected exception when calling cas on an expired key"); } } /************************************************* * Attempting cas on key from a different namespace *************************************************/ @Test public void testCUpdateDifferentNamespace() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(10); try{ JunoResponse junoResponse = junoClient.create(key, data, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient1.create(key1, data, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse mResponse = junoClient1.compareAndSet(junoResponse.getRecordContext(), data, (long)10); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue("CAS can have no key error instead of exception", false); } } /************************************************* * Attempting cas to get VersionToOld status *************************************************/ @Test public void testCUpdateVersionTooOld() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data, 10); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); //check for the record junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); String data2 = "New test data to update"; LOGGER.debug("Use compareAndSet to update data"); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data2.getBytes(), new Long (15)); LOGGER.debug("Check for update data"); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (data2, new String (junoResponse1.getValue())); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); LOGGER.debug("Use cas to update with old version"); String data3 = "Update with modified data"; //Use old response version, update shouldn't be successful try { JunoResponse mResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data3.getBytes(), new Long(1)); AssertJUnit.assertEquals (OperationStatus.ConditionViolation,mResponse1.getStatus()); } catch (JunoException mex) { //LOGGER.debug("OperationStatus is " + mex.getOperationStatus()); AssertJUnit.assertTrue ("Exception is seen for Condition violation :"+mex.getMessage(), false); } JunoResponse mResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse1.getStatus()); AssertJUnit.assertEquals (2,mResponse1.getVersion()); AssertJUnit.assertTrue (mResponse1.getTtl() <= 15 && mResponse1.getTtl() > 15-3); AssertJUnit.assertEquals (data2.getBytes().length,mResponse1.getValue().length); AssertJUnit.assertEquals (new String(data2.getBytes()), new String(mResponse1.getValue())); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }catch(IllegalArgumentException iaex){ AssertJUnit.assertTrue("shouldn't get expcetion ", false); } } /************************************************* * Attempting cas() with version too old to update *************************************************/ @Test public void testCUpdateVersionTooOld2() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig1); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); //check for the record junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); String data2 = "New test data to update"; LOGGER.debug("Use cas()to update data"); JunoResponse junoResponse2 = junoClient.compareAndSet(junoResponse.getRecordContext(), data2.getBytes(), new Long (15)); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertTrue (2 == junoResponse2.getVersion()); String data3 = "Other new test data to update again"; LOGGER.debug("Use cas()to update data"); try { JunoResponse junoResponse3 = junoClient.compareAndSet(junoResponse.getRecordContext(), data3.getBytes(), new Long (15)); AssertJUnit.assertEquals (OperationStatus.ConditionViolation, junoResponse3.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for Condition Violation", false); } //Read again to ensure that right data is returned JunoResponse junoResponse4 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse4.getStatus()); AssertJUnit.assertEquals(key, junoResponse4.key()); AssertJUnit.assertTrue(2 == junoResponse4.getVersion()); AssertJUnit.assertEquals(data2, new String(junoResponse4.getValue())); AssertJUnit.assertTrue(junoResponse4.getTtl() <= prop.getDefaultLifetime() && junoResponse4.getTtl() > prop.getDefaultLifetime()-3); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); }catch(IllegalArgumentException iaex){ LOGGER.debug(iaex.getMessage()); } } /** * Send a cas request with different payload and should not generate an exception * @throws JunoException * @throws IOException * Seeing negative version print out * Version: -8 */ //@Test public void testCUpdateVersionOverflow() throws JunoException, IOException{ byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); junoClient.create(key, data, (long)20); long lifetime = 5L; //after 65536, should be overflow for (int i = 0; i < 65540; i++) { lifetime +=1; JunoResponse junoResponse = junoClient.get(key, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); //org.junit.Assert.assertEquals(key, junoResponse1.key()); //org.junit.Assert.assertEquals("NS", junoResponse1.getNamespace()); LOGGER.debug("Version: " + junoResponse1.getVersion()); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); } } }
87
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchReactSetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BatchReactSetTest{ private JunoReactClient junoRctClient; private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private enum syncFlag {reactAsync, reactSync}; private int flag; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchSetTest.class); URL url = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); LOGGER.debug("Read syncFlag"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); flag = Integer.parseInt(sync_flag.trim()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoReactClient = JunoClientFactory.newJunoReactClient(url); URL url1 = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); URL url2 = BatchSetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try{ junoRctClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Create and get multiple keys using batch create * @throws JunoException //TODO: Ask so during set, what version passed in doesn't matter? */ @Test public void testBatchCreateSet() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; Long[] ttl = new Long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using existing Juno Create, no lifetime"); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[numKeys-1] = DataGenUtils.createKey(128).getBytes(); Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); payload[i] = DataGenUtils.createKey(payloadlen).getBytes(); payload[numKeys-1] = DataGenUtils.createKey(204800).getBytes(); JunoResponse mResponse = junoClient2.create(key[i], payload[i]); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); } Long[] ttl1 = new Long[numKeys]; byte[][] payload1 = new byte[numKeys][]; LOGGER.debug("Calling Batch set with lifetime"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { Random r = new Random(); int payloadlen = DataGenUtils.rand(r, 200, 204800); payload1[i] = DataGenUtils.createKey(payloadlen).getBytes(); payload1[numKeys-1] = DataGenUtils.createKey(204800).getBytes(); ttl1[i] = 20L; hmap.put(new String(key[i]), payload1[i]); JunoRequest item1 = new JunoRequest(key[i], payload1[i], (long)0, ttl1[i], System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item1); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoRctClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } int i = 1; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); String mkey = new String(mResponse.getKey()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); i++; } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); } //Read Item List List<JunoRequest> list2 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item2 = new JunoRequest(key[i],(long)0, (long)0, JunoRequest.OperationType.Get ); list2.add(item2); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoRctClient.doBatch(list2).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoRctClient, list2); } int i = 0; for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); LOGGER.debug("Key: " + i + ": "+ response.getKey()); LOGGER.debug("Data: " + new String(response.getValue())); AssertJUnit.assertTrue(2 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); i++; } AssertJUnit.assertEquals(i,numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Set batch keys with 1 empty key * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetEmptyKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Batch set " + numKeys + " keys with one zero-length key"); byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(127).getBytes(); key[4] = "".getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item); } try{ Iterable<JunoResponse> batchResp; LOGGER.debug("\n===Batch Set is sent "); if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoRctClient.doBatch(list).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoRctClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[4]) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with 2 NULL keys * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetNullKeys() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Batch Set " + numKeys + " keys with two null keys"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[3] = null; key[9] = null; String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; //intentionally use below value for set JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item); } try{ Iterable<JunoResponse> batchResp; LOGGER.error( "\n===Batch Create is sent "); if (syncFlag.reactSync.ordinal() == flag) { batchResp=junoRctClient.doBatch(list).toIterable(); } else { batchResp=BatchReactSubscriber.async_dobatch(junoRctClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with keys >=257 keys * Verify JunoException does not thrown * @throws JunoException */ @Test public void testBatchSet257BytesKeys() throws JunoException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Batch set " + numKeys + " keys with more than 1 key >= 257 bytes"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); key[1] = DataGenUtils.createKey(259).getBytes(); key[9] = DataGenUtils.createKey(257).getBytes(); for (int i = 0; i < numKeys; i ++) { if ( i != 1 && i != 9 ) { key[i] = DataGenUtils.createKey(128).getBytes(); } String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Create is sent "); try { int i = 0; Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoRctClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } for (JunoResponse mResponse: resp) { String mkey = new String(mResponse.getKey()); if ( mkey.equals(new String(key[9])) || mkey.equals(new String(key[1])) ) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } } AssertJUnit.assertEquals(i,numKeys-2); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for key with > 256 bytes long happen on one item only", false); } ArrayList <JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoRctClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoRctClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[1])) || mkey.equals(new String(key[9]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); i++; } } AssertJUnit.assertEquals(i,numKeys-2); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with keys having 0 or null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetZeroPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Create " + numKeys + " keys with some keys having zero payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = DataGenUtils.createKey(25); payload[i] = str.getBytes(); payload[5] = "".getBytes(); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); LOGGER.debug("i is " + i + ", key is " + (new String(key[i])) + ", payload is " + (new String(payload[i]))); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); int k = 0; Iterable <JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoRctClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } for (JunoResponse response: resp) { byte[] mkey=response.getKey(); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); k++; } AssertJUnit.assertEquals(k, numKeys); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item1 = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list1.add(item1); } Iterable <JunoResponse> getBatchResponse; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoRctClient.doBatch(list1).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoRctClient, list1); } int j = 0; for (JunoResponse response: getBatchResponse) { byte[] mkey=response.getKey(); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(new String(mkey)), response.getValue()); j++; } AssertJUnit.assertEquals(j, numKeys); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Set batch keys with keys having null payload * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetNullPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Set " + numKeys + " keys with some keys having null payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap <String, byte[]> hmap = new HashMap <String, byte[]>(); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> list1 = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); payload[0] = null; payload[4] = "".getBytes(); hmap.put(new String(key[i]), payload[i]); ttl[i] = 20; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try { Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoRctClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } int i = 0; for (JunoResponse response: resp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for null payload on just one item", false); } for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list1.add(item); } Iterable<JunoResponse> setBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call setBatchResponse = junoRctClient.doBatch(list1).toIterable(); } else { //async react call setBatchResponse = BatchReactSubscriber.async_dobatch(junoRctClient, list1); } int i = 0; for (JunoResponse response: setBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); LOGGER.info("0"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); } for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoRctClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoRctClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[0]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (0, response.getValue().length); } else { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(2 == response.getVersion()); LOGGER.debug("hmap value is " + hmap.get(mkey) + " " + "response value is " + response.getValue() + " i is " + i); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Set batch keys with a key having > 200KB payload * Verify JunoException does not thrown * @throws JunoException */ @Test public void testBatchSetMoreThan200KPayload() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; LOGGER.debug("Set " + numKeys + " keys with a key having > 200KB payload"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, byte[]> hmap = new HashMap<String, byte[]>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.genBytes(204801); payload[numKeys-1] = DataGenUtils.genBytes(20); ttl[i] = 20; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try { int i = 0; Iterable<JunoResponse> resp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoRctClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } for (JunoResponse mResponse: resp) { String mkey = new String(mResponse.getKey()); if ( !mkey.equals(new String(key[numKeys-1]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } } AssertJUnit.assertEquals(i,1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for big payload happened on one item", false); } ArrayList <JunoRequest> getList = new ArrayList<JunoRequest>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); getList.add(item); } Iterable<JunoResponse> getBatchResponse; try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResponse = junoRctClient.doBatch(getList).toIterable(); } else { //async react call getBatchResponse = BatchReactSubscriber.async_dobatch(junoRctClient, getList); } int i = 0; for (JunoResponse response: getBatchResponse) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[numKeys-1]))) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); } else { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); i++; } } AssertJUnit.assertEquals(i,numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } catch (JunoException mex) { LOGGER.debug("Exception occurs at reset: " + mex.getCause().getMessage()); AssertJUnit.assertTrue(false); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with a key having TTL more than 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetTTLmorethan3days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > lifetime > 3 days"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); payload[i] = DataGenUtils.createKey(25).getBytes(); ttl[i] = 20; ttl[1] = 259201; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Set); list.add(item); } LOGGER.debug("\n===Batch Set is sent "); try { int k = 0; Iterable<JunoResponse> resp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoRctClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } for (JunoResponse mResponse: resp) { String mkey = new String(mResponse.getKey()); if ( mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, mResponse.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); k++; } } AssertJUnit.assertEquals(k,numKeys-1); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is not thrown for TTL > 3 days", false); } ArrayList <JunoRequest> list1 = new ArrayList<> (); LOGGER.debug("Read " + numKeys + " keys using batch Get()"); for (int i = 0; i < numKeys; i ++) { JunoRequest item1 = new JunoRequest(key[i], null, (long)0, ttl[i], JunoRequest.OperationType.Get); list1.add(item1); } Iterable<JunoResponse> getBatchResp = null; try { LOGGER.debug("before blocking mode batch get " + System.currentTimeMillis()); if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoRctClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoRctClient, list1); } LOGGER.debug("after batch get " + System.currentTimeMillis()); int i = 0; for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertTrue(OperationStatus.Success == response.getStatus()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertTrue(hmapTTL.get(mkey)-10 <= response.getTtl() && response.getTtl() <= hmapTTL.get(mkey)); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } catch (JunoException ex) { LOGGER.debug("Exception occured:" + ex.getMessage() ); AssertJUnit.assertTrue(false); } } /** * Create batch keys with different TTL and payload * One key has max payload and TTL * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchSetDiffLifeTimePayloads() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); long ttl1 = DataGenUtils.rand(r, 200, 86400); LOGGER.debug("ttl1: " + ttl1); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 2048)); payload[5] = DataGenUtils.genBytes(204800); ttl[i] = DataGenUtils.rand(r, 200, 86400); ttl[5] = 259200; hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoRctClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { //LOGGER.debug("Key: " + i + ": "+ mResponse.getKey()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { //LOGGER.debug("Error code: " + mex.getOperationStatus().getCode()); LOGGER.debug("Exception occurs: " + mex.getMessage()); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, (long)0, 0, JunoRequest.OperationType.Get); list1.add(item); } Iterable<JunoResponse> getBatchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoRctClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoRctClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform set batch keys without TTL * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask create can not have 0 TTL while set can? Why it's 3600 not 1800?? */ @Test public void testBatchSetNoLifeTime() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); Random r = new Random(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); hmap.put(new String(key[i]), payload[i]); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoRctClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoRctClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); i++; } AssertJUnit.assertEquals(i, numKeys); } catch (JunoException mex) { AssertJUnit.assertTrue (false); } LOGGER.debug("Read " + numKeys + " keys using existing Juno read()"); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i++) { JunoResponse response = junoClient2.get(key[i]); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals (new String(payload[i]), new String (response.getValue())); //System.out.println("TTL in Response :"+response.getTtl()); AssertJUnit.assertTrue (1800 - 8 <= response.getTtl() && response.getTtl() <= 1800); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Perform batch set keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: same question as testBatchGetZeroItem */ //@Test public void testBatchSetZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch create"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call junoRctClient.doBatch(list).toIterable(); } else { //async react call BatchReactSubscriber.async_dobatch(junoRctClient, list); } AssertJUnit.assertTrue ("Exception is not thrown for no key in the Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); } } }
88
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/CreateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xerial.snappy.Snappy; public class CreateTest{ private JunoClient junoClient; private JunoClient junoClient1; private JunoClient junoClient2; private JunoClient junoClient3; private JunoClient junoClient4; private JunoClient junoClient5; private JunoClient junoClient6; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Properties pConfig3; private Properties pConfig4; private Logger LOGGER; int syncFlag; @BeforeClass public void setup() throws IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER = LoggerFactory.getLogger(CreateTest.class); URL url = this.getClass().getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "JunoTestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS1"); LOGGER.debug("Read syncFlag test to findout if we need to run test in sync/async mode"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); URL url1 = CreateTest.class.getResource("/com/paypal/juno/Juno.properties"); junoClient1 = JunoClientFactory.newJunoClient(url1); URL url2 = CreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "false"); pConfig2.setProperty(JunoProperties.APP_NAME, "JunoTestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS1"); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); pConfig3 = new Properties(); pConfig3.load(url1.openStream()); pConfig3.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS3"); pConfig3.setProperty(JunoProperties.DEFAULT_LIFETIME, "2900"); pConfig3.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "false"); junoClient3 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); pConfig3.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "true"); junoClient4 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); pConfig4 = new Properties(); pConfig4.load(url1.openStream()); pConfig4.setProperty(JunoProperties.RECORD_NAMESPACE, "NS4"); pConfig4.setProperty(JunoProperties.DEFAULT_LIFETIME, "2900"); pConfig4.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "false"); pConfig4.setProperty(JunoProperties.MAX_LIFETIME, "315360000"); junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig4), SSLUtil.getSSLContext()); pConfig4.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "true"); junoClient6 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig4), SSLUtil.getSSLContext()); Thread.sleep(1000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Send a insert request to the Juno 2.0 server with specified key. * It should not generate any exception, if there is no problem on server side. * @throws JunoException //TODO: ask, don't really need sync_flag as everything is eventually based on async?? * @throws IOException */ @Test public void testCreateWithKey() throws JunoException, IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoPropertiesProvider prop3 = new JunoPropertiesProvider(pConfig3); LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); try { for(int i=0; i < 3; i++){ //create(key, data) LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); JunoResponse mResponse3 = junoClient3.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertTrue(mResponse3.getTtl() <= prop3.getDefaultLifetime() && mResponse3.getTtl() >= prop3.getDefaultLifetime()-3); mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse.getValue())); AssertJUnit.assertTrue (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); LOGGER.debug("default ttl is " + prop.getDefaultLifetime()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); mResponse3 = junoClient3.get(key); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse3.getValue())); AssertJUnit.assertTrue (mResponse3.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertTrue(mResponse3.getTtl() <= 2900 && mResponse3.getTtl() >= 2900-3); LOGGER.info("0"); LOGGER.info("Completed"); } for(int i=0; i < 3; i++){ //create(key,data,ttl) LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoClient.create(key, data, 20); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); JunoResponse mResponse3 = junoClient3.create(key, data, 100); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse.getValue())); AssertJUnit.assertTrue (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertTrue(mResponse.getTtl() <= 20 && mResponse.getTtl() > 20-3); mResponse3 = junoClient3.get(key); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse3.getValue())); AssertJUnit.assertTrue (mResponse3.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertTrue(mResponse3.getTtl() <= 100 && mResponse3.getTtl() > 100-3); LOGGER.info("0"); LOGGER.info("Completed"); } }catch(Exception e) { LOGGER.debug("Exception.."); AssertJUnit.assertFalse("Exception :"+e.getMessage(),true); } } /** * Send a insert request twice with same key to Juno 2.0 server * It should generate UniqueKeyViolation or JunoException exception. * @throws JunoException * @throws IOException */ @Test public void testCreateWithSameKey() throws JunoException, IOException{ LOGGER.info( "TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); //It should have used the configured default TTL AssertJUnit.assertTrue( junoResponse.getTtl() >= (prop.getDefaultLifetime() -3) && junoResponse.getTtl() <= prop.getDefaultLifetime()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse mResponse = junoClient.create(key, data); AssertJUnit.assertEquals (mResponse.getStatus(), OperationStatus.UniqueKeyViolation); LOGGER.info("DupKey"); LOGGER.info("0"); } catch (JunoException ex) { AssertJUnit.assertTrue ("Exception seen for Duplicate key", false); } finally { LOGGER.info("Completed"); } } /** * Send a insert request with empty key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testCreateWithEmptyKey() throws JunoException, IOException{//TODO: reevaluate LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse mResponse = null; try{ junoClient.create(key, data); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); }catch(Exception mex){ Assert.assertEquals("The Document key must not be null or empty", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } key = "Test_key".getBytes(); try{ junoClient.create(key, data,0); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); }catch(Exception mex){ Assert.assertEquals("The Document's TTL cannot be 0 or negative.", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with Null key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testCreateWithNullKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); try{ junoClient.create(key, data); AssertJUnit.assertTrue ("Exception is not seen for null key", false); } catch (JunoException mex) { AssertJUnit.assertEquals("The Document key must not be null or empty", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with 128bytes key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testCreateWith128BytesKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with 256bytes key and should generate IllegalArgumentException * with "Invalid key length. current length=257, max length=256" * @throws JunoException * @throws IOException */ @Test public void testCreateWith129BytesKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.create(key, data); Assert.assertTrue(false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); Assert.assertEquals("The Document key must not be larger than 128 bytes", mex.getCause().getMessage()); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request special characters key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testCreateWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "Q:������������������A:����@@#$%^&*()_+?>,<|}{[]~abc780=.__?|".getBytes(); byte[] data = "Q:������������������������������������A:���������������������������".getBytes(); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data, 100L); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 100 && junoResponse.getTtl() >= 100-3); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with normal lifetime and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testCreateWith10SecLifetime() throws JunoException, IOException, InterruptedException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() > lifetime-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with zero lifetime, default lifetime should be used * @throws JunoException * @throws IOException */ @Test public void testCreateWithZeroLifetime() throws JunoException, Exception{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.create(key, data, (long)0); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be 0 or negative.")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with Negative lifetime and should generate an * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testCreateWithNegativeLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.create(key, data, (long)-1); AssertJUnit.assertTrue ("Exception is NOT seen for negative lifetime", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative. ")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with null lifetime and should generate an * IllegalArgumentException //TODO: should 0 lifetime for create throw exception?? * @throws JunoException * @throws IOException */ @Test public void testCreateWithNullLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.create(key, data, 0); AssertJUnit.assertTrue(false); }catch(JunoException mex) { AssertJUnit.assertEquals("The Document's TTL cannot be 0 or negative.",mex.getCause().getMessage()); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with max lifetime 3 days and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testCreateWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key, (long)10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with more than max lifetime 3 days and should * generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testCreateWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ junoClient.create(key, data, lifetime); AssertJUnit.assertTrue ("Exception is not seen for TTL > 3 days", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with null payload and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testCreateWithNullPayload() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse res = junoClient.create(key, null); AssertJUnit.assertEquals(OperationStatus.Success,res.getStatus()); AssertJUnit.assertEquals(1,res.getVersion()); //AssertJUnit.assertTrue ("Exception is NOT seen for Null payload", false); }catch(Exception mex){ AssertJUnit.assertFalse(true); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with zero size payload and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testCreateWithZeroPayload() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(0); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success , mResponse.getStatus()); AssertJUnit.assertEquals(1, mResponse.getVersion()); mResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success , mResponse.getStatus()); AssertJUnit.assertEquals(1, mResponse.getVersion()); AssertJUnit.assertEquals(key, mResponse.getKey()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with 100KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testCreateWith100KBPayload() throws JunoException, Exception{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(100200); byte[] key = DataGenUtils.genBytes(64); long lifetime = 4; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success , junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success , junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Sleep 3 seconds to expire daata"); Thread.sleep (5000); try { JunoResponse mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is not seen for empty key", false); } finally { LOGGER.info("0"); LOGGER.info("Completed"); } } /** * Send a insert request with 200KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testCreateWith200KBPayload() throws IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204800); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success , junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success , junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with more than 200KB payload and should generate * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testCreateWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoClient.create(key, data); AssertJUnit.assertTrue ("Exception is not seen for payload > 200KB", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with more than 1KB payload and see if its compressed, get * can get both compressed and non-compressed data.Test contains another set of key * which is used to insert data for c++ client to read * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testCreateWithAndWithoutCompression() throws JunoException, Exception{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = new String("Couchbase stores data as key value pairs where the value is a JSON document and the key is an identifier for retrieving that document. By default cbexport will only export the value portion of the document. If you wish to include the key in the exported document then this option should be specified. The value passed to this option should be the field name that the key is stored under.Skips the SSL verification phase. Specifying this flag will allow a connection using SSL encryption, but will not verify the identity of the server you connect to. You are vulnerable to a man-in-the-middle attack if you use this flag. Either this flag or the --cacert flag must be specified when using an SSL encrypted connection Specifies a CA certificate that will be used to verify the identity of the server being connecting to. Either this flag or the --no-ssl-verify flag must be specified when using an SSL encrypted connection. Specifies the number of concurrent clients to use when exporting data. Fewer clients means exports will take longer, but there will be less cluster resources used to complete the export. More clients means faster exports, but at the cost of more cluster resource usage. This parameter defaults to 1 if it is not specified and it is recommended that this parameter is not set to be higher than the number of CPUs on the machine where the export is taking place. Exports JSON data from Couchbase. The cbexport-json command supports exporting JSON docments to a file with a document on each line or a file that contain a JSON list where each element is a document. The file format to export to can be specified with the --format flag. See the DATASET FORMATS section below for more details on the supported file formats.").getBytes(); byte[] for_c_data = new String("For C++ testing data, Couchbase stores data as key value pairs where the value is a JSON document and the key is an identifier for retrieving that document. By default cbexport will only export the value portion of the document. If you wish to include the key in the exported document then this option should be specified. The value passed to this option should be the field name that the key is stored under.Skips the SSL verification phase. Specifying this flag will allow a connection using SSL encryption, but will not verify the identity of the server you connect to. You are vulnerable to a man-in-the-middle attack if you use this flag. Either this flag or the --cacert flag must be specified when using an SSL encrypted connection Specifies a CA certificate that will be used to verify the identity of the server being connecting to. Either this flag or the --no-ssl-verify flag must be specified when using an SSL encrypted connection. Specifies the number of concurrent clients to use when exporting data. Fewer clients means exports will take longer, but there will be less cluster resources used to complete the export. More clients means faster exports, but at the cost of more cluster resource usage. This parameter defaults to 1 if it is not specified and it is recommended that this parameter is not set to be higher than the number of CPUs on the machine where the export is taking place. Exports JSON data from Couchbase. The cbexport-json command supports exporting JSON docments to a file with a document on each line or a file that contain a JSON list where each element is a document. The file format to export to can be specified with the --format flag. See the DATASET FORMATS section below for more details on the supported file formats. End for C++ data").getBytes(); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(64); byte[] key_compress_cplusplus = "keyvalue with data Compression".getBytes(); byte[] key_compress_cplusplus2 = "keyvalue with data Compression2".getBytes(); byte[] key_compress_cplusplus3 = "keyvalue with data Compression3".getBytes(); byte[] key_compress_cplusplus4 = "keyvalue with data Compression4".getBytes(); byte[] key_compress_cplusplus5 = "keyvalue with data Compression5".getBytes(); byte[] key_compress_cpp_destroy = "keyvalue with data Compression for destroy".getBytes(); byte[] key_no_compress_cplusplus = "keyvalue with no data Compression".getBytes(); byte[] key_no_compress_cplusplus2 = "keyvalue with no data Compression2".getBytes(); byte[] key_no_compress_cplusplus3 = "keyvalue with no data Compression3".getBytes(); byte[] key_no_compress_cplusplus4 = "keyvalue with no data Compression4".getBytes(); byte[] key_no_compress_cplusplus5 = "keyvalue with no data Compression5".getBytes(); long ttl = (long)31530; try{ junoClient5.delete(key_compress_cplusplus); junoClient5.delete(key_compress_cplusplus2); junoClient5.delete(key_compress_cplusplus3); junoClient5.delete(key_compress_cplusplus4); junoClient5.delete(key_compress_cplusplus5); junoClient5.delete(key_no_compress_cplusplus); junoClient5.delete(key_no_compress_cplusplus2); junoClient5.delete(key_no_compress_cplusplus3); junoClient5.delete(key_no_compress_cplusplus4); junoClient5.delete(key_no_compress_cplusplus5); junoClient6.delete(key_compress_cplusplus); junoClient6.delete(key_compress_cplusplus2); junoClient6.delete(key_compress_cplusplus3); junoClient6.delete(key_compress_cplusplus4); junoClient6.delete(key_compress_cplusplus5); junoClient6.delete(key_no_compress_cplusplus); junoClient6.delete(key_no_compress_cplusplus2); junoClient6.delete(key_no_compress_cplusplus3); junoClient6.delete(key_no_compress_cplusplus4); junoClient6.delete(key_no_compress_cplusplus5); junoClient5.delete(key_compress_cpp_destroy); Thread.sleep(3000); //Write with payload compression enabled client and read it via client without compression enabled. JunoResponse junoResponse = junoClient4.create(key, data, 1800); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient4.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(Arrays.equals(data, junoResponse.getValue())); JunoResponse junoResponse1 = junoClient3.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(Arrays.equals(data, junoResponse1.getValue())); junoResponse = junoClient6.create(key_compress_cplusplus, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); //below keys are created for c++ batch get, so no need to get here junoResponse = junoClient6.create(key_compress_cplusplus2, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient6.create(key_compress_cplusplus3, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient6.create(key_compress_cplusplus4, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient6.create(key_compress_cplusplus5, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient6.create(key_compress_cpp_destroy, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient6.get(key_compress_cplusplus); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(Arrays.equals(for_c_data, junoResponse.getValue())); junoResponse1 = junoClient5.get(key_compress_cplusplus); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(Arrays.equals(for_c_data, junoResponse1.getValue())); //Write with out compression and read using compression enabled. junoResponse = junoClient3.create(key1, data, 1800); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient3.get(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(Arrays.equals(data, junoResponse.getValue())); junoResponse1 = junoClient4.get(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(Arrays.equals(data, junoResponse1.getValue())); junoResponse = junoClient5.create(key_no_compress_cplusplus, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); //below keys are created for c++ batch get, so no need to get here junoResponse = junoClient5.create(key_no_compress_cplusplus2, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient5.create(key_no_compress_cplusplus3, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient5.create(key_no_compress_cplusplus4, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient5.create(key_no_compress_cplusplus5, for_c_data, ttl); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient5.get(key_no_compress_cplusplus); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(Arrays.equals(for_c_data, junoResponse.getValue())); junoResponse1 = junoClient6.get(key_no_compress_cplusplus); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(Arrays.equals(for_c_data, junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /************************************************* * Send a insert request with same key for two different name spaces and should not * generate exceptions * *************************************************/ @Test public void testCreateWithSameKeyInDifferentNameSpaces() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); byte[] key = "TestKey1".getBytes(); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient1.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient1.create(key, data1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); junoResponse = junoClient1.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); try { junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for No key", false); } junoResponse1 = junoClient1.create(key, data, 30); //insert same key/value with different ttl AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertEquals(junoResponse.getVersion(), junoResponse1.getVersion()); AssertJUnit.assertNotSame(junoResponse.getTtl(), junoResponse1.getTtl()); junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two records with same key and name space. * The 2nd insert fails and should generate an exception *************************************************/ @Test public void testCreateWithSameKeysInSameNameSpace() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create with same key, different data try { JunoResponse mResponse = junoClient.create(key, data2); AssertJUnit.assertEquals (OperationStatus.UniqueKeyViolation,mResponse.getStatus()); LOGGER.info("DupKey"); LOGGER.info("0"); } catch (JunoException ex) { AssertJUnit.assertTrue ("Exception is seen for Duplicate key", false); } JunoResponse gResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, gResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(gResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two clients with same ns but diff app name * Create 1 record each using clients1 and client2. * The 2nd insert will fail. *************************************************/ @Test public void testCreateWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create same key try { JunoResponse mResponse = junoClient2.create(key, data); AssertJUnit.assertEquals (mResponse.getStatus(), OperationStatus.UniqueKeyViolation); LOGGER.info("DupKey"); LOGGER.info("0"); } catch (JunoException ex) { AssertJUnit.assertTrue(false); } finally { LOGGER.info("Completed"); } } //Need to rewrite the below test cases /********************************************** * app_name length > 32 (MF_APP_NAME_MAX_LEN) *********************************************/ @Test public void testValidateAppnameLength() throws JunoException, IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); String appname = DataGenUtils.genString(32); String appname1 = DataGenUtils.genString(33); URL url = CreateTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, appname); junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse result = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, result.getStatus()); AssertJUnit.assertEquals(data.length, result.getValue().length); AssertJUnit.assertEquals(new String(data), new String(result.getValue())); pConfig.setProperty(JunoProperties.APP_NAME, "JunoTestApp"); //set back to orig junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); try{ pConfig.setProperty(JunoProperties.APP_NAME, appname1); junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient.create(key, data); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Application Name length exceeds MAX LENGTH of 32 bytes")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } finally { pConfig.setProperty(JunoProperties.APP_NAME, "JunoTestApp"); // set back to orig junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } } /***************************************************** * namespace_name lenght > 64 (MF_NAMESPACE_MAX_LEN) *****************************************************/ @Test public void testValidateNamespaceLength() throws JunoException, IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(64); String namespace = DataGenUtils.genString(64); String namespace1 = DataGenUtils.genString(65); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, namespace); junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse result = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, result.getStatus()); AssertJUnit.assertEquals(data.length, result.getValue().length); AssertJUnit.assertEquals(new String(data), new String(result.getValue())); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS1"); //set back to orig junoClient junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); try{ pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, namespace1); junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertEquals("Namespace length exceeds MAX LENGTH of 64 bytes", mex.getMessage()); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } finally { pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "JunoNS1"); //set back to orig junoClient1 junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } } /***************************************************************** * m_max_lifetime > Juno_CONFIG_DEFAULT_MAX_LIFETIME (259200) *****************************************************************/ @Test public void testValidateByChangingMaxLifeTime() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ junoClient2.create(key, data, (long)259201); AssertJUnit.assertTrue ("Exception is NOT seen for invalid lifetime", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=259201, max configured lifetime=259200")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /*********************************************************************** * m_max_payload_size > Juno_CONFIG_DEFAULT_MAX_PAYLOAD_SIZE (204800) ***********************************************************************/ @Test public void testValidateByChangingMaxPayloadSize() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoClient2.create(key, data); AssertJUnit.assertTrue ("Exception is NOT seen for invalid payload", false); }catch(JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than ")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } @Test public void testCreateWithChineseKey() throws JunoException, Exception { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); String key = "Q:������������������������A:������. Q:����� A:����"; String key1 = DataGenUtils.createKey(127); byte[] data = "New data testing".getBytes(); byte[] data1 = "New data111111111111".getBytes(); byte [] keybyte = key.getBytes(); LOGGER.debug(new String (keybyte) + "length is: " + keybyte.length); JunoResponse junoResponse = junoClient.delete(keybyte); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(keybyte, data); JunoResponse junoResponse1 = junoClient.create(key1.getBytes(), data1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); junoResponse = junoClient.get(keybyte); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse1 = junoClient.get(key1.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); LOGGER.debug("Status: " + junoResponse1.getStatus()); LOGGER.debug("Data: " + new String (junoResponse.getValue())); LOGGER.debug("Data1: " + new String (junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testCreateWithChineseKeyBigThan128() throws JunoException, Exception { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); String key = "Q:������������������������A:������. Q:������������������������� A:������������B:�����B:�����B:������������������������� AQ:������������������������� "; byte[] data = "New data testing".getBytes(); try{ byte [] keybyte = key.getBytes(); LOGGER.debug(new String (keybyte) + "length is: " + keybyte.length); JunoResponse junoResponse = junoClient.delete(keybyte); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(keybyte, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(keybyte); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); LOGGER.debug("Data: " + new String (junoResponse.getValue())); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than " + prop.getMaxKeySize())); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } //@Test public void testCreateResponseTimeout() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url3 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); Properties pConfig3 = new Properties(); pConfig3.load(url3.openStream()); pConfig3.setProperty(JunoProperties.APP_NAME, "QATestApp3"); pConfig3.setProperty(JunoProperties.RECORD_NAMESPACE, "NS3"); pConfig3.setProperty(JunoProperties.RESPONSE_TIMEOUT, "1"); JunoClient junoClient3 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig3), SSLUtil.getSSLContext()); byte[] key = DataGenUtils.genBytes(128); byte[] payload = DataGenUtils.genBytes(204700); long ttl = (long)10000; try { JunoResponse junoResponse = junoClient3.create(key, payload); AssertJUnit.assertTrue("should hit response timeout exception", false); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Response Timed out")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } //@Test /** * This test case will run successfully only after shutdown proxy, so either disable * this test case or shutdown proxy and then run this test * @throws JunoException //TODO: it doesn't throw connection timeout, but only response timeout */ //TODO: BUG? exception is not connection timeout but response timeout //@Test public void testCreateConnectionTimeout() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); URL url1 = BatchCreateTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); pConfig1.setProperty(JunoProperties.CONNECTION_TIMEOUT, "1"); JunoClient junoClient3 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); byte[] key = DataGenUtils.genBytes(12); byte[] payload = DataGenUtils.genBytes(20); long ttl = (long)10000; try { JunoResponse junoResponse = junoClient3.create(key, payload); AssertJUnit.assertTrue("should hit connection timeout exception", false); } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Connection Timedout")); LOGGER.info("Exception", mex.getCause().getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Test client call won't be disrupted after server timeout */ @Test public void testCreateServerIdletimeout() throws JunoException, IOException{ LOGGER.info( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoPropertiesProvider prop3 = new JunoPropertiesProvider(pConfig3); try { for(int i=0; i < 10; i++){ //create(key, data) LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse mResponse = junoClient.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); JunoResponse mResponse3 = junoClient3.create(key, data); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals(mResponse3.getTtl(), prop3.getDefaultLifetime().longValue()); AssertJUnit.assertTrue(mResponse3.getTtl() <= prop3.getDefaultLifetime() && mResponse3.getTtl() >= prop3.getDefaultLifetime()-3); mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse.getValue())); AssertJUnit.assertTrue (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); LOGGER.debug("default ttl is " + mResponse.getTtl()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); mResponse3 = junoClient3.get(key); AssertJUnit.assertEquals (OperationStatus.Success, mResponse3.getStatus()); AssertJUnit.assertEquals (new String(data), new String(mResponse3.getValue())); AssertJUnit.assertTrue (mResponse3.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertTrue(mResponse3.getTtl() <= prop3.getDefaultLifetime() && mResponse3.getTtl() >= prop3.getDefaultLifetime()-3); LOGGER.info("0"); LOGGER.info("Completed"); } }catch(Exception e) { AssertJUnit.assertTrue("shouldn't throw exception here", false); } } @Test public void testOrigSizeExceedsNotAfterCompress() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(300000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testExceedsCompressLimit").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is:" + data.length + "compressed length is " + dataLength); JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); } }
89
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchReactSubscriber.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.exception.JunoException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import reactor.core.publisher.Flux; public class BatchReactSubscriber implements Subscriber<JunoResponse> { AtomicInteger num_records = new AtomicInteger(0); AtomicInteger count = new AtomicInteger(0); AtomicBoolean completed = new AtomicBoolean(false); List<JunoResponse> resp = Collections.synchronizedList(new ArrayList<JunoResponse>()); BlockingQueue<JunoException> exception = new LinkedBlockingQueue<>(); private static final Logger LOGGER = LoggerFactory.getLogger(BatchReactSubscriber.class); @BeforeClass public void setup() throws IOException { } BatchReactSubscriber(int num) { num_records.set(num); } public BlockingQueue<JunoException> getAllException() { return exception; } public List<JunoResponse> getAllResps() { return resp; } public Throwable getException() { return exception.peek(); } public List<JunoResponse> getResp() { return resp; } public boolean isCompleted() { return completed.get(); } public int getCount() { return count.get(); } @Override public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); } @Override public void onComplete() { //if (getCount() ) LOGGER.debug("========" + BatchReactSubscriber.class.getSimpleName() + " onCompleted: " + System.currentTimeMillis()); completed.set(true); } @Override public void onError(Throwable e) { LOGGER.debug("========" + BatchReactSubscriber.class.getSimpleName() + " onError: " + e.toString()); try { exception.put((JunoException)e); } catch (InterruptedException e1) { LOGGER.debug("exception put in onError gets exception" + e1); }; } @Override public void onNext(JunoResponse message) { this.count.incrementAndGet(); if (message == null) { LOGGER.debug("========" + BatchReactSubscriber.class.getSimpleName() + " No result"); return; } try { resp.add(message); } catch (JunoException mex) { LOGGER.debug(mex.getMessage()); } LOGGER.debug("========" + BatchReactSubscriber.class.getSimpleName() + " onNext: " + message.getStatus() + System.currentTimeMillis()); } public static List<JunoResponse> getResponse(BatchReactSubscriber subscriber, int timeout) throws JunoException { boolean completed = subscriber.isCompleted(); LOGGER.debug("complete is " + completed + " " + System.currentTimeMillis()); int count = timeout / 10; while (!completed && count > 0) { Throwable t = subscriber.getException(); if (t != null) { LOGGER.debug("=========== Got exception: " + t.getCause()); break; } try { Thread.sleep(10); } catch (InterruptedException e) { LOGGER.debug("thread sleep exception? " + e.getMessage() ); } completed = subscriber.isCompleted(); if (completed) { LOGGER.debug("=========== Completed"); } count --; if (count == 0) { LOGGER.debug("=========== Timeout"); } LOGGER.debug("inside of while loop time is " + System.currentTimeMillis()); } return subscriber.getResp(); } public static List<JunoResponse> subscriberResponse(Flux<JunoResponse> ob, int numKeys) throws JunoException { BatchReactSubscriber batchReactSubscriber = new BatchReactSubscriber(numKeys); LOGGER.debug("time before ob subscribe " + System.currentTimeMillis()); ob.subscribe(batchReactSubscriber); LOGGER.debug("time after ob subscribe " + System.currentTimeMillis()); BatchReactSubscriber.getResponse(batchReactSubscriber, 10000); if (batchReactSubscriber.isCompleted()) { LOGGER.debug("Batch complete"); return batchReactSubscriber.getResp(); } else { throw batchReactSubscriber.exception.poll(); } } public static List<JunoResponse> async_dobatch(JunoReactClient asyncJunoClient, List<JunoRequest> requests) throws JunoException { Flux<JunoResponse> ob = asyncJunoClient.doBatch(requests); return subscriberResponse (ob, requests.size()); } }
90
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/SetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.client.io.RecordContext; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xerial.snappy.Snappy; public class SetTest{ private JunoClient junoClient; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(SetTest.class); URL url = SetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); pConfig.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "true"); URL urlPem = SetTest.class.getResource("/secrets/server.pem"); URL urlCrt = SetTest.class.getResource("/secrets/server.crt"); junoClient = new JunoTestClientImpl(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext(urlCrt.getPath(), urlPem.getPath()),0); URL url1 = SetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); URL url2 = JunoClientFactory.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try{ junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext("server.pem", "server.crt")); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(1000); } /** * Send a set request to the juno 2.0 server with specified key which does not exist. * It should not generate any exception, if there is no problem on server side. * @throws JunoException */ @Test public void testsetWithKey() throws IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] data2 = DataGenUtils.genBytes(20); byte[] data3 = DataGenUtils.genBytes(40); byte[] data4 = DataGenUtils.genBytes(800); long lifetime = 22000; JunoResponse mResponse = junoClient.set(key, data); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); LOGGER.debug("set ttl is " + mResponse.getTtl()); AssertJUnit.assertTrue(mResponse.getTtl() == prop.getDefaultLifetime()); mResponse = junoClient.set(key, data1); //ttl won't be updated AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertTrue(mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() >= prop.getDefaultLifetime()-3); JunoResponse junoResponse = junoClient.set(key,data2, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(3 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); junoResponse = junoClient.set(key, data3, 10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(4 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() >=9 ); junoResponse = junoClient.set(key, data4, 0); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(5 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-3); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(5 == junoResponse.getVersion()); AssertJUnit.assertEquals(data4.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data4), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-3); key = DataGenUtils.genBytes(64); data = DataGenUtils.genBytes(10); JunoResponse junoResponse1 = junoClient1.set(key, data, 0); //it gets default time from server side which is 3600 AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request twice with same key to juno 2.0 server * It should be successfull. * @throws JunoException * @throws IOException */ @Test public void testsetWithSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); long lifetime = 100; JunoResponse junoResponse = junoClient.set(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoClient1.set(key, data2, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(key == junoResponse.getKey()); mResponse = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); mResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request twice with same key to juno 2.0 server * It should be successfull. * @throws JunoException * @throws IOException */ @Test public void testsetWithoutTTL() throws JunoException, IOException { LOGGER.info("\n***TEST CASE: " + new Object() {}.getClass().getEnclosingMethod().getName()); LOGGER.info(new Object() {}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoResponse junoResponse = junoClient.set(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } junoResponse = junoClient.get(key); // It will show that 10 sec has elapsed from original TTL AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(junoResponse.getTtl() >= (prop.getDefaultLifetime()-14) && (junoResponse.getTtl() <= prop.getDefaultLifetime()-10)); //System.out.println("TTL now is:"+junoResponse.getTtl()); junoResponse = junoClient.set(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); // It will show that 1800 sec as TTL. AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() >= (prop.getDefaultLifetime() - 4) && junoResponse.getTtl() <= prop.getDefaultLifetime()); //System.out.println("TTL now is:"+junoResponse.getTtl()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with empty key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testSetWithEmptyKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse mResponse = null; try{ mResponse = junoClient.set(key, data); AssertJUnit.assertTrue(false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a insert request with Null key and should generate IllegalArgumentException. * @throws JunoException * @throws IOException */ @Test public void testsetWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); try{ long lifetime = 100; junoClient.set(key, data, lifetime); AssertJUnit.assertTrue ("Exception is not seen for null key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with 128bytes key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = new String(DataGenUtils.createKey(50) + "SETWith128BytesKey").getBytes(); byte[] data = DataGenUtils.genBytes(10); long lifetime = 100; JunoResponse junoResponse = null; try { junoResponse = junoClient.set(key, data, lifetime); } catch (JunoException ex) { LOGGER.debug("Exception Occured: " + ex.getMessage()); AssertJUnit.assertTrue(false); } AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Call insert() to create a record with same key, verify DupKey error"); try { JunoResponse mResponse = junoClient2.create(key, data); AssertJUnit.assertEquals (OperationStatus.UniqueKeyViolation,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for duplicate key", false); LOGGER.info("0"); } LOGGER.info("Completed"); } /** * Send a set request with 129bytes key and should generate IllegalArgumentException * with "Invalid key length. current length=257, max length=256" * @throws JunoException * @throws IOException */ @Test public void testsetWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.set(key, data, 100L); AssertJUnit.assertTrue ("Exception is NOT seen for Key = 129 bytes length", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request special characters key and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "@@#$%^&*()_+?>,<|}{[]~abc780=.__?|".getBytes(); byte[] key1 = "Q:������������A:����. Q:������������������ A:��� Q:".getBytes(); byte[] data = "Q:你好嗎?A:我很好".getBytes(); byte[] data1 = "Q:������������A:���������. Q:������������������ A:������������������ Q:������������������ A:������������������ Ok ���������".getBytes(); LOGGER.debug("key length is " + key.length + " key1 length is " + key1.length); try { junoClient.delete(key); junoClient.delete(key1); Thread.sleep(5000); } catch (Exception e) { LOGGER.debug(e.getMessage()); } JunoResponse junoResponse = junoClient.set(key, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.set(key1, data1); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key1, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); JunoResponse junoResponse2 = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertEquals(key, junoResponse2.key()); AssertJUnit.assertTrue(1 == junoResponse2.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse2.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with normal lifetime and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWith10SecLifetime() throws JunoException, IOException, InterruptedException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = new String(DataGenUtils.createKey(40) + "SETWith10SecLifetime").getBytes(); byte[] data = DataGenUtils.genBytes(10); long lifetime = 15; JunoResponse junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); Thread.sleep (7000); junoResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Sleep more for the key to expire"); Thread.sleep (10000); try { JunoResponse mResponse = junoClient2.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a set request with zero lifetime, default lifetime should be used * Call insert() to insert same key, should get Duplicate error * @throws JunoException //TODO: ask why get default 3600 not 1800? * @throws IOException */ @Test public void testsetWithZeroLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); byte[] key = new String(DataGenUtils.createKey(30) + "set").getBytes(); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse mResponse = junoClient.set(key, data, 15); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getTtl() == 15); mResponse = junoClient.set(key, data); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); mResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); mResponse = junoClient.set(key, data, 0L); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue (mResponse.getTtl() <= prop.getDefaultLifetime() && mResponse.getTtl() > prop.getDefaultLifetime()-3); AssertJUnit.assertEquals(3,mResponse.getVersion()); mResponse = junoClient2.set(key, data2); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(4,mResponse.getVersion()); mResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertEquals(4,mResponse.getVersion()); AssertJUnit.assertEquals(data2.length,mResponse.getValue().length); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); JunoResponse mResponse1 = junoClient1.set(key, data, 0); AssertJUnit.assertEquals(OperationStatus.Success, mResponse1.getStatus()); mResponse1 = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, mResponse1.getStatus()); //System.out.println("lifetime for junoClient1 is " + mResponse1.getTtl()); LOGGER.debug("lifetime for junoClient1 is " + mResponse1.getTtl() + ", default is " + prop.getDefaultLifetime()); AssertJUnit.assertEquals(1,mResponse1.getVersion()); AssertJUnit.assertEquals(data.length, mResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(mResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with Negative lifetime and should generate an * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithNegativeLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.set(key, data, (long)-1); AssertJUnit.assertTrue ("Exception is NOT seen for negative lifetime", false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative.")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with max lifetime 3 days and should not generate exceptions * @throws JunoException * @throws IOException */ @Test public void testsetWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = new String(DataGenUtils.createKey(50) + "SETWith3DaysLifetime").getBytes(); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient2.get(key, (long)10); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with more than max lifetime 3 days and should * generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ junoClient.set(key, data, lifetime); AssertJUnit.assertTrue ("Exception is not seen for TTL > 3 days", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime.")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with null payload and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithNullPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse res = junoClient.set(key, null, 50L); AssertJUnit.assertEquals (OperationStatus.Success,res.getStatus()); AssertJUnit.assertEquals(key, res.key()); AssertJUnit.assertTrue(1 == res.getVersion()); AssertJUnit.assertEquals(0 , res.getValue().length); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertFalse(true); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a set request with zero size payload and should be successfull * @throws JunoException * @throws IOException //TODO: ask set can not be zero payload but create allows zero payload? */ @Test public void testsetWithZeroPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(0); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.set(key, data, 20L); LOGGER.info("0"); }catch(Exception mex){ AssertJUnit.assertTrue("should be able to set empty payload, why come here?", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a set request with 100KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testsetWith100KBPayload() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(102400); byte[] key = new String(DataGenUtils.createKey(50) + "SETWith100KBPayload").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); LOGGER.debug("property config in 100K is :" + prop.getRecordNamespace() + " " + prop.getAppName()); prop = new JunoPropertiesProvider(pConfig); LOGGER.debug("property config1 in 100K is :" + prop.getRecordNamespace() + " " + prop.getAppName()); JunoResponse junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("Sleep 3 seconds before geting daata"); JunoResponse mResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with 200KB payload and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testsetWith200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204800); byte[] key = new String(DataGenUtils.createKey(64) + "SETWith200KBPayload").getBytes(); JunoResponse junoResponse = junoClient.set(key, data, 15L); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a insert request with more than 200KB payload and should generate * IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testsetWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoClient.set(key, data, 10L); AssertJUnit.assertTrue ("Exception is not seen for payload > 200KB", false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /************************************************* * Send a insert request with same key for two different name spaces and should not * generate exceptions * *************************************************/ @Test public void testsetWithSameKeyInDifferentNameSpaces() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(100); JunoResponse junoResponse = junoClient.set(key, data, 100L); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient1.set(key, data1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertEquals(junoResponse.getVersion(), junoResponse1.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two records using set() with same key and name space. * The 2nd set call should succeed *************************************************/ @Test public void testsetWithSameKeysInSameNameSpace() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); byte[] key = new String(DataGenUtils.createKey(6) + "SETWithSameKeysInSameNameSpace").getBytes(); JunoResponse junoResponse = junoClient.set(key, data, 10L); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create with same key, different data JunoResponse mResponse = junoClient2.set(key, data2, 100L); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(2 == mResponse.getVersion()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * insert two clients using insert() then set() with same ns but diff app name * The 2nd set() should succeed *************************************************/ @Test public void testsetWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.createKey(10).getBytes(); LOGGER.debug("key is " + new String(key)); JunoResponse junoResponse = junoClient.create(key, data, 100L); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //Create same key using set() should be OK junoClient2.set(key, data2, 10L); JunoResponse mResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * Do a set(), update, conditionalUpdate() * delete() *************************************************/ @Test public void testSetWithOtherOps() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); byte[] data3 = DataGenUtils.genBytes(15); byte[] key = new String(DataGenUtils.createKey(60) + "SETWithOtherOps").getBytes(); JunoResponse junoResponse = junoClient.set(key, data, 100L); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoClient2.update(key, data2, 0L); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data2), new String(mResponse.getValue())); AssertJUnit.assertTrue(2 == mResponse.getVersion()); LOGGER.debug("\nUpdate the key using conditional update"); long lifetime = 100L; JunoResponse junoResponse1 = junoClient.compareAndSet(mResponse.getRecordContext(), data3, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(3 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(new String(data3), new String(junoResponse1.getValue())); junoResponse1 = junoClient2.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); try { JunoResponse result1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey, result1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } @Test public void testCompareAndTestWithWrongVersion()throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info(new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data1 = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(20); byte[] key = new String(DataGenUtils.createKey(60) + "SETWithOtherOps").getBytes(); JunoResponse junoResponse = junoClient.set(key, data1, 100L); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse.getValue())); RecordContext reqCtx = new RecordContext(key,0,0,120); try{ junoClient.compareAndSet(reqCtx, data2, 240); AssertJUnit.assertTrue ("Exception should happen for version = 0", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document version cannot be less than 1")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /*********************************************************************** * m_max_payload_size > JUNO_CONFIG_DEFAULT_MAX_PAYLOAD_SIZE (204800) ***********************************************************************/ @Test public void testValidateByChangingMaxPayloadSize() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); pConfig.setProperty("MAX_PAYLOAD_SIZE", "204809"); JunoClient junoClient2 = null; try { junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); } catch (Exception e) { throw new RuntimeException(e); } byte[] data = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ junoClient2.set(key, data, 10L); AssertJUnit.assertTrue ("Exception is NOT seen for invalid payload", false); }catch(Exception mex){ LOGGER.debug("\nException occur: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } @Test public void testsetWithChineseKey() throws JunoException, Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "Q:你好嗎?A:我很好. Q:你�?去哪裡? A:我�?去迪斯尼 Q:�?�什麼想看? A:米奇米尼�?鼠ok".getBytes(); byte[] key1 = DataGenUtils.createKey(127).getBytes(); byte[] data = "New data testing".getBytes(); byte[] data1 = "New data111111111111".getBytes(); LOGGER.debug("Key length: " + key.length); LOGGER.debug("Key1 length: " + key1.length); LOGGER.debug("\nKey length without UTF-8: " + key.length); LOGGER.debug("Key1 length without UTF-8: " + key1.length); byte [] tmp = key; LOGGER.debug(new String (tmp) + " " + tmp.length); try { junoClient.delete(key); Thread.sleep(5000); } catch (Exception e) { LOGGER.debug("Exception Occured: " + e.getMessage()); } long lifetime = 100; JunoResponse junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient.set(key1, data1, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse1 = junoClient.get(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); LOGGER.debug("Status: " + junoResponse1.getStatus()); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testSetWithCompression() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(100000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testSetWithCompression").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is " + data.length + "compressed length is " + dataLength); JunoResponse junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a set request with 150K byte payload which will trigger compression, data can be read * by mayfly java client testGetFromJunoInsert func or junocli, junocli command is: * ./junocli -s host:port -ssl -c config.toml get -ns "NS1" _testSetWithCompressionCrossRead * exception * @throws Exception */ @Test public void testSetWithCompressionCrossMayfly() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(150000).getBytes(); byte[] key = new String("_testSetWithCompressionCrossRead").getBytes(); long lifetime = 2500; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is " + data.length + ", compressed length is " + dataLength); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); Thread.sleep (2000); junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertEquals(new String(data), new String(mResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testExceedsCompressLimit() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(800000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testExceedsCompressLimit").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; LOGGER.info("data original length is:" + data.length + "compressed length is " + dataLength); try { junoClient.set(key, data, lifetime); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } @Test public void testUpdateExceedsMax() throws Exception { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.createCompressablePayload(300000).getBytes(); byte[] updateD = DataGenUtils.createCompressablePayload(800000).getBytes(); byte[] key = new String(DataGenUtils.createKey(50) + "testExceedsCompressLimit").getBytes(); long lifetime = 25; JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig2); prop = new JunoPropertiesProvider(pConfig); int dataLength = Snappy.compress(data).length; int updateDLength = Snappy.compress(updateD).length; LOGGER.info("data original length is:" + data.length + "compressed length is " + dataLength); LOGGER.info("updatedata original length is:" + data.length + "compressed length is " + updateDLength); JunoResponse junoResponse = junoClient.set(key, data, lifetime); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try { JunoResponse junoResponse1 = junoClient.update(key, updateD); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } // @Test // public void testSetExceedsVersion() throws Exception { // LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); // update(key, data1, lifetime1) // LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); // byte[] data = DataGenUtils.genBytes(2000); // byte[] key = DataGenUtils.createKey(50).getBytes(); // long lifetime = 25; // // try { // for (int i=0; i<40000; i++) { // JunoResponse junoResponse = junoClient.set(key, data, lifetime); // AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); // // JunoResponse junoResponse1 = junoClient.get(key); // AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); // LOGGER.info("get version is " + junoResponse1.getVersion()); // } // }catch(Exception mex){ // LOGGER.debug(mex.getMessage()); // LOGGER.info("Exception", mex.getMessage()); // LOGGER.info("2"); // LOGGER.info("Completed"); // } // } }
91
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ReactorDestroyTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ReactorDestroyTest{ private JunoReactClient junoReactClient; private JunoReactClient junoReactClient1; private JunoReactClient junoReactClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; int syncFlag; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException { URL url = DestroyTest.class.getResource("/com/paypal/juno/Juno.properties"); LOGGER = LoggerFactory.getLogger(DestroyTest.class); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); URL url1 = DestroyTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); URL url2 = DestroyTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try{ junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient1 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoReactClient2 = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(3000); } /** * Send a delete request with key to juno 2.0 server and should not generate * an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWithKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals (OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertTrue ( deleteResponse.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.update(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.set(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(4, junoResponse.getVersion()); deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); try { JunoResponse result1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, result1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a delete request for existing key and insert a record with same key * after delete and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyAndCreateWithSameKey() throws JunoException, IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "juno_test1".getBytes(); byte[] data = "testing data".getBytes(); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); AssertJUnit.assertTrue ( deleteResponse.getStatus().getCode() == OperationStatus.Success.getCode()); try { JunoResponse result1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, result1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); } junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() > prop.getDefaultLifetime()-3); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send delete request with empty key and should generate and exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWithEmptyKey() { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); try{ junoReactClient.delete(key).block(); AssertJUnit.assertTrue ("***Error: null key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a delete request with null key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); try{ junoReactClient.delete(null).block(); AssertJUnit.assertTrue ("***Error: null key not throwing exception", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a delete request after five seconds if creation record lifetime 10 seconds * and should not generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ @Test public void testDestroyAfterFiveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoReactClient.create(key, data, (long)lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(5000); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); try { JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a delete request after twelve seconds if creation record lifetime is ten seconds * and should generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ //This test can be used to test default juno.idleConnectionsTimeoutMillis = 9000 ( 9 seconds) @Test public void testDestroyAfterTwelveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] key2 = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoReactClient.create(key, data, (long)lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(6000); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); junoResponse = junoReactClient.create(key2, data, (long)lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data, (long)lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a request with 128 bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoReactClient.create(key, data, (long)lifetime).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); try { JunoResponse junoResponse1 = junoReactClient.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a delete request with 129 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); try{ junoReactClient.delete(key).block(); AssertJUnit.assertTrue ("Exception should happen for long key > 128bytes ", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a delete request with no key exists on server and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyNoKeyExists() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); String key1 = new String("haha, nohaoma"); String key2 = new String("Q:������������������������������������A:���"); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); JunoResponse deleteResponse1 = junoReactClient.delete(key1.getBytes()).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse1.getStatus()); //System.out.println("Key size:"+key2.getBytes().length); JunoResponse deleteResponse2 = junoReactClient.delete(key2.getBytes()).block(); AssertJUnit.assertEquals (OperationStatus.Success, deleteResponse2.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.getKey()); AssertJUnit.assertEquals(key1.getBytes(), deleteResponse1.getKey()); AssertJUnit.assertEquals(key2.getBytes(), deleteResponse2.getKey()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); AssertJUnit.assertEquals(new String(deleteResponse1.getValue()), ""); AssertJUnit.assertEquals(new String(deleteResponse2.getValue()), ""); LOGGER.info("0"); LOGGER.info("Completed"); } /*********************************************** * Create two records under different namespaces * but with same key. Destroy one of the records. * Verify that the other record still exists. ************************************************/ @Test public void testDestroyWithDiffNamespacesWithSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "juno_test3".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient1.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient1.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); AssertJUnit.assertTrue ( deleteResponse.getStatus().getCode() == OperationStatus.Success.getCode()); LOGGER.debug("Verify the other namspace still has the key"); junoResponse = junoReactClient1.get(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /***************************************** * Create one records, delete the record * and get the same key with same app name *****************************************/ @Test public void testDestroyWithDiffAppnameWithSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "juno_test_sameappname".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient2.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoReactClient.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); try { Thread.sleep(2000); JunoResponse junoResponse2 = junoReactClient2.create(key, data).block(); AssertJUnit.assertEquals(OperationStatus.UniqueKeyViolation,junoResponse2.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key :"+mex.getMessage(), false); } catch (Exception e) { LOGGER.debug(e.getMessage()); } JunoResponse deleteResponse = junoReactClient.delete(key).block(); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); LOGGER.debug("Verify the other appname does not have key"); try { junoResponse = junoReactClient2.get(key).block(); AssertJUnit.assertEquals(OperationStatus.NoKey, junoResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } }
92
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/DestroyTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class DestroyTest{ private JunoClient junoClient; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { URL url = DestroyTest.class.getResource("/com/paypal/juno/Juno.properties"); LOGGER = LoggerFactory.getLogger(DestroyTest.class); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoClient = new JunoTestClientImpl(new JunoPropertiesProvider(pConfig),null,0); URL url1 = DestroyTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); URL url2 = DestroyTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); Thread.sleep(3000); } /** * Send a delete request with key to juno 2.0 server and should not generate * an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWithKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals (OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertTrue ( deleteResponse.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.update(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.set(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.compareAndSet(junoResponse.getRecordContext(), data, (long)5); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); try { JunoResponse result1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey, result1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a delete request for existing key and insert a record with same key * after delete and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyAndCreateWithSameKey() throws JunoException, IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "juno_test1".getBytes(); byte[] data = "testing data".getBytes(); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); AssertJUnit.assertTrue ( deleteResponse.getStatus().getCode() == OperationStatus.Success.getCode()); try { JunoResponse result1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey, result1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); } junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() > prop.getDefaultLifetime()-3); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send delete request with empty key and should generate and exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWithEmptyKey() { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); try{ junoClient.delete(key); AssertJUnit.assertTrue ("***Error: null key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a delete request with null key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); try{ junoClient.delete(null); AssertJUnit.assertTrue ("***Error: null key not throwing exception", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a delete request after five seconds if creation record lifetime 10 seconds * and should not generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ @Test public void testDestroyAfterFiveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(5000); JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals (OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); try { JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a delete request after twelve seconds if creation record lifetime is ten seconds * and should generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ //This test can be used to test default juno.idleConnectionsTimeoutMillis = 9000 ( 9 seconds) @Test public void testDestroyAfterTwelveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] key2 = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(7000); JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); junoResponse = junoClient.create(key2, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a request with 128 bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse deleteResponse= junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); try { JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a delete request with 129 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); try{ junoClient.delete(key); AssertJUnit.assertTrue ("Exception should happen for long key > 128bytes ", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a delete request with no key exists on server and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testDestroyNoKeyExists() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); String key1 = new String("haha, nohaoma"); String key2 = new String("Q:������������������������������������A:���"); JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); JunoResponse deleteResponse1 = junoClient.delete(key1.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); JunoResponse deleteResponse2 = junoClient.delete(key2.getBytes()); AssertJUnit.assertEquals (OperationStatus.Success, deleteResponse2.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.getKey()); AssertJUnit.assertEquals(key1.getBytes(), deleteResponse1.getKey()); AssertJUnit.assertEquals(key2.getBytes(), deleteResponse2.getKey()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); AssertJUnit.assertEquals(new String(deleteResponse1.getValue()), ""); AssertJUnit.assertEquals(new String(deleteResponse2.getValue()), ""); LOGGER.info("0"); LOGGER.info("Completed"); } /*********************************************** * Create two records under different namespaces * but with same key. Destroy one of the records. * Verify that the other record still exists. ************************************************/ @Test public void testDestroyWithDiffNamespacesWithSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "juno_test3".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient1.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient1.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); LOGGER.debug("data: " + deleteResponse.getValue()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); LOGGER.debug("Verify the other namspace still has the key"); junoResponse = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /***************************************** * Create one records, delete the record * and get the same key with same app name *****************************************/ @Test public void testDestroyWithDiffAppnameWithSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "juno_test_sameappname".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient2.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); try { Thread.sleep(2000); JunoResponse junoResponse2 = junoClient2.create(key, data); AssertJUnit.assertEquals(OperationStatus.UniqueKeyViolation,junoResponse2.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key :"+mex.getMessage(), false); } catch (Exception e) { LOGGER.debug(e.getMessage()); } JunoResponse deleteResponse = junoClient.delete(key); AssertJUnit.assertEquals (OperationStatus.Success, deleteResponse.getStatus()); AssertJUnit.assertEquals(key, deleteResponse.key()); AssertJUnit.assertEquals(new String(deleteResponse.getValue()), ""); LOGGER.debug("Verify the other appname does not have key"); try { junoResponse = junoClient2.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey, junoResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } }
93
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/GetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger;import com.paypal.juno.client.JunoClient; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class GetTest{ private JunoClient junoClient; private JunoClient junoClient1; private JunoClient junoClient2; private JunoClient cryptClient2; private Properties pConfig; private Properties pConfig2; private Logger LOGGER; int syncFlag; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(GetTest.class); URL url = GetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); LOGGER.debug("Read syncFlag test to findout if we need to run test in sync/async mode"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); syncFlag = Integer.parseInt(sync_flag.trim()); //junoClient = new JunoTestClientImpl(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); URL url1 = GetTest.class.getResource("/com/paypal/juno/Juno.properties"); junoClient1 = JunoClientFactory.newJunoClient(url1); URL url2 = GetTest.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try{ junoClient = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(1000); } /** * Send a get request with key to the Juno 2.0 server and should not generate * exception * @throws JunoException * @throws IOException */ @Test public void testGetWithKey() throws IOException{ JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 220000; JunoResponse mResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); JunoResponse junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); junoResponse = junoClient.get(key, 0); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); junoResponse = junoClient.get(key, lifetime); LOGGER.debug("lifetime get is " + junoResponse.getTtl()); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.get(key, 10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime == junoResponse.getTtl()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request with empty key and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testGetWithEmptyKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); try{ JunoResponse junoResponse = junoClient.get(key); AssertJUnit.assertTrue ("Exception is not seen for empty key", false); AssertJUnit.assertEquals (OperationStatus.NoKey,junoResponse.getStatus()); }catch(Exception mex){ LOGGER.debug("Exception: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with null key and should generate IllegalArgumentException * @throws JunoException * @throws IOException */ @Test public void testGetWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); try{ JunoResponse junoResponse = junoClient.get(null); AssertJUnit.assertTrue ("Exception is not seen for null key", false); }catch(Exception mex){ LOGGER.debug("Exception: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with no key exists on the server and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testGetNoKeyExists() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); try { JunoResponse mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request after five seconds of creation of a record and should not * generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ @Test public void testGetAfterFiveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; junoClient.create(key, data, lifetime); Thread.sleep(5000); JunoResponse junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 10-5 && junoResponse.getTtl() > 10-3-5); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request after twelve seconds after creation of a record and should * generate an exception * @throws JunoException * @throws IOException * @throws InterruptedException */ @Test public void testGetAfterTwelveSeconds() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data, 12); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); LOGGER.debug("default ttl is " + junoResponse.getTtl()); Thread.sleep(5000); LOGGER.debug("Read should not extend lilfetime"); junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 12-5 && junoResponse.getTtl() > 12-3-5); AssertJUnit.assertTrue (junoResponse.getStatus().getCode() == OperationStatus.Success.getCode()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(9000); try { JunoResponse mResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey, mResponse.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } LOGGER.info("Completed"); } /** * Send a get request with 128bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request with 130 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(129); try{ JunoResponse junoResponse = junoClient.get(key); AssertJUnit.assertTrue ("Exception is not seen for key > 128 bytes length", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with lifetime and should not generate exception * @throws JunoException * @throws IOException */ @Test public void testGetWithLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key, (long)5); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 5 && junoResponse.getTtl() > 5-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(3000); LOGGER.debug("Update key with new timeline add" ); JunoResponse junoResponse1; try { junoResponse1 = junoClient.get(key, (long)5); } catch (JunoException mex) { AssertJUnit.assertTrue("\"get time out Exception?", false); } Thread.sleep(3000); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); LOGGER.debug("Sleep for key to expire"); Thread.sleep(3000); try { JunoResponse junoResponse2 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey,junoResponse2.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request with zero life time and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithZeroLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 5; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.get(key, (long)0); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(junoResponse1.getTtl() <= 5 && junoResponse1.getTtl() > 5-3); Thread.sleep(6000); try { JunoResponse junoResponse2 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey,junoResponse2.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request with zero life time and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithoutLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 8; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() > lifetime-3 && junoResponse.getTtl() <= lifetime); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() > lifetime-3 && junoResponse.getTtl() <= lifetime); Thread.sleep(10000); try { JunoResponse junoResponse2 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.NoKey,junoResponse2.getStatus()); LOGGER.info("0"); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a get request with max lifetime 3days and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithMaxLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse mResponse = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); mResponse = junoClient.create(key, data, 10); AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(10 == mResponse.getTtl()); JunoResponse junoResponse = junoClient.get(key, 0); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(10-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= 10); junoResponse = junoClient.get(key, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-2 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.get(key, 10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a get request with more than max lifetime and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithMoreThanMaxLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; long lifetime1 = 777000; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); try{ junoResponse = junoClient.get(key, lifetime1); AssertJUnit.assertTrue ("Exception is not seen for big lifetime = 777000", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=777000, max configured lifetime=259200")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a get request with negative lifetime and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testGetWithNegativeLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); long lifetime = 10; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); try{ JunoResponse junoResponse1 = junoClient.get(key, (long)-1); AssertJUnit.assertTrue ("Exception is not seen for negative lifetime", false); }catch(Exception mex){ LOGGER.debug(mex.getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /*********************************************** * insert 2 client objects with different * application names but same namespace. insert * record with key k1 using one client object. * Do a get for record with k1 using the second * client object. * ************************************************/ @Test public void testGetWithSameNameSpaceDiffAPP_NAME() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient2.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); LOGGER.debug("BUGGY : response ttl is " + junoResponse.getTtl() + " respnose1 ttl is " + junoResponse1.getTtl()); AssertJUnit.assertTrue(junoResponse.getTtl() >= junoResponse1.getTtl()); AssertJUnit.assertEquals(junoResponse.getVersion(), junoResponse1.getVersion()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /*********************************************** * insert 2 client objects with namespaces NS1 & * NS2. insert records with different keys and * payloads under both clients. Perform 'Get' * for key insertd under NS1 using NS2's client * object and vice-versa. * Result: Should get "key not found" * ************************************************/ @Test public void testGetWithDiffNameSpaceAndDiffKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(64); byte[] key1 = DataGenUtils.genBytes(64); long lifetime = 3600; JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient1.create(key1, data1, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); //client1 get key from a different name space NS junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertTrue (junoResponse.getTtl() <= lifetime && junoResponse.getTtl() > lifetime-3); try { junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey, junoResponse1.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } //client get key from a different name space try { junoResponse = junoClient.get(key1); AssertJUnit.assertEquals (OperationStatus.NoKey, junoResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } junoResponse1 = junoClient1.get(key1); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue (junoResponse1.getTtl() <= lifetime && junoResponse1.getTtl() > lifetime-3); LOGGER.info("0"); LOGGER.info("Completed"); } /*********************************************** * insert 2 client objects with namespaces NS1 & * NS2. insert records with same key but different * payloads under both clients. Perform a 'Get' * for the key under NS1 and NS2. * ************************************************/ @Test public void testGetWithDiffNameSpaceDiffPayloadSameKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(10); junoClient.delete(key); try { Thread.sleep(2000); } catch (Exception ex) { LOGGER.debug(ex.getMessage()); } junoClient.create(key, data); try { JunoResponse res = junoClient1.create(key, data1); AssertJUnit.assertEquals(OperationStatus.Success,res.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for duplicate key", false); } JunoResponse junoResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertTrue(junoResponse.getVersion() == junoResponse1.getVersion()); AssertJUnit.assertTrue(junoResponse.getValue().length < junoResponse1.getValue().length); AssertJUnit.assertTrue(new String(junoResponse.getValue()) != new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } @Test public void testinsertChineseKeyForCpp() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); //byte[] key = "123456"; byte[] key = "Q:������������A:���������. Q:�������������".getBytes(); byte[] key_utf8 = new String("UTF-8,UTF-8").getBytes(); byte[] data = "Q:������������A:���������".getBytes("UTF-8"); byte[] data2 = "Q:������������A:���������. Q:���������������123".getBytes("UTF-8"); JunoResponse junoResponse = junoClient.delete(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.delete(key_utf8); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); junoResponse = junoClient.create(key, data, 100); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(1, junoResponse.getVersion()); junoResponse = junoClient.get(key, 0); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(1, junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 100 && junoResponse.getTtl() > 100-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.get(key, 115); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(1, junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= 115 && junoResponse.getTtl() > 115-3); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.debug("\nUpdate key: "); byte[] data1 = "Q:������������A:���������. Q:���������������".getBytes("UTF8"); long lifetime1 = 120L; JunoResponse junoResponse1 = junoClient.update(key, data1, lifetime1); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); junoResponse1 = junoClient.get(key); LOGGER.debug("New Data1: " + new String(junoResponse1.getValue())); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); JunoResponse junoResponse2 = junoClient.create(key_utf8, data); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertEquals(1, junoResponse2.getVersion()); AssertJUnit.assertTrue(junoResponse2.getTtl() <= prop.getDefaultLifetime() && junoResponse2.getTtl() > prop.getDefaultLifetime()-3); junoResponse2 = junoClient2.get(key_utf8); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse2.getStatus()); AssertJUnit.assertEquals(data.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse2.getValue())); //conditional update old response will fail, ttl etc. shouldn't be updated LOGGER.debug("\nConditional Update: "); try { JunoResponse junoResponse3 = junoClient.compareAndSet(junoResponse.getRecordContext(), data2, (long)600L); AssertJUnit.assertEquals(OperationStatus.ConditionViolation, junoResponse3.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for Condition Violation", false); } JunoResponse gResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,gResponse.getStatus()); AssertJUnit.assertEquals(2, gResponse.getVersion()); LOGGER.debug("junoResponse3 lifetime is " + gResponse.getTtl()); AssertJUnit.assertTrue(gResponse.getTtl() <= lifetime1 && gResponse.getTtl() > lifetime1 - 5); AssertJUnit.assertEquals(data1.length, gResponse.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(gResponse.getValue())); //conditional update successful gResponse = junoClient.compareAndSet(junoResponse1.getRecordContext(), data2, (long)600L); AssertJUnit.assertEquals (OperationStatus.Success,gResponse.getStatus()); gResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,gResponse.getStatus()); AssertJUnit.assertEquals(key, gResponse.key()); AssertJUnit.assertEquals(3, gResponse.getVersion()); AssertJUnit.assertTrue(gResponse.getTtl() <= 600 && gResponse.getTtl() > 600-3); AssertJUnit.assertEquals(new String(data2), new String(gResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } //@Test public void testGetEncrypt() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "Thisisanewkey".getBytes(); LOGGER.debug("Crypt client1 inserts key"); //cryptClient1.delete (key); //cryptClient1.insert(key, data, 7200L); LOGGER.debug("Crypt client2 gets key"); JunoResponse junoResponse = cryptClient2.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); LOGGER.debug("Data from Infra: " + new String(junoResponse.getValue())); // LOGGER.debug("Crypt client1 updates key"); // byte[] data1 = "Hello testing data".getBytes(); // JunoResponse junoResponse2 = cryptClient1.update (key, data1); // assertEquals (junoResponse2.getStatus(), OperationStatus.Success); // // junoResponse = cryptClient2.get(key); // assertEquals (new String(data1), new String(junoResponse.getValue())); // LOGGER.debug("Data: " + new String(junoResponse.getValue())); // // LOGGER.debug("Crypt client2 do a Conditional Update on key"); // // JunoResponse junoResponse3 = cryptClient1.cas (junoResponse, data2, (long)15); // assertEquals (junoResponse3.getStatus(), OperationStatus.Success); // assertEquals (new String(data2), new String(junoResponse3.getValue())); // LOGGER.debug("Data: " + new String(junoResponse3.getValue())); // LOGGER.debug("Crypt client1 delete key"); // cryptClient1.delete(key); // junoResponse = cryptClient2.get(key); // assertEquals (junoResponse.getStatus(), OperationStatus.NoKey); } @Test public void testGetWithKey3() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "EbZaSXjUi3IHef52XSCe".getBytes(); byte[] data2 = "This is a new test data testing".getBytes(); JunoResponse res = junoClient.delete(key); AssertJUnit.assertEquals(OperationStatus.Success, res.getStatus()); res = junoClient.create(key,data2,160L); AssertJUnit.assertEquals(OperationStatus.Success, res.getStatus()); AssertJUnit.assertTrue(res.getTtl() == 160); JunoResponse junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); LOGGER.info("0"); LOGGER.info("Completed"); } public String generateRandomString (int len) { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-"; int max = chars.length(); LOGGER.debug(String.valueOf(max)); StringBuffer strBuf = new StringBuffer(); for (int i = 0 ; i < len; i++) { double index = Math.random() * max; //LOGGER.debug(Math.random()); strBuf.append(chars.charAt((int) index)); } LOGGER.debug(strBuf.toString()); return strBuf.toString(); } // @Test // public void testinsertWithEncryptData() throws JunoException, IOException{ // LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); // //byte[] key = DataGenUtils.genBytes(64); // //byte[] data = DataGenUtils.genBytes(10); // byte[] key = "ccctest"; // byte[] data = "This is a special day of year 2015".getBytes(); // //byte[] data = DataGenUtils.genBytes(10); // LOGGER.debug("Crypt client1 inserts key"); // } /** * Send a get request with key to the Juno 2.0 server and should not generate * exception * @throws JunoException * @throws IOException */ // @Test // public void testGetWithEncryptData() throws JunoException, IOException{ // LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); // byte[] key = DataGenUtils.genBytes(64); // byte[] data = DataGenUtils.genBytes(10); // //byte[] key = "abctest"; // //byte[] data = "This is second day of year 2015".getBytes(); // //byte[] data = DataGenUtils.genBytes(10); // LOGGER.debug("Crypt client1 inserts key"); // cryptClient1.insert(key, data); // // LOGGER.debug("Crypt client2 gets key"); // JunoResponse junoResponse = cryptClient2.get(key); // AssertJUnit.assertEquals(key, junoResponse.key()); // AssertJUnit.assertEquals("NS1", junoResponse.getNamespace()); // //org.junit.Assert.assertTrue(1 == junoResponse.getVersion()); // // AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); // AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); // LOGGER.debug("Data from Infra: " + new String(junoResponse.getValue())); // // LOGGER.debug("Crypt client1 updates key"); // byte[] data1 = "Hello testing data".getBytes(); // JunoResponse junoResponse2 = cryptClient1.update (key, data1); // AssertJUnit.assertEquals (junoResponse2.getStatus(), OperationStatus.Success); // // junoResponse = cryptClient2.get(key); // AssertJUnit.assertEquals (new String(data1), new String(junoResponse.getValue())); // LOGGER.debug("Data: " + new String(junoResponse.getValue())); // // LOGGER.debug("Crypt client2 do a Conditional Update on key"); // byte[] data2 = "Hello, updating testing data".getBytes(); // JunoResponse junoResponse3 = cryptClient1.cas (junoResponse, data2, (long)15); // AssertJUnit.assertEquals (junoResponse3.getStatus(), OperationStatus.Success); // AssertJUnit.assertEquals (new String(data2), new String(junoResponse3.getValue())); // LOGGER.debug("Data: " + new String(junoResponse3.getValue())); // // LOGGER.debug("Crypt client1 delete key"); // cryptClient1.delete(key); // junoResponse = cryptClient2.get(key); // AssertJUnit.assertEquals (junoResponse.getStatus(), OperationStatus.NoKey); // } }
94
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/DataGenUtils.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.util.JunoClientUtil; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Random; /** * DataGenUtils provides utility methods for generating random data, such as * Strings and numbers. * <p> * This class is Thget-safe. * */ public class DataGenUtils { /** SCM ID String - do not remove */ public static final String SCM_ID = "$Id$"; /** String containing characters for generating random strings */ public static final String RANDOM_STRING_DATA = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM[]\\;',/`1234567890-={}|:\"<>?~!@#$%^&*()_+"; /** String containing characters for generating random numeric strings */ public static final String RANDOM_STRING_DATA_NUMERIC = "1234567890"; /** String containing characters for generating random alpha strings */ public static final String RANDOM_STRING_DATA_ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /** String containing characters for generating random alphanumeric strings */ public static final String RANDOM_STRING_DATA_ALPHANUM = RANDOM_STRING_DATA_ALPHA + RANDOM_STRING_DATA_NUMERIC; /** * Random generator. Although the javadoc does not specify if this class * is thget-safe, it appears to be so based on the results of a Google search. */ private static Random s_random = new Random(System.currentTimeMillis()); /** * Generate a String of random alpha data (no numerics). * * @param length the length of the string to gen; must be >= 0 * @throws IllegalArgumentException if length < 0 */ public static String genString(int length) { return genString(RANDOM_STRING_DATA, length); } /** * Generate a String of random alpha data. * * @param length the length of the string to gen; must be >= 0 * @throws IllegalArgumentException if length < 0 */ public static String genAlphaString(int length) { return genString(RANDOM_STRING_DATA_ALPHA, length); } /** * Generate a String of random alpha-numeric data. * * @param length the length of the string to gen; must be >= 0 * @throws IllegalArgumentException if length < 0 */ public static String genAlphaNumString(int length) { return genString(RANDOM_STRING_DATA_ALPHANUM, length); } /** * Generate a String of random numberic data. * * @param length the length of the string to gen; must be >= 0 * @throws IllegalArgumentException if length < 0 */ public static String genNumString(int length) { return genString(RANDOM_STRING_DATA_NUMERIC, length); } /** * Generate a String of random data. * * @param length the length of the string to gen; must be >= 0 * @throws IllegalArgumentException if sourceData is null * @throws IllegalArgumentException if length < 0 */ public static String genString(String sourceData, int length) { // Sanity check JunoClientUtil.throwIfNull(sourceData, "sourceData"); if (length < 0) { throw new IllegalArgumentException("length must be >= 0"); } StringWriter sw = new StringWriter(length); int maxRand = sourceData.length(); for (int i=0; i<length; ++i) { sw.write(sourceData, s_random.nextInt(maxRand), 1); } return sw.toString(); } /** * Generate some random bytes. * * @param length the length of the string to gen; must be >= 0 * @throws IllegalArgumentException if length < 0 */ public static byte[] genBytes(int length) { // Sanity check if (length < 0) { throw new IllegalArgumentException("length must be >= 0"); } byte[] bytes = new byte[length]; s_random.nextBytes(bytes); return bytes; } /** * Generate a random boolean. */ public static boolean genBoolean() { return s_random.nextBoolean(); } /** * Generate a random integer. */ public static int genInt() { return s_random.nextInt(); } /** * Generate a random integer up to some max. */ public static int genInt(int max) { return s_random.nextInt(max); } /** * Generate a random long. */ public static long genLong() { return s_random.nextLong(); } /** * Generate a random float. */ public static float genFloat() { return s_random.nextFloat(); } /** * Generate a random double. */ public static double genDouble() { return s_random.nextDouble(); } public static final Map<String,String> propsToMap(Properties props) { Map<String,String> map = new HashMap<String,String>(); for( Object key : props.keySet() ) { map.put((String)key, props.getProperty((String)key)); } return map; } /** * Create a new random key of size byteCount * * @param byteCount * @return the key as a string */ public static String createKey(int byteCount) { byte[] keyBytes = new byte[byteCount]; Random r = new Random(); for (int i = 0; i < byteCount; i++) { keyBytes[i] = (byte)rand(r ,'a', 'z'); } return new String(keyBytes); } public static int rand(Random rn, int lo, int hi) { int n = hi - lo + 1; int i = rn.nextInt() % n; if (i < 0) { i = -i; } return lo + i; } public static String createCompressablePayload(int size){ String [] words = {"Paypal","is","a","payments","company","in","San Fransisco","and","in","Austin","We","have","1 billon","Users","and", "thousands","of","merchants"}; String CretedPayload = words[0]; Random r = new Random(); while(CretedPayload.length() < size){ CretedPayload = CretedPayload + " " + words[rand(r ,0,words.length -1 )]; } return CretedPayload; } }
95
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/BatchReactGetTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory;import com.paypal.juno.client.JunoClient; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class BatchReactGetTest{ private JunoReactClient junoReactClient; private JunoReactClient junoReactClient2; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig1; private Properties pConfig2; private enum syncFlag {reactAsync, reactSync}; private int flag; private Logger LOGGER; @BeforeClass public void setup() throws IOException, InterruptedException { LOGGER = LoggerFactory.getLogger(BatchReactGetTest.class); URL url = BatchReactGetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig = new Properties(); pConfig.load(url.openStream()); LOGGER.debug("Read syncFlag"); String sync_flag = pConfig.getProperty("sync_flag_test", "0"); LOGGER.debug("*********SYNC FLAG: " + sync_flag); flag = Integer.parseInt(sync_flag.trim()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); URL url1 = BatchReactGetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig1 = new Properties(); pConfig1.load(url1.openStream()); pConfig1.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig1.setProperty(JunoProperties.RECORD_NAMESPACE, "NS2"); URL url2 = BatchReactGetTest.class.getResource("/com/paypal/juno/Juno_batch.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "junotoken"); try{ junoReactClient = JunoClientFactory.newJunoReactClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); junoReactClient2 = JunoClientFactory.newJunoReactClient(url); junoClient1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig1), SSLUtil.getSSLContext()); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); }catch (Exception e) { throw new RuntimeException(e); } Thread.sleep(3000); } @AfterClass public void cleanSetup() throws Exception{ } /** * Create and get multiple keys * @throws JunoException */ @Test public void testBatchGet() throws JunoException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); key[numKeys-1] = DataGenUtils.createKey(20).getBytes(); LOGGER.debug("key" + i + " is " + new String(key[i])); payload[i] = DataGenUtils.createKey(100).getBytes();; payload[9] = DataGenUtils.createKey(204800).getBytes(); ttl[i] = 200; ttl[6] = 259200; hmap.put(new String(key[i]), payload[i]); long createTime = System.currentTimeMillis(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i],createTime, JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; LOGGER.debug("reactASync is " + syncFlag.reactAsync.ordinal() + ", flag is " + flag); if (syncFlag.reactSync.ordinal() == flag) { //sync react call, flag 1 is sync call, flag 0 is async call LOGGER.debug("enter into sync create call"); batchResp = junoReactClient.doBatch(list).toIterable(); } else { //async react call LOGGER.debug("enter into async create call"); batchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } int i = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is thrown for batch Create", false); } List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item; LOGGER.debug("key " + i + " at get is " + new String(key[i])); item = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list1.add(item); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call LOGGER.debug("enter into sync get call"); getBatchResp = junoReactClient.doBatch(list1).toIterable(); } else { //async react call LOGGER.debug("enter into async get call"); getBatchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Create and get multiple keys with two keys expired * @throws JunoException */ @Test public void testBatchGetExpiredRecord() throws JunoException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing " + i; payload[i] = str.getBytes(); ttl[i] = 20000; ttl[3] = 3; ttl[8] = 4; hmap.put(new String(key[i]), payload[i]); long createTime = System.currentTimeMillis(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i],createTime, JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoReactClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } int i = 1; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + i + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success, mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); i++; } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue ("Exception is thrown for batch Create", false); } LOGGER.debug("Sleep for key to expire"); Thread.sleep (5000); List<JunoRequest> list1 = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { JunoRequest item = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list1.add(item); } LOGGER.debug("Read " + numKeys + " keys using batch Get(), no lifetime"); Iterable<JunoResponse> getBatchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoReactClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); if (mkey.equals (new String(key[3])) || mkey.equals(new String(key[8]))) { LOGGER.debug("Check for key to expire"); if (response.getStatus() != OperationStatus.NoKey ) { AssertJUnit.assertTrue ("Key not expired", false); } else { LOGGER.debug("Key expired as expected"); } } else { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Get batch keys with lifetime extended * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testGetWithLifeTimeExtented() throws JunoException, InterruptedException { LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create " + numKeys + " keys using batch Create"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(10).getBytes(); String str = "Hello Testing, Happy Friday" + i; payload[i] = str.getBytes(); ttl[i] = 4; hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Create); list.add(item); } try { Iterable<JunoResponse> batchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp = junoReactClient.doBatch(list).toIterable(); } else { //async react call batchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } int j = 0; for (JunoResponse mResponse: batchResp) { LOGGER.debug("Key: " + j + ": "+ new String(mResponse.getKey())); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); AssertJUnit.assertTrue(1 == mResponse.getVersion()); AssertJUnit.assertTrue(ttl[j] == mResponse.getTtl()); j++; } } catch (JunoException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); } List<JunoRequest> list1 = new ArrayList<>(); LOGGER.debug("Set and passing lifetime, some will have lifetime 0 passing"); for (int i = 0; i < numKeys; i ++) { ttl[i] = 0; ttl[2] = 30; ttl[9] = 20; hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); LOGGER.debug("Key: " + key[i]); JunoRequest item1 = new JunoRequest(key[i], null, 0, ttl[i], JunoRequest.OperationType.Get); list1.add(item1); } LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getBatchResp = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp = junoReactClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp = BatchReactSubscriber.async_dobatch(junoReactClient, list1); } for (JunoResponse response: getBatchResp) { String mkey = new String(response.getKey()); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); } Thread.sleep (5000); //Most keys will expired LOGGER.debug("Verify keys have lifetime=0 passing are expired"); Iterable<JunoResponse> getBatchResp1 = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp1 = junoReactClient.doBatch(list1).toIterable(); } else { //async react call getBatchResp1 = BatchReactSubscriber.async_dobatch(junoReactClient, list1); } for (JunoResponse response: getBatchResp1) { String mkey = new String(response.getKey()); if (!mkey.equals (new String(key[2])) && !mkey.equals(new String(key[9]))) { if (response.getStatus() != OperationStatus.NoKey ) { AssertJUnit.assertTrue ("Key not expired", false); } else { LOGGER.debug("Key expired as expected"); } } else { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(new String(hmap.get(mkey)), new String(response.getValue())); AssertJUnit.assertTrue(1 == response.getVersion()); AssertJUnit.assertEquals(hmapTTL.get(mkey), String.valueOf(response.getTtl())); } } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Verify appropriate JunoException is thrown when getting a key with zero length * @throws JunoException */ @Test public void testBatchGetEmptyKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with 1 key having zero length"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); key[9] = "".getBytes(); ttl[i]=10; payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, ttl[i], JunoRequest.OperationType.Set); JunoRequest getItem = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Get); list.add(item); getList.add(getItem); } try{ Iterable<JunoResponse> batchResp; LOGGER.debug("Read " + numKeys + " keys using batch Set()"); if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoReactClient.doBatch(list).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoReactClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try{ Iterable<JunoResponse> getResp; LOGGER.debug("Read " + numKeys + " keys using batch Get()"); if (syncFlag.reactSync.ordinal() == flag) { //sync react call getResp=junoReactClient.doBatch(list).toIterable(); } else { //async react call getResp=BatchReactSubscriber.async_dobatch(junoReactClient, list); } for (JunoResponse response: getResp) { if (response != null && response.getKey() != null && response.getKey() != key[9]) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Verify appropriate JunoException is thrown when keys not exist * @throws JunoException //TODO: check So we will still have key info in response even we didn't insert at all? */ @Test public void testBatchGetNotExist() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 4; long[] ttl = new long[numKeys]; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; HashMap<String, String> hmapTTL = new HashMap<String, String>(); HashMap<String, OperationStatus> hmapStatus = new HashMap<String, OperationStatus>(); HashMap<String, byte[]> hmap = new HashMap<String, byte[]>(); LOGGER.debug("Create 2 keys using Existing Juno Sync Client"); LOGGER.debug("Two keys are created with NS1, two key created with different Namespace"); key[0] = "56789".getBytes(); //key not exist in Juno key[1] = DataGenUtils.createKey(20).getBytes(); key[2] = "23456".getBytes(); //key not exist in Juno key[3] = DataGenUtils.createKey(10).getBytes(); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); payload[1] = data; payload[3] = data1; payload[0] = data1; payload[2] = data1; for (int i = 0; i < numKeys; i ++) { ttl[i]=(long)20; } junoClient1.delete("23456".getBytes()); junoClient1.delete("56789".getBytes()); try { Thread.sleep(2000); } catch (Exception ex) { LOGGER.debug(ex.getMessage()); } try { junoClient2.create(key[1], payload[1], ttl[1]); junoClient2.create(key[3], payload[3], ttl[3]); junoClient1.create(key[0], payload[0]); junoClient1.create(key[2], payload[2]); } catch (JunoException ex) { AssertJUnit.assertEquals("shouldn't come here ", false); } LOGGER.debug("Create Juno request items "); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { hmapStatus.put(new String(key[i]), OperationStatus.Success); hmapStatus.put(new String(key[0]), OperationStatus.NoKey); hmapStatus.put(new String(key[2]), OperationStatus.NoKey); hmap.put(new String(key[i]), payload[i]); hmapTTL.put(new String(key[i]), String.valueOf(ttl[i])); JunoRequest item = new JunoRequest(key[i], null, 0, 0, JunoRequest.OperationType.Get); list.add(item); } Iterable<JunoResponse> getBatchResp1 = null; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getBatchResp1 = junoReactClient.doBatch(list).toIterable(); } else { //async react call getBatchResp1 = BatchReactSubscriber.async_dobatch(junoReactClient, list); } for (JunoResponse response: getBatchResp1) { String mkey = new String(response.getKey()); LOGGER.debug("Key is??: " + mkey); AssertJUnit.assertEquals (hmapStatus.get(mkey), response.getStatus()); if (response.getStatus() == OperationStatus.Success) { AssertJUnit.assertEquals(hmap.get(mkey), response.getValue()); AssertJUnit.assertTrue(Integer.parseInt(hmapTTL.get(mkey)) - 10 <= response.getTtl() && response.getTtl() <= Integer.parseInt(hmapTTL.get(mkey))); AssertJUnit.assertTrue(1 == response.getVersion()); } } LOGGER.info("0"); LOGGER.info("Completed"); } /** * Verify appropriate JunoException is thrown when batch get to read key=null * @throws JunoException */ @Test public void testBatchGetNullKey() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with key = null"); List<JunoRequest> list = new ArrayList<>(); List<JunoRequest> getList = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); key[0] = null; payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Set); JunoRequest getItem = new JunoRequest(key[i], payload[i], (long)0, (long)0, JunoRequest.OperationType.Get); list.add(item); getList.add(getItem); } try{ LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> batchResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call batchResp=junoReactClient.doBatch(list).toIterable(); } else { //async react call batchResp=BatchReactSubscriber.async_dobatch(junoReactClient, list); } for (JunoResponse response: batchResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals (OperationStatus.Success, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } try{ LOGGER.debug("Read " + numKeys + " keys using batch Get()"); Iterable<JunoResponse> getResp; if (syncFlag.reactSync.ordinal() == flag) { //sync react call getResp=junoReactClient.doBatch(getList).toIterable(); } else { //async react call getResp=BatchReactSubscriber.async_dobatch(junoReactClient, getList); } for (JunoResponse response: getResp) { if (response != null && response.getKey() != null) { AssertJUnit.assertEquals(OperationStatus.Success, response.getStatus()); AssertJUnit.assertEquals(1, response.getVersion()); } else { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } } } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("key must not be null")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Get batch keys to pass TTL > 3 days * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchGetLifetimeLongerThan3Days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; long[] ttl = new long[numKeys]; Random r = new Random(); LOGGER.debug("Create request item with key = null"); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); ttl[i] = 100; ttl[4] = 259201; JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, (long)ttl[i], JunoRequest.OperationType.Get); list.add(item); } Iterable <JunoResponse> gResp = new ArrayList<>(); try { LOGGER.debug("Read " + numKeys + " keys using batch Get()"); if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoReactClient.doBatch(list).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for one item with NULL key", false); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-1); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Get batch keys with keys >=256 bytes * Verify appropriate JunoException is thrown * @throws JunoException */ @Test public void testBatchGetKey257Bytes() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 10; byte[][] key = new byte[numKeys][]; byte[][] payload = new byte[numKeys][]; Random r = new Random(); LOGGER.debug("Create request item with key = null"); key[9] = DataGenUtils.createKey(258).getBytes(); key[4] = DataGenUtils.createKey(129).getBytes(); List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < numKeys; i ++) { if ( i != 4 && i != 9 ) { key[i] = DataGenUtils.createKey(DataGenUtils.rand(r, 1, 128)).getBytes(); } payload[i] = DataGenUtils.genBytes(DataGenUtils.rand(r, 1, 4048)); JunoRequest item = new JunoRequest(key[i], null, (long)0, (long)0, JunoRequest.OperationType.Get); list.add(item); } Iterable <JunoResponse> gResp = new ArrayList<>(); try { LOGGER.debug("Read " + numKeys + " keys using batch Get()"); if (syncFlag.reactSync.ordinal() == flag) { //sync react call gResp = junoReactClient.doBatch(list).toIterable(); } else { //async react call gResp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception should not thrown for only one item key with long length", false); } int i=0; for (JunoResponse response: gResp) { String mkey = new String(response.getKey()); if ( mkey.equals(new String(key[9])) || mkey.equals(new String(key[4]))) { AssertJUnit.assertEquals (OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertEquals (OperationStatus.NoKey, response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-2); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Batch keys with no Item in the JunoRequest list * Verify appropriate JunoException is thrown * @throws JunoException //TODO: ask no exception for empty list? test case has real failure for now */ //@Test public void testBatchGetZeroItem() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); LOGGER.debug("Send 0 item to Batch create"); List<JunoRequest> list = new ArrayList<>(); LOGGER.debug("\n===Batch Create is sent "); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call junoReactClient.doBatch(list).toIterable(); } else { //async react call BatchReactSubscriber.async_dobatch(junoReactClient, list); } AssertJUnit.assertTrue ("Exception is not thrown for no key in Juno Request", false); } catch (IllegalArgumentException mex) { LOGGER.debug("Exception occurs: " + mex.getMessage()); AssertJUnit.assertTrue(mex.getMessage().contains("Empty juno request list")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Create batch keys with a key having TTL more than 3 days * Verify get correct response for each item including long TTL one */ @Test public void testBatchSetTTLmorethan3days() throws JunoException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); int numKeys = 5; LOGGER.debug("Create " + numKeys + " keys with a key having > lifetime > 3 days"); byte[][] key = new byte[numKeys][]; long[] ttl = new long[numKeys]; byte[][] payload = new byte[numKeys][]; List<JunoRequest> list = new ArrayList<>(); HashMap <String, Long> hmapTTL = new HashMap <String, Long>(); for (int i = 0; i < numKeys; i ++) { key[i] = DataGenUtils.createKey(25).getBytes(); String str = "Hello Testing testing " + i; payload[i] = str.getBytes(); ttl[i] = 20; ttl[1] = 259201; hmapTTL.put(new String(key[i]), ttl[i]); JunoRequest item = new JunoRequest(key[i], null, (long)0, ttl[i], System.currentTimeMillis(), JunoRequest.OperationType.Get); list.add(item); } LOGGER.debug("\n===Batch Get is sent "); Iterable <JunoResponse> resp = new ArrayList<JunoResponse>(); try { if (syncFlag.reactSync.ordinal() == flag) { //sync react call resp = junoReactClient.doBatch(list).toIterable(); } else { //async react call resp = BatchReactSubscriber.async_dobatch(junoReactClient, list); } } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is not thrown for TTL > 3 days", false); } int i = 0; for (JunoResponse response: resp) { String mkey = new String(response.getKey()); if (mkey.equals(new String(key[1]))) { AssertJUnit.assertEquals(OperationStatus.IllegalArgument, response.getStatus()); } else { AssertJUnit.assertTrue(OperationStatus.NoKey == response.getStatus()); i++; } } AssertJUnit.assertEquals(i, numKeys-1); } }
96
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/ConnectionPoolingTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Date; import java.util.Properties; import java.util.UUID; import org.apache.commons.lang.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ConnectionPoolingTest{ private JunoClient junoClient1; private JunoClient junoClient2; private JunoClient junoClient3; private JunoClient junoClient4; private JunoClient junoClient5; private JunoClient junoClient6; private JunoClient junoClient7; private Logger LOGGER; private Properties pConfig; @BeforeClass public void setup() throws JunoException, IOException, InterruptedException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { URL url = ConnectionPoolingTest.class.getResource("/com/paypal/juno/Juno.properties"); LOGGER = LoggerFactory.getLogger(ConnectionPoolingTest.class); junoClient1 = JunoClientFactory.newJunoClient(url); junoClient2 = JunoClientFactory.newJunoClient(url); junoClient3 = JunoClientFactory.newJunoClient(url); junoClient4 = JunoClientFactory.newJunoClient(url); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.PORT, "8080"); pConfig.setProperty(JunoProperties.USE_SSL, "false"); junoClient5 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); pConfig.setProperty(JunoProperties.PORT, "5080"); pConfig.setProperty(JunoProperties.USE_SSL, "true"); pConfig.setProperty(JunoProperties.BYPASS_LTM, "true"); pConfig.setProperty(JunoProperties.CONNECTION_LIFETIME, "5000"); try{ junoClient6 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); }catch(Exception e){ //System.out.println("Exception in constructor :"+e.getMessage()); } pConfig.setProperty(JunoProperties.PORT, "8080"); pConfig.setProperty(JunoProperties.USE_SSL, "false"); pConfig.setProperty(JunoProperties.RESPONSE_TIMEOUT,"1"); pConfig.setProperty(JunoProperties.ENABLE_RETRY, "true"); junoClient7 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig), SSLUtil.getSSLContext()); Thread.sleep(3000); } @Test(enabled = false) private void testLoadCreates(int records, int loops ) throws JunoException, Exception { long totalCreateTime = 0L; String[] key = new String[loops]; StopWatch clock = new StopWatch(); String data[] = new String[100]; for (int iter = 0; iter < loops; ++iter) { key[iter] = DataGenUtils.createKey(loops+20); data[iter] = "testing datadasfkkkkkksd'''''''8!@#$*((())-/?:;677777777fggggggggggggggggh~`" + iter; byte[] payload = data[iter].getBytes(); clock.start(); junoClient1.create(key[iter].getBytes(), payload, 3600L); clock.stop(); totalCreateTime += clock.getTime(); clock.reset(); } LOGGER.debug("Time per insert: " + totalCreateTime / loops + " ms/insert"); LOGGER.debug("Total time for " + loops + " loops creating " + records + "KB of data: " + totalCreateTime / 1000 + " seconds"); for (int iter = 0; iter < loops; ++iter){ JunoResponse response = junoClient1.get(key[iter].getBytes()); AssertJUnit.assertEquals( key[iter], new String(response.key())); LOGGER.debug(new String (response.getValue())); AssertJUnit.assertEquals( data[iter], new String (response.getValue())); junoClient1.delete(key[iter].getBytes()); } } @Test(enabled = false) private void testLoadGets(int records, int loops ) throws JunoException, IOException { String[] key = new String[loops]; for (int iter = 0; iter < loops; ++iter){ key[iter] = DataGenUtils.createKey(1024*iter+1); byte[] payload = DataGenUtils.genBytes(1024 * records); junoClient2.create(key[iter].getBytes(), payload); } JunoResponse[] junoRecords = new JunoResponse[loops]; long totalGetTime = 0L; StopWatch clock = new StopWatch(); for (int iter = 0; iter < loops; ++iter) { clock.start(); junoRecords[iter] = junoClient2.get(key[iter].getBytes()); clock.stop(); totalGetTime += clock.getTime(); clock.reset(); } LOGGER.debug("Time per Get: " + totalGetTime / loops + " ms/get"); LOGGER.debug("Total time for " + loops + " loops getting " + records + "KB of data: " + totalGetTime / 1000 + " seconds"); //for(int iter = 0; iter < loops; ++iter){ // LOGGER.debug("Record " + iter +":" + junoRecords[iter]); //} for (int iter = 0; iter < loops; ++iter){ junoClient2.delete(key[iter].getBytes()); } } @Test(enabled = false) private void testLoadUpdates(int records, int loops ) throws JunoException, IOException { byte[] data = DataGenUtils.genBytes(10); String key[] = new String[loops]; for (int iter = 0; iter < loops; ++iter){ key[iter] = DataGenUtils.createKey(iter+1); junoClient1.create(key[iter].getBytes(), data); } long totalUpdateTime = 0L; StopWatch clock = new StopWatch(); for (int iter = 0; iter < loops; ++iter) { byte[] payload = DataGenUtils.genBytes(1024 * records); clock.start(); junoClient1.update(key[iter].getBytes(), payload); clock.stop(); totalUpdateTime += clock.getTime(); clock.reset(); } LOGGER.debug("Time per update: " + totalUpdateTime / loops + " ms/update"); LOGGER.debug("Total time for " + loops + " loops updating " + records + "KB of data: " + totalUpdateTime / 1000 + " seconds"); for (int iter = 0; iter < loops; ++iter){ junoClient1.delete(key[iter].getBytes()); } } @Test(enabled = false) private void testLoadCAS (int records, int loops ) throws JunoException, IOException { byte[] data = DataGenUtils.genBytes(10); String key[] = new String[loops]; JunoResponse mResponse[] = new JunoResponse[loops]; for (int iter = 0; iter < loops; ++iter){ key[iter] = DataGenUtils.createKey(iter+1); mResponse[iter] = junoClient1.create(key[iter].getBytes(), data); } LOGGER.debug("\nKey creation is done for all"); long totalUpdateTime = 0L; long lifetime = 120; StopWatch clock = new StopWatch(); for (int iter = 0; iter < loops; ++iter) { byte[] payload = DataGenUtils.genBytes(1024 * records); clock.start(); junoClient1.compareAndSet(mResponse[iter].getRecordContext(), payload, lifetime); clock.stop(); totalUpdateTime += clock.getTime(); clock.reset(); } LOGGER.debug("Time per cas: " + totalUpdateTime / loops + " ms/update"); LOGGER.debug("Total time for " + loops + " loops updating " + records + "KB of data: " + totalUpdateTime / 1000 + " seconds"); for (int iter = 0; iter < loops; ++iter){ junoClient1.delete(key[iter].getBytes()); } } @Test(enabled = false) private void testLoadDestroys(int records, int loops ) throws JunoException, IOException { byte[] payload = DataGenUtils.genBytes(1024 * records); String[] key = new String[loops]; for (int iter = 0; iter < loops; ++iter){ key[iter] = DataGenUtils.createKey(iter+1); junoClient1.create(key[iter].getBytes(), payload); } long totalDestroyTime = 0L; StopWatch clock = new StopWatch(); for (int iter = 0; iter < loops; ++iter) { clock.start(); junoClient1.delete(key[iter].getBytes()); clock.stop(); totalDestroyTime += clock.getTime(); clock.reset(); } LOGGER.debug("Time per delete: " + totalDestroyTime / loops + " ms/delete"); LOGGER.debug("Total time for " + loops + " loops deleteing " + records + "KB of data: " + totalDestroyTime / 1000 + " seconds"); } @Test private void testLoadAll() throws JunoException, IOException { long totalCreateTime = 0L; int loops = 100; int records = 10; byte[][] key = new byte[loops][]; for (int iter = 0; iter < loops; ++iter){ key[iter] = DataGenUtils.genBytes(20); } StopWatch clock = new StopWatch(); for (int iter = 0; iter < loops; ++iter) { clock.start(); byte[] payload = DataGenUtils.genBytes(1024 * records); byte[] payload1 = DataGenUtils.genBytes(1024 * records); junoClient5.create(key[iter], payload); junoClient5.update(key[iter], payload1); junoClient5.get(key[iter]); junoClient5.delete(key[iter]); junoClient6.delete(key[iter]); clock.stop(); totalCreateTime += clock.getTime(); clock.reset(); } LOGGER.debug("Time per all(insert+update+get+delete): " + totalCreateTime / loops + " ms/all"); LOGGER.debug("Total time for " + loops + " loops for all " + records + "KB of data: " + totalCreateTime / 1000 + " seconds"); } @Test private void testResponseTimeout() throws JunoException, IOException { byte[] key = DataGenUtils.genBytes(20); byte[] payload = DataGenUtils.genBytes(1024); try{ junoClient7.create(key, payload); }catch(Exception e){ AssertJUnit.assertTrue(e.getMessage().contains("Response Timed out")); } } @Test(enabled = false) public void testCreateGetKey(int loops) throws Exception { String key, key2, key3; for (int i = 0; i < loops; i++) { key = UUID.randomUUID().toString(); key2 = UUID.randomUUID().toString(); key3 = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); JunoResponse response = junoClient1.create(key.getBytes(), bytes); assert(response.getStatus() == OperationStatus.Success); // Check for the record response = junoClient1.get(key.getBytes()); assert(response.getStatus() == OperationStatus.Success); String dataOut = new String(response.getValue()); LOGGER.debug("Data: " + dataOut); assert (data.equals(dataOut)); String data2 = "testing data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes2 = data2.getBytes(); JunoResponse response2 = junoClient2.create(key2.getBytes(), bytes2); assert(response2.getStatus() == OperationStatus.Success); response2 = junoClient2.get(key2.getBytes()); assert(response2.getStatus() == OperationStatus.Success); String dataOut2 = new String(response2.getValue()); LOGGER.debug("Data: " + dataOut2); assert (data2.equals(dataOut2)); String data3 = "testing juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes3 = data3.getBytes(); JunoResponse response3 = junoClient3.create(key3.getBytes(), bytes3); assert(response3.getStatus() == OperationStatus.Success); response3 = junoClient3.get(key3.getBytes()); assert(response3.getStatus() == OperationStatus.Success); String dataOut3 = new String(response3.getValue()); LOGGER.debug("Data: " + dataOut3); assert (data3.equals(dataOut3)); } LOGGER.info("SUCCESS"); } //juno.use.persistent.connection = true //juno.connection.reCycleDuration = 500 //Verify log has: //"Recycling connection as connection lifetime expired" //Should have "The pool size is:2" as we use 2 threads. @Test(threadPoolSize = 2, invocationCount = 2) //Passed on 6/29 public void testRecyleAfter1second1() throws JunoException, Exception { testLoadCreates(5, 1); Thread.sleep (1000); testLoadCreates(5, 1); } //juno.use.persistent.connection = true //juno.connection.reCycleDuration = 500 //Verify log has: //"Recycling connection as connection lifetime expired" //Should always see "The pool size is:1" as we use 1 threads. @Test(threadPoolSize = 1, invocationCount = 2) //Passed on 6/29 public void testCreateWith1thread() throws JunoException, Exception { testLoadCreates(5, 10); } //juno.use.persistent.connection = true //juno.connection.reCycleDuration = 500 //Verify log that the recycle happens only before the 3rd request @Test(threadPoolSize = 1, invocationCount = 1) //Passed on 6/29 public void testRecycleAfter9second() throws JunoException, Exception { LOGGER.debug("run testLoadGet"); testLoadGets(5, 1); LOGGER.debug("sleep 8 secs"); Thread.sleep (9000); LOGGER.debug("run testLoadUpdates"); testLoadUpdates(5, 1); LOGGER.debug("sleep 1 secs"); Thread.sleep (1000); LOGGER.debug("run testLoadCAS"); testLoadCAS(5, 1); } //juno.use.persistent.connection = true //Do operations on multiple pools with insert and get operation in //Parallel. Should not see any error. Verify that the log shows //3 different connections insertd for each pool and the pool should //have total 6 connections after the fist operation is done. @Test(threadPoolSize = 2, invocationCount = 2) public void testMultiPoolMultithread() throws JunoException, Exception { testCreateGetKey(1); Thread.sleep (100); testCreateGetKey(1); } //juno.use.persistent.connection = true //Do operations on multiple pools with insert and get operation in //Parallel. Should not see any error. Verify that the log shows //3 different connections insertd for each pool and the pool should //have total of 3 connections after the fist operation is done. @Test(threadPoolSize = 1, invocationCount = 2) public void testMultiPoolSinglethread() throws JunoException, Exception { testCreateGetKey(1); Thread.sleep (100); testCreateGetKey(1); } @Test public void testReusingConnection() throws JunoException, Exception { String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); //Create a key using junoClient3 object on stage2t4663. JunoResponse response = junoClient3.create(key.getBytes(), bytes); assert(response.getStatus() == OperationStatus.Success); //Read the Key using junoClient4 object which is pointing to a unknown stage as primary. //But the port will be the same so this get operation has to use the same connection which was insertd //for the above insert operation and get the key successfully. response = junoClient4.get(key.getBytes()); assert(response.getStatus() == OperationStatus.Success); String dataOut = new String(response.getValue()); assert (data.equals(dataOut)); } @Test public void testColoFailover() throws JunoException, Exception { String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); //Create a key using junoClient4 object. The connection to primary server will fail. //But the secondary server will succeed. JunoResponse response = junoClient4.create(key.getBytes(), bytes); assert(response.getStatus() == OperationStatus.Success); //Read the same key using junoClient3 object. The operation has to be successful. //There should be any new connection insertd.It has to use the existing connection. response = junoClient3.get(key.getBytes()); assert(response.getStatus() == OperationStatus.Success); String dataOut = new String(response.getValue()); assert (data.equals(dataOut)); } }
97
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/UpdateTest.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.util.SSLUtil; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class UpdateTest{ private JunoClient junoClient; private JunoClient junoClient1; private JunoClient junoClient2; private Properties pConfig; private Properties pConfig2; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException { URL url = JunoClientFactory.class.getResource("/com/paypal/juno/Juno.properties"); LOGGER = LoggerFactory.getLogger(UpdateTest.class); pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.APP_NAME, "QATestApp"); pConfig.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); junoClient1 = JunoClientFactory.newJunoClient(url); URL url2 = JunoClientFactory.class.getResource("/com/paypal/juno/Juno.properties"); pConfig2 = new Properties(); pConfig2.load(url2.openStream()); pConfig2.setProperty(JunoProperties.APP_NAME, "QATestApp2"); pConfig2.setProperty(JunoProperties.RECORD_NAMESPACE, "NS1"); try { junoClient = new JunoTestClientImpl(new JunoPropertiesProvider(pConfig),null,0); junoClient2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig2), SSLUtil.getSSLContext()); Thread.sleep(1000); } catch (Exception ex) { LOGGER.debug(ex.getMessage()); } } @Test public void testUpdateWithoutTTL() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info(new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); // It uses the default TTL 1800sec JunoResponse junoResponse =junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } JunoResponse junoResponse1 = junoClient.update(key, data); // Update without TTL AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertFalse(1800 == junoResponse1.getTtl()); // It cannot be 1800 as we waited for 10sec LOGGER.info("Completed"); } /** * Send a update request with different payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithDiffPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] data2 = DataGenUtils.genBytes(20); byte[] data3 = DataGenUtils.genBytes(40); byte[] data4 = DataGenUtils.genBytes(800); long lifetime = 22000; JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoClient.update(key, data1); //ttl won't be updated AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); assert (mResponse.getStatus().getCode() == OperationStatus.Success.getCode()); junoResponse = junoClient.update(key,data2, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(3 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); junoResponse = junoClient.update(key, data3, 10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(4 == junoResponse.getVersion()); AssertJUnit.assertTrue(lifetime-3 <= junoResponse.getTtl() && junoResponse.getTtl() <= lifetime); junoResponse = junoClient.update(key, data4, 0); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(5 == junoResponse.getVersion()); AssertJUnit.assertTrue(junoResponse.getTtl() <= lifetime && junoResponse.getTtl() >= lifetime-5); JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(5 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data4.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data4), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with same payload * @throws JunoException * @throws IOException */ @Test public void testUpdateWithSamePayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse =junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient.update(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(junoResponse.getValue().length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(junoResponse.getValue()), new String(junoResponse1.getValue())); AssertJUnit.assertTrue(1800-8 <= junoResponse1.getTtl() && junoResponse1.getTtl() <= 1800); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update with empty key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithEmptyKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = "".getBytes(); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.update(key, data); AssertJUnit.assertTrue ("Exception should happen for empty key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a update request with null key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithNullKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = null; byte[] data = DataGenUtils.genBytes(10); try{ junoClient.update(key, data); AssertJUnit.assertTrue ("Exception should happen for null key", false); }catch(Exception mex){ AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be null or empty")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a update request with no key exists on server and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testUpdateKeyWhichDoesNotExist() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(64); byte[] data = DataGenUtils.genBytes(10); try { JunoResponse mResponse = junoClient.update(key, data); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a update request with 128 bytes key and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith128BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = DataGenUtils.genBytes(128); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key1, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.update(key1, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key1, junoResponse.getKey()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with 130 bytes key and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith129BytesKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = DataGenUtils.genBytes(129); byte[] data = DataGenUtils.genBytes(10); try{ junoClient.update(key1, data); AssertJUnit.assertTrue ("Exception should happen for key > 128 bytes", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document key must not be larger than 128 bytes")); } } /** * Send a update request with mix of special chars and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithSpecialCharsKey() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); JunoPropertiesProvider prop = new JunoPropertiesProvider(pConfig); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key1 = "@@#$%^&*()_+?>,<|}{[]~abc780=.".getBytes(); byte[] data = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.delete(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.create(key1, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.update(key1, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key1, junoResponse.key()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); junoResponse = junoClient.get(key1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); AssertJUnit.assertTrue(junoResponse.getTtl() <= prop.getDefaultLifetime() && junoResponse.getTtl() >= prop.getDefaultLifetime()-3); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with zero lifetime, the original lifetime for the * object will be retained. * @throws JunoException * @throws IOException */ @Test public void testUpdateWithZeroLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data, (long)3); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.update(key, data2, (long)0); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); Thread.sleep (4000); try { JunoResponse mResponse = junoClient.update(key, data); AssertJUnit.assertEquals (OperationStatus.NoKey, mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } /** * Send a update request with negative lifetime, exception will be throw * @throws JunoException * @throws IOException */ @Test public void testUpdateWithNegativeLifetime() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data, (long)3); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); try { junoClient.update(key, data2, (long)-1); AssertJUnit.assertTrue(false); } catch (JunoException mex) { AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document's TTL cannot be negative")); LOGGER.info("0"); LOGGER.info("Completed"); } } /** * Send a update request without lifetime, default lifetime will be updated for existing Juno * @throws JunoException * @throws IOException */ @Test public void testUpdateWithoutLifetime() throws JunoException, Exception{ //TODO: ??? LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); byte[] data2 = DataGenUtils.genBytes(10); JunoResponse junoResponse = junoClient.create(key, data, (long)3); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); LOGGER.debug("lifetime is " + junoResponse.getTtl()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse mResponse = junoClient.update(key, data2); // This should not update the Life time AssertJUnit.assertEquals(OperationStatus.Success, mResponse.getStatus()); LOGGER.debug("updated lifetime is " + mResponse.getTtl()); Thread.sleep (4000); // Sleep for 2 sec so that the key expires mResponse = junoClient.update(key, data); AssertJUnit.assertEquals(OperationStatus.NoKey, mResponse.getStatus()); mResponse = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with 3 days lifetime and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259200; JunoResponse junoResponse = junoClient.create(key, data, (long)10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.update(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /** * Send a update request with more than 3 days lifetime and should generate an * exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithMorethan3DaysLifetime() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] key = DataGenUtils.genBytes(10); byte[] data = DataGenUtils.genBytes(10); long lifetime = 259201; try{ JunoResponse junoResponse = junoClient.create(key, data, (long)10); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoClient.update(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue ("Exception should happen for life time > 3 days", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("Invalid lifetime. current lifetime=259201, max configured lifetime=259200")); } } /** * Send a update request with null payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithNullPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoClient.update(key, null); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(0, junoResponse1.getValue().length); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertFalse(true); } } /** * Send a update request with empty payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithEmptyPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(64); byte[] key = DataGenUtils.genBytes(64); byte[] data1 = "".getBytes(); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoClient.update(key, data1); LOGGER.info("0"); }catch(Exception mex){ AssertJUnit.assertTrue("empty payload should be allowed, why come to exception?", false); LOGGER.info("2"); } finally { LOGGER.info("Completed"); } } /** * Send a update request with 200KB payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWith200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204800); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = null; try { junoResponse1 = junoClient.update(key, data1); } catch (JunoException ex) { LOGGER.debug("Exception occured: " + ex.getMessage()); AssertJUnit.assertTrue(false); } AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); } /** * Send a update request with more than 200KB payload and should generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithMorethan200KBPayload() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(204801); byte[] key = DataGenUtils.genBytes(64); try{ JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); @SuppressWarnings("unused") JunoResponse junoResponse1 = junoClient.update(key, data1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue ("Exception should happen for big payload > 200KB", false); }catch(Exception mex){ LOGGER.debug(mex.getCause().getMessage()); AssertJUnit.assertTrue(mex.getCause().getMessage().contains("The Document Value must not be larger than 204800 bytes")); LOGGER.info("Exception", mex.getMessage()); LOGGER.info("2"); LOGGER.info("Completed"); } } /** * Send a update request with Lifetime and payload and should not generate an exception * @throws JunoException * @throws IOException */ @Test public void testUpdateWithLifeTimeAndPayload() throws JunoException, Exception{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(1000); long lifetime =10; long lifetime1 = lifetime+2; long lifetime2 = lifetime1+5; byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data, lifetime); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); junoResponse = junoClient.update(key, data1, lifetime1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); JunoResponse junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse1.getStatus()); AssertJUnit.assertTrue (junoResponse1.getStatus().getCode() == OperationStatus.Success.getCode()); //Sleep 11 seconds, key should not expired Thread.sleep (11000); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); Thread.sleep (4000); //Sleep 2 more seconds for a total of 13 seconds try { JunoResponse mResponse = junoClient.update(key, data1, lifetime2); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } //Below tests needs to be reviewed This is important. /************************************************* * Create 2 client objects with namespaces NS1 & NS2. * Create records with same key under both clients. * Update the record under NS1 only. *************************************************/ @Test public void testUpdateInOneOfTheNameSpaces() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(11); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data, (long)20); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient1.create(key, data); //same appname, different namespace junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(1 == junoResponse1.getVersion()); AssertJUnit.assertTrue(OperationStatus.Success == junoResponse1.getStatus()); JunoResponse junoResponse2 = junoClient.compareAndSet(junoResponse.getRecordContext(), data1, (long)5); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(junoResponse.key(), junoResponse2.key()); AssertJUnit.assertTrue(2 == junoResponse2.getVersion()); junoResponse2 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertEquals(data1.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse2.getValue())); AssertJUnit.assertTrue(junoResponse.getValue().length < junoResponse2.getValue().length); AssertJUnit.assertTrue(new String(junoResponse.getValue()) != new String(junoResponse2.getValue())); junoResponse2 = junoClient1.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse2.getStatus()); AssertJUnit.assertTrue(1 == junoResponse2.getVersion()); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * Create two clients with the same namespaces but * different application names. Create a record * using client1 with key k1.Update the record * with key k1 using client2. *************************************************/ @Test public void testUpdateWithSameNameSpaceDiffAppname() throws JunoException, IOException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(20); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.status()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success,junoResponse.status()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); JunoResponse junoResponse1 = junoClient2.update(key, data1); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse1.getStatus()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); LOGGER.info("0"); LOGGER.info("Completed"); } /************************************************* * Attempting update expired data * @throws InterruptedException *************************************************/ @Test public void testUpdateExpiredData() throws JunoException, IOException, InterruptedException{ LOGGER.info("\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ",Integer.toHexString((new Random()).nextInt(0x10000000) + 3846)); byte[] data = DataGenUtils.genBytes(10); byte[] data1 = DataGenUtils.genBytes(10); byte[] key = DataGenUtils.genBytes(64); JunoResponse junoResponse = junoClient.create(key, data, (long)7); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); junoResponse = junoClient.get(key); AssertJUnit.assertEquals(OperationStatus.Success, junoResponse.getStatus()); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); Thread.sleep(10000); try { JunoResponse mResponse = junoClient1.update(key, data1); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for key", false); LOGGER.info("0"); } finally { LOGGER.info("Completed"); } } }
98
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/test/java/com/paypal/qa/juno/usf/JunoUSFFactoryChild.java
// // Copyright 2023 PayPal Inc. // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.paypal.qa.juno.usf; import com.paypal.juno.client.JunoClient; import javax.inject.Inject; import javax.inject.Named; import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration("classpath:spring-config.xml") @Component public class JunoUSFFactoryChild extends JunoUSFFactoryBase { @Inject public JunoUSFFactoryChild(@Named("junoClientAuth")JunoClient junoClient) { super(junoClient); } public JunoClient getFIJunoClient() { return getFieldInjectedJunoClient(); } public JunoClient getCIJunoClient() { return getConstructorInjectedJunoClient(); } }
99