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/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/JunoUSFFactoryRChild.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.JunoReactClient; 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 JunoUSFFactoryRChild extends JunoUSFFactoryRBase { @Inject public JunoUSFFactoryRChild(@Named("junoReactClientAuth")JunoReactClient junoReactClient) { super(junoReactClient); } public JunoReactClient getFIJunoReactClient() { return getFieldInjectedJunoReactClient(); } public JunoReactClient getCIJunoReactClient() { return getConstructorInjectedJunoReactClient(); } }
100
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/JunoUSFFactoryBase.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.test.context.testng.AbstractTestNGSpringContextTests; abstract public class JunoUSFFactoryBase extends AbstractTestNGSpringContextTests { //Inject Juno object here @Inject @Named("junoClientAuth") JunoClient junoClientF; JunoClient junoClientC; // @Inject // @Named("junoReactClientAuth") // JunoReactClient junoReactClientF; // // JunoReactClient junoReactClientC; public JunoUSFFactoryBase(JunoClient junoClient) { this.junoClientC = junoClient; } // public JunoUSFFactoryBase(JunoReactClient junoReactClient) { // this.junoReactClientC = junoReactClient; // } public JunoClient getFieldInjectedJunoClient() { return this.junoClientF; } public JunoClient getConstructorInjectedJunoClient() { return this.junoClientC; } // public JunoReactClient getFieldInjectedJunoReactClient() { // return this.junoReactClientF; // } // // public JunoReactClient getConstructorInjectedJunoReactClient() { // return this.junoReactClientC; // } }
101
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/JunoUSFFactoryRBase.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.JunoReactClient; import javax.inject.Inject; import javax.inject.Named; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; abstract public class JunoUSFFactoryRBase extends AbstractTestNGSpringContextTests { //Inject Juno object here @Inject @Named("junoReactClientAuth") JunoReactClient junoReactClientF; JunoReactClient junoReactClientC; public JunoUSFFactoryRBase(JunoReactClient junoReactClient) { this.junoReactClientC = junoReactClient; } public JunoReactClient getFieldInjectedJunoReactClient() { return this.junoReactClientF; } public JunoReactClient getConstructorInjectedJunoReactClient() { return this.junoReactClientC; } }
102
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/JunoUSFFactoryClientTest.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 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.exception.JunoException; import com.paypal.qa.juno.DataGenUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.lang.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit;import com.paypal.juno.client.JunoAsyncClient; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * These test cases to test JunoClientUSFFactory */ @ContextConfiguration("classpath:spring-config.xml") @Component public class JunoUSFFactoryClientTest extends AbstractTestNGSpringContextTests { @Inject @Named("junoClient5") JunoClient junoClient; @Inject @Named("junoClient6") JunoClient junoClient6; @Inject @Named("junoRClient1") JunoReactClient junoRctClient; @Inject @Named("junoRClient2") JunoReactClient junoRTimeoutClient; @Inject JunoClient junoSyncClient; @Inject JunoAsyncClient junoAsyncClient; @Inject JunoReactClient junoReactClient; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException { LOGGER = LoggerFactory.getLogger(JunoUSFFactoryClientTest.class); LOGGER.debug("Read syncFlag test to findout what needs to be run"); // Do nothing } /** * This is a helper function to do create/read/update/delete keys * @param records: to use for payload size * @param loops: Number of keys to be created * @throws JunoException * @throws IOException */ //@Test private void testLoadAll(int records, int loops ) throws JunoException, IOException { long totalCreateTime = 0L; String[] key = new String[loops]; for (int iter = 0; iter < loops; ++iter){ key[iter] = DataGenUtils.createKey(iter+1); } 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); junoReactClient.create(key[iter].getBytes(), payload, 100L).block(); junoClient.update(key[iter].getBytes(), payload1, 100L); JunoResponse junoResponse = junoClient.get(key[iter].getBytes()); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); AssertJUnit.assertEquals(key[iter], new String(junoResponse.key())); //System.out.println ("Version: " + junoResponse.getVersion() ); AssertJUnit.assertEquals(new String(payload1), new String(junoResponse.getValue())); junoClient.delete(key[iter].getBytes()); clock.stop(); totalCreateTime += clock.getTime(); clock.reset(); } //System.out.println("Time per all(create+update+get+delete): " + totalCreateTime / loops + " ms/all"); //System.out.println("Total time for " + loops + " loops for all "+ records + "KB of data: " + totalCreateTime / 1000 + " seconds"); } /** * This test case calls testLoadAll() to create/update/read/delete 100 records * @throws JunoException * @throws IOException */ @Test public void testLoadAllForOneHundredRecords() throws JunoException, IOException { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); try{ testLoadAll(200, 10); }catch(IllegalArgumentException iaex){ //System.out.println ("Exception occur: " + iaex.getMessage()); AssertJUnit.assertTrue(iaex.getMessage().contains("Invalid payload size. current payload size=1024000, max payload size=204800")); }catch(Exception e){ //System.out.println("Exception occured: "+e.getMessage()); } } /** * Create and read the same key back */ @Test public void testCreateKey() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); JunoResponse response = junoClient.create(key.getBytes(), bytes); // Check for the record response = junoClient.get(key.getBytes()); String dataOut = new String(response.getValue()); //System.out.println ("Data: " + dataOut); assert (data.equals(dataOut)); JunoResponse rresponse = junoRctClient.create(key.getBytes(), bytes).block(); rresponse = junoRctClient.get(key.getBytes()).block(); String rdataOut = new String(rresponse.getValue()); //System.out.println ("Data from reactClient is : " + rdataOut); assert (data.equals(rdataOut)); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Test with mixed Object types. */ @Test public void mixedObjectTest() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); String key = UUID.randomUUID().toString(); String data = "data to store in juno by Sync client " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); // Create the Key using Juno Sync Client JunoResponse response = junoSyncClient.create(key.getBytes(), bytes); AssertJUnit.assertEquals(response.getStatus(),OperationStatus.Success); // Check for the record and data using Async client response = junoAsyncClient.get(key.getBytes()).toBlocking().value(); AssertJUnit.assertEquals(response.getStatus(),OperationStatus.Success); String dataOut = new String(response.getValue()); assert (data.equals(dataOut)); // Update it with Reactor client String data1 = "data is updated by juno react client " + new Date(System.currentTimeMillis()).toString(); response = junoReactClient.update(key.getBytes(),data1.getBytes()).block(); AssertJUnit.assertEquals(response.getStatus(),OperationStatus.Success); //Validate it using the Juno Sync client response = junoClient.get(key.getBytes()); AssertJUnit.assertEquals(response.getStatus(),OperationStatus.Success); dataOut = new String(response.getValue()); assert (data1.equals(dataOut)); //Destroy the Key with Juno Async Client and check it using react Client response = junoAsyncClient.delete(key.getBytes()).toBlocking().value(); AssertJUnit.assertEquals(response.getStatus(),OperationStatus.Success); response = junoReactClient.get(key.getBytes()).block(); AssertJUnit.assertEquals(response.getStatus(),OperationStatus.NoKey); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * */ @Test public void testNoConnectionToServer() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); try{ junoClient6.create(key.getBytes(), bytes); AssertJUnit.assertFalse("Exception not seen for No connection to server Test", false); }catch(JunoException e){ AssertJUnit.assertTrue("testNoConnectionToServer failed",e.getMessage().contains("Connection Error")); //System.out.println(" Exception1 is:"+e.getMessage()); }finally { LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } try{ junoRTimeoutClient.create(key.getBytes(), bytes); AssertJUnit.assertFalse("Exception not seen for No connection to server Test", false); }catch(JunoException e){ AssertJUnit.assertTrue("testNoConnectionToServer failed",e.getMessage().contains("Connection Error")); //System.out.println(" Exception1 is:"+e.getMessage()); }finally { LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } try{ List<JunoRequest> list = new ArrayList<>(); JunoRequest item = new JunoRequest(key.getBytes(), bytes, (long)0, 10, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); junoClient6.doBatch(list); AssertJUnit.assertFalse("Exception not seen for No connection to server Test", false); }catch(JunoException e){ //System.out.println(" Exception2 is:"+e.getMessage()); AssertJUnit.assertTrue("testNoConnectionToServer failed",e.getCause().getMessage().contains("Connection Error")); }finally { LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } try{ List<JunoRequest> list = new ArrayList<>(); JunoRequest item = new JunoRequest(key.getBytes(), bytes, (long)0, 10, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); junoRTimeoutClient.doBatch(list).toIterable(); AssertJUnit.assertFalse("Exception not seen for No connection to server Test", false); }catch(JunoException e){ //System.out.println(" Exception2 is:"+e.getMessage()); AssertJUnit.assertTrue("testNoConnectionToServer failed",e.getCause().getMessage().contains("No Connection to server")); }finally { LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } } /** * This test case tests unicode keys * A complete interop test will be running this test case, then run C++ test * ./test_client.tst --gtest_filter=TestClientCreate.unicodeKeyFromJava * @throws JunoException * @throws IOException */ @Test public void testCreateChineseKeyForCpp() throws JunoException, IOException{ //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = "Q:������������A:���. Q:����� A:������������ Q:�".getBytes(); byte[] data = "Q:���������������������������������������������".getBytes("UTF-8"); //System.out.println ("Destroy the key first"); junoClient.delete(key); junoClient.create(key, data, 6L); JunoResponse junoResponse = junoReactClient.get(key, (long)0).block(); AssertJUnit.assertEquals (OperationStatus.Success,junoResponse.getStatus()); //System.out.println ("Version: " + junoResponse.getVersion()); //System.out.println ("Key: " + junoResponse.key() ); //System.out.println ("Data: " + new String(junoResponse.getValue())); AssertJUnit.assertEquals(1, junoResponse.getVersion()); AssertJUnit.assertEquals(data.length, junoResponse.getValue().length); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); //System.out.println ("\nUpdate key: "); byte[] data1 = "Q:������������������������������������A:���������������������������".getBytes("UTF-8"); long lifetime1 = 12L; JunoResponse junoResponse1 = junoReactClient.update(key, data1, lifetime1).block(); //System.out.println ("New Data1: " + new String(junoResponse.getValue())); //System.out.println ("Version: " + junoResponse1.getVersion()); AssertJUnit.assertEquals(key, junoResponse1.key()); junoResponse1 = junoClient.get(key); AssertJUnit.assertEquals(data1.length, junoResponse1.getValue().length); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); //System.out.println ("\nConditional Update: "); byte[] data2 = "Q:������������������������������������A:���������������������������123".getBytes("UTF-8"); JunoResponse junoResponse2 = junoClient.compareAndSet(junoResponse1.getRecordContext(), data2, (long)6L); //System.out.println ("Version: " + junoResponse2.getVersion()); AssertJUnit.assertEquals(key, junoResponse2.key()); junoResponse2 = junoClient.get(key); AssertJUnit.assertEquals(data2.length, junoResponse2.getValue().length); AssertJUnit.assertEquals(new String(data2), new String(junoResponse2.getValue())); } }
103
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/JunoUSFFactoryMultiClientTest.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 com.paypal.juno.client.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.exception.JunoException; import com.paypal.qa.juno.DataGenUtils; import java.util.Date; import java.util.UUID; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * Test multiple JunoClient implementations being instantiated * into the Spring Bean Context. The config xml references a Commons * Configuration implementation that references a properties * file with more than 1 set of Juno client configuration * properties. */ @ContextConfiguration("classpath:spring-config.xml") @Component public class JunoUSFFactoryMultiClientTest extends AbstractTestNGSpringContextTests { @Inject @Named("junoClient1") JunoClient junoClient1; @Inject @Named("junoClient2") JunoClient junoClient2; @Inject @Named("junoClient3") JunoClient junoClient3; @Inject @Named("junoClnt4") JunoClient junoClient4; @Inject @Named("junoRClient1") JunoReactClient junoRClient1; @Inject @Named("junoRClient3") JunoReactClient junoRClient3; @Inject JunoClient junoClient; private static final Logger LOGGER = LoggerFactory.getLogger(JunoUSFFactoryMultiClientTest.class); @Test public void testJunoClientNotNull() { AssertJUnit.assertNotNull(junoClient1); AssertJUnit.assertNotNull(junoClient2); AssertJUnit.assertNotNull(junoClient3); AssertJUnit.assertNotNull(junoClient4); } //This test has this setting in juno_usf_multiple_configuration.properties //juno.connection.reCycleDuration = 1000 //PASS in 6/29 - only 1 connection is seen @Test public void testCreateKey() throws Exception { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key; for (int i = 0; i < 100; i++) { key = UUID.randomUUID().toString().getBytes(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); JunoResponse response = junoClient1.create(key, bytes); AssertJUnit.assertTrue (response.getStatus().getCode() == OperationStatus.Success.getCode()); // Check for the record response = junoClient2.get(key); AssertJUnit.assertTrue (response.getStatus().getCode() == OperationStatus.Success.getCode()); String dataOut = new String(response.getValue()); //System.out.println ("Data: " + dataOut); assert (data.equals(dataOut)); //Thread.sleep(1500); JunoResponse response2 = junoClient2.get(key); String dataOut2 = new String(response2.getValue()); //System.out.println ("Data: " + dataOut2); assert (data.equals(dataOut2)); //Check log to make sure that recyle happening here JunoResponse response3 = junoClient2.get(key); String dataOut3 = new String(response3.getValue()); //System.out.println ("Data: " + dataOut3); assert (data.equals(dataOut3)); } LOGGER.info("SUCCESS"); } /** * This test has this setting in juno_usf_multiple_configuration.properties * juno.connection.reCycleDuration = 1000 * */ @Test //Due to recycle, make sure 3 connections are created public void testCreateReadUpdateMultClients() throws Exception { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = UUID.randomUUID().toString().getBytes(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); Long lifetime = 10L; JunoResponse response = junoClient1.create(key, bytes,lifetime); // Check for the record from client2 JunoResponse junoResponse = junoClient2.get(key); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(1 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(data), new String(junoResponse.getValue())); String data2 = "New data to store " + new Date(System.currentTimeMillis()).toString(); byte[] bytes2 = data2.getBytes(); lifetime = 12L; junoResponse = junoClient2.update(key, bytes2, lifetime); junoResponse = junoClient1.get(key); AssertJUnit.assertEquals(key, junoResponse.key()); AssertJUnit.assertTrue(2 == junoResponse.getVersion()); AssertJUnit.assertEquals(new String(data2), new String(junoResponse.getValue())); Thread.sleep (15000); String data3 = "Beautiful weather " + new Date(System.currentTimeMillis()).toString(); byte[] bytes3 = data3.getBytes(); try { JunoResponse mResponse = junoClient1.update(key, bytes3); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } LOGGER.info("SUCCESS"); } /** * Client2 creates a key * Client3 which has different namespace reads the key, should get NoKey. * Before the key expires, Client1 invokes CAS to update the key with new data and version * Verify CAS is successfull * Client2 delete the key * Client1 read the key, verify NoKey status is returned * @throws Exception */ @Test public void testCreateCASDestroyMultiClients() throws Exception { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ","id12345"); byte[] key = DataGenUtils.createKey(64).getBytes(); String data = "Test data - happy testing " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); JunoResponse response = junoClient2.create(key, bytes); AssertJUnit.assertEquals (OperationStatus.Success,response.getStatus()); try { JunoResponse mResponse = junoClient3.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } Thread.sleep(8000); String data1 = "Test data - happy Friday " + new Date(System.currentTimeMillis()).toString(); byte[] bytes1 = data1.getBytes(); Long lifetime = 15000L; JunoResponse junoResponse1 = junoClient2.compareAndSet(response.getRecordContext(), bytes1, lifetime); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient2.get(key); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); JunoResponse mResponse = junoClient2.delete (key); AssertJUnit.assertEquals(key, mResponse.key()); AssertJUnit.assertTrue(new String(mResponse.getValue()).equals("")); try { mResponse = junoClient1.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } LOGGER.info("SUCCESS"); } @Test public void testCreateCASDestroyMultiCAndRlients() throws Exception { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); LOGGER.info("CorrID : ","id12345"); byte[] key = DataGenUtils.createKey(64).getBytes(); String data = "Test data - happy testing " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); JunoResponse response = junoRClient1.create(key, bytes).block(); AssertJUnit.assertEquals (OperationStatus.Success,response.getStatus()); JunoResponse mResponse = junoClient1.get(key); AssertJUnit.assertEquals (OperationStatus.Success,mResponse.getStatus()); try { mResponse = junoRClient3.get(key).block(); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } Thread.sleep(8000); String data1 = "Test data - happy Friday " + new Date(System.currentTimeMillis()).toString(); byte[] bytes1 = data1.getBytes(); long lifetime = 15000; JunoResponse junoResponse1 = junoRClient1.compareAndSet(response.getRecordContext(), bytes1, lifetime).block(); AssertJUnit.assertEquals(key, junoResponse1.key()); AssertJUnit.assertTrue(2 == junoResponse1.getVersion()); junoResponse1 = junoClient2.get(key); AssertJUnit.assertEquals(new String(data1), new String(junoResponse1.getValue())); mResponse = junoClient1.delete (key); AssertJUnit.assertEquals(key, mResponse.key()); AssertJUnit.assertTrue(new String(mResponse.getValue()).equals("")); try { mResponse = junoClient2.get(key); AssertJUnit.assertEquals (OperationStatus.NoKey,mResponse.getStatus()); } catch (JunoException mex) { AssertJUnit.assertTrue ("Exception is seen for no key", false); } LOGGER.info("SUCCESS"); } @Test public void testGetKey() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); byte[] key = "mytesting1234".getBytes(); String data = "Test data - happy Friday " + new Date(System.currentTimeMillis()).toString(); byte[] bytes = data.getBytes(); junoClient4.delete(key); JunoResponse response = junoClient4.create(key, bytes); response = junoClient4.get(key); AssertJUnit.assertEquals (OperationStatus.Success,response.getStatus()); response = junoClient.delete(key); AssertJUnit.assertEquals (OperationStatus.Success,response.getStatus()); } // @Test // public void testGetProperties(){ // // AssertJUnit.assertEquals("{juno.server.port=5080, juno.connection.pool_size=3, juno.operation.retry=false, juno.default_record_lifetime_sec=259200, juno.record_namespace=NS1, prefix=, juno.server.host=10.183.38.11, juno.response.timeout_msec=1000, juno.connection.timeout_msec=500, juno.usePayloadCompression=false, juno.connection.byPassLTM=true, juno.application_name=mayflyng}",junoClient.getProperties().toString()); // AssertJUnit.assertEquals("{juno.server.port=5080, juno.connection.pool_size=3, juno.operation.retry=false, juno.default_record_lifetime_sec=259200, juno.record_namespace=NS1, prefix=junoClient1, juno.server.host=10.183.38.11, juno.response.timeout_msec=1000, juno.connection.timeout_msec=500, juno.usePayloadCompression=false, juno.connection.byPassLTM=true, juno.application_name=mayflyng}",junoClient1.getProperties().toString()); // AssertJUnit.assertEquals("{juno.server.port=8080, juno.connection.pool_size=1, juno.operation.retry=false, juno.default_record_lifetime_sec=259200, juno.record_namespace=NS1, prefix=junoClient2, juno.server.host=10.183.38.11, juno.response.timeout_msec=1000, juno.connection.timeout_msec=500, juno.usePayloadCompression=false, juno.connection.byPassLTM=true, juno.application_name=mayflyng}",junoClient2.getProperties().toString()); // AssertJUnit.assertEquals("{juno.server.port=5080, juno.connection.pool_size=1, juno.operation.retry=false, juno.default_record_lifetime_sec=259200, juno.record_namespace=JunoNS1, prefix=junoClient3, juno.server.host=10.183.38.11, juno.response.timeout_msec=1000, juno.connection.timeout_msec=500, juno.usePayloadCompression=false, juno.connection.byPassLTM=true, juno.application_name=mayflyng}",junoClient3.getProperties().toString()); // AssertJUnit.assertEquals("{juno.server.port=5080, juno.connection.pool_size=1, juno.operation.retry=false, juno.default_record_lifetime_sec=259200, juno.record_namespace=NS1, prefix=junoClnt4, juno.server.host=10.183.38.11, juno.response.timeout_msec=1000, juno.connection.timeout_msec=500, juno.usePayloadCompression=false, juno.connection.byPassLTM=true, juno.application_name=mayflyng}",junoClient4.getProperties().toString()); // // } }
104
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/JunoUSFFactoryChildTest.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.JunoReactClient; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import com.paypal.juno.exception.JunoException; import java.io.IOException; import java.util.Date; import java.util.UUID; import org.slf4j.Logger;import com.paypal.juno.client.JunoClient; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * This Class is to test the field and constructor Injection that happens in the base class */ @ContextConfiguration("classpath:spring-config.xml") public class JunoUSFFactoryChildTest extends AbstractTestNGSpringContextTests { private JunoClient junoClientF; private JunoClient junoClientC; private JunoReactClient junoReactClientF; private JunoReactClient junoReactClientC; private Logger LOGGER; @BeforeClass public void setup() throws JunoException, IOException { LOGGER = LoggerFactory.getLogger(JunoUSFFactoryClientTest.class); LOGGER.debug("Read syncFlag test to find out what needs to be run"); ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); JunoUSFFactoryChild child = (JunoUSFFactoryChild) context.getBean("JunoUSFChild"); JunoUSFFactoryRChild rchild = (JunoUSFFactoryRChild) context.getBean("JunoUSFRChild"); junoClientF = child.getFIJunoClient(); junoClientC = child.getCIJunoClient(); junoReactClientF = rchild.getFIJunoReactClient(); junoReactClientC = rchild.getCIJunoReactClient(); } /** * Test the Field injected JunoClient object */ @Test public void testCreateWithFieldInjectedClient() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] payload = data.getBytes(); JunoResponse response = junoClientF.create(key.getBytes(), payload); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); // Check for the record response = junoClientF.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); AssertJUnit.assertEquals(payload, response.getValue()); JunoResponse rresponse = junoReactClientF.create(key.getBytes(), payload).block(); AssertJUnit.assertEquals(OperationStatus.UniqueKeyViolation, rresponse.status()); rresponse = junoReactClientF.get(key.getBytes()).block(); AssertJUnit.assertEquals(OperationStatus.Success, rresponse.status()); AssertJUnit.assertEquals(payload, rresponse.getValue()); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Test the Constructor injected JunoClient object */ @Test public void testCreateWithConstructorInjectedClient() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] payload = data.getBytes(); JunoResponse response = junoClientC.create(key.getBytes(), payload); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); // Check for the record response = junoClientC.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); AssertJUnit.assertEquals(payload, response.getValue()); JunoResponse rresponse = junoReactClientC.create(key.getBytes(), payload).block(); AssertJUnit.assertEquals(OperationStatus.UniqueKeyViolation, rresponse.status()); rresponse = junoReactClientC.get(key.getBytes()).block(); AssertJUnit.assertEquals(OperationStatus.Success, rresponse.status()); AssertJUnit.assertEquals(payload, rresponse.getValue()); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } /** * Test Create with Constructor injected object and Read with Field * injected object. */ @Test public void testCreateWithCIOAndReadWithFIO() { //System.out.println( "\n***TEST CASE: " + new Object(){}.getClass().getEnclosingMethod().getName()); String key = UUID.randomUUID().toString(); String data = "data to store in juno on " + new Date(System.currentTimeMillis()).toString(); byte[] payload = data.getBytes(); JunoResponse response = junoReactClientC.create(key.getBytes(), payload).block(); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); response = junoClientC.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); JunoResponse rresponse = junoClientC.create(key.getBytes(), payload); AssertJUnit.assertEquals(OperationStatus.UniqueKeyViolation, rresponse.status()); rresponse = junoReactClientC.get(key.getBytes()).block(); AssertJUnit.assertEquals(OperationStatus.Success, rresponse.status()); response = junoClientF.get(key.getBytes()); AssertJUnit.assertEquals(OperationStatus.Success, response.status()); AssertJUnit.assertEquals(payload, response.getValue()); rresponse = junoReactClientF.get(key.getBytes()).block(); AssertJUnit.assertEquals(OperationStatus.Success, rresponse.status()); AssertJUnit.assertEquals(payload, rresponse.getValue()); LOGGER.info("SUCCESS"); LOGGER.info("Completed"); } }
105
0
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/main/java/com/paypal/qa
Create_ds/junodb/client/Java/Juno/FunctionalTests/src/main/java/com/paypal/qa/juno/JunoTestClientImpl.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.RecordContext; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import java.util.Map; import javax.net.ssl.SSLContext; public final class JunoTestClientImpl implements JunoClient { private enum syncFlag {sync, rxAsync, ReactAsync}; private JunoClient junoSyncClient; private JunoAsyncClient junoAsyncClient; private JunoReactClient junoReactClient; public JunoTestClientImpl(JunoPropertiesProvider props,SSLContext ctx, int flag) { if (syncFlag.sync.ordinal() == flag) { junoSyncClient = JunoClientFactory.newJunoClient(props,ctx); } else if (syncFlag.rxAsync.ordinal() == flag) { junoAsyncClient = JunoClientFactory.newJunoAsyncClient(props,ctx); } else if (syncFlag.ReactAsync.ordinal() == flag) { junoReactClient = JunoClientFactory.newJunoReactClient(props,ctx); } } @Override public JunoResponse create(byte[] key, byte[] serializedContent) throws JunoException { return create(key, serializedContent, 0); } public JunoResponse create(byte[] key, byte[] serializedContent, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.create(key, serializedContent); } else { return junoReactClient.create(key, serializedContent).block(); } } @Override public JunoResponse create(byte[] key, byte[] serializedContent, long lifetime) throws JunoException { return create(key, serializedContent, lifetime, 0); } public JunoResponse create(byte[] key, byte[] serializedContent, long lifetime, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.create(key, serializedContent, lifetime); } else { return junoReactClient.create(key,serializedContent,lifetime).block(); } } public Iterable<JunoResponse> batchInsert(Iterable<JunoRequest> request) throws JunoException { return null; }; @Override public JunoResponse get(byte[] key) throws JunoException { return get(key, 0); } public JunoResponse get(byte[] key, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.get(key); } else { return junoReactClient.get(key).block(); } } @Override public JunoResponse get(byte[] key, long newLifetime) throws JunoException { return get(key, newLifetime, 0); } public JunoResponse get(byte[] key, long newLifetime, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.get(key, newLifetime); } else { return junoReactClient.get(key,newLifetime).block(); } } public Iterable<JunoResponse> batchGet(Iterable<JunoRequest> request) throws JunoException { return null; } @Override public JunoResponse update(byte[] key, byte[] value) throws JunoException { return update(key, value, 0); } public JunoResponse update(byte[] key, byte[] value, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.update(key,value); } else { return junoReactClient.update(key, value).block(); } } @Override public JunoResponse update(byte[] key, byte[] value, long newLifetime) throws JunoException { return update(key, value, newLifetime, 0); } public JunoResponse update(byte[] key, byte[] value, long newLifetime, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.update(key,value,newLifetime); } else { return junoReactClient.update(key,value,newLifetime).block(); } } public Iterable<JunoResponse> batchUpdate(Iterable<JunoRequest> request) throws JunoException { return null; }; @Override public JunoResponse set(byte[] key, byte[] serializedContent) throws JunoException { return set(key, serializedContent, 0); } public JunoResponse set(byte[] key, byte[] serializedContent, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.set(key, serializedContent); } else { return junoReactClient.set(key,serializedContent).block(); } } @Override public JunoResponse set(byte[] key, byte[] serializedContent, long lifetime) throws JunoException { return set(key, serializedContent, lifetime, 0); } public JunoResponse set(byte[] key, byte[] serializedContent, long lifetime, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.set(key, serializedContent, lifetime); } else { return junoReactClient.set(key,serializedContent,lifetime).block(); } } public Iterable<JunoResponse> batchUpsert(Iterable<JunoRequest> request) throws JunoException{ return null; }; @Override public JunoResponse delete(byte[] key) throws JunoException { return delete(key, 0); } public JunoResponse delete(byte[] key, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.delete(key); } else { return junoReactClient.delete(key).block(); } } public Iterable<JunoResponse> batchDelete(Iterable<byte[]> keys) throws JunoException { return null; }; @Override public JunoResponse compareAndSet(RecordContext rcx, byte[] serializedContent, long lifetime) throws JunoException { return compareAndSet(rcx,serializedContent,lifetime, 0); } public JunoResponse compareAndSet(RecordContext rcx, byte[] serializedContent, long lifetime, int flag) throws JunoException { if (syncFlag.sync.ordinal() == flag) { return junoSyncClient.compareAndSet(rcx,serializedContent,lifetime); } else { return junoReactClient.compareAndSet(rcx,serializedContent,lifetime).block(); } } @Override public Iterable<JunoResponse> doBatch(Iterable<JunoRequest> request) throws JunoException { return null; } @Override public Map<String, String> getProperties() { return null; } }
106
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/net/RequestTest.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.net; import com.paypal.juno.client.io.JunoRequest; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.transport.socket.SocketConfig; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RequestTest { public RequestTest() {} @Before public void initialize() throws Exception { RequestQueue.clear(); } @After public void tearDown() { RequestQueue.clear(); } @Test public void test1ResponseTimeout() { SocketConfig cfg = new SocketConfig(false); cfg.setResponseTimeout(-1); RequestQueue reqQueue = RequestQueue.getInstance(cfg); ConcurrentHashMap<Integer, BlockingQueue<OperationMessage>> respQueueMap = reqQueue.getOpaqueResMap(); BlockingQueue<OperationMessage> respQ = new ArrayBlockingQueue<OperationMessage>(10); respQueueMap.put(10, respQ); for (int i = 0; i < 3; i++) { PingMessage ping = new PingMessage("JunoNetTest_1", 10); reqQueue.enqueue(ping); } try { Thread.sleep(6000); } catch (Exception e) { } assertTrue(reqQueue.isConnected()); assertEquals(respQ.size(), 0); } @Test public void test2Request() { SocketConfig cfg = new SocketConfig(true); RequestQueue reqQueue = RequestQueue.getInstance(cfg); ConcurrentHashMap<Integer, BlockingQueue<OperationMessage>> respQueueMap = reqQueue.getOpaqueResMap(); try { Thread.sleep(5000); } catch (Exception e) { } for (int i = 0; i < 3; i++) { PingMessage ping = new PingMessage("JunoNetTest_2", 0); BlockingQueue<OperationMessage> respQueue = new ArrayBlockingQueue<OperationMessage>(2); respQueueMap.put(0, respQueue); reqQueue.enqueue(ping); } try { Thread.sleep(5000); } catch (Exception e) { } assertTrue(reqQueue.isConnected()); } @Test public void testJunoRequest1() { //Test the API 1 JunoRequest req1 = new JunoRequest("key1".getBytes(), "value1".getBytes(), 0, JunoRequest.OperationType.Create); assertEquals(new String(req1.key()), "key1"); assertEquals(new String(req1.getValue()),"value1"); assertEquals(req1.getVersion(),0); assertEquals(req1.getType(),JunoRequest.OperationType.Create); //Test the API 2 JunoRequest req2 = new JunoRequest("key2".getBytes(), 10,10, JunoRequest.OperationType.Get); assertEquals(new String(req2.key()), "key2"); assertEquals(req2.getVersion(),10); assertEquals(req2.getTimeToLiveSec(),new Long(10)); assertEquals(req2.getType(),JunoRequest.OperationType.Get); assertFalse(req1.equals(req2)); //System.out.println("hash code :"+req2.hashCode()); assertEquals(-247185975,req2.hashCode()); //System.out.println("String value of req1:"+req2.toString()); } }
107
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/net/ShutdownTest.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.net; import com.paypal.juno.transport.socket.SocketConfig; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import static org.junit.Assert.assertTrue; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ShutdownTest { public ShutdownTest() {} @Before public void initialize() throws Exception { RequestQueue.clear(); } @After public void tearDown() { RequestQueue.clear(); } @Test public void testShutdown() { SocketConfig cfg = new SocketConfig(false); RequestQueue reqQueue = RequestQueue.getInstance(cfg); WorkerPool wp = new WorkerPool(cfg, reqQueue); try { Thread.sleep(2000); } catch (Exception e) { } boolean yes = wp.isConnected(); assertTrue(yes); wp.shutdown(); try { Thread.sleep(5000); } catch (Exception e) { } assertTrue(WorkerPool.isQuit()); } }
108
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/net/PingMessageTest.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.net; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class PingMessageTest { public PingMessageTest() {} @Before public void initialize() throws Exception {} @After public void tearDown() {} @Test public void testPingResp() { BaseProcessor processor = new BaseProcessor(); OperationMessage msg = new PingMessage(null, 0); boolean yes = PingMessage.isPingResp(msg, processor); assertEquals(yes, true); // No meta component msg.setMetaComponent(null); yes = PingMessage.isPingResp(msg, processor); assertFalse(yes); // No sourcefield MetaOperationMessage mo = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); msg.setMetaComponent(mo); yes = PingMessage.isPingResp(msg, processor); assertFalse(yes); // app is not JunoInternal byte[] ip = new byte[4]; ip[0] = 115; mo = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); mo.addSourceField(ip, 0, new String("SomeApp").getBytes()); msg.setMetaComponent(mo); yes = PingMessage.isPingResp(msg, processor); assertFalse(yes); // ip is not 4 bytes ip = new byte[3]; ip[0] = 115; mo = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); mo.addSourceField(ip, 0, new String("JunoInternal").getBytes()); msg.setMetaComponent(mo); yes = PingMessage.isPingResp(msg, processor); assertTrue(yes); // ip is a loopback address ip = new byte[4]; ip[0] = 127; mo = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); mo.addSourceField(ip, 0, new String("JunoInternal").getBytes()); msg.setMetaComponent(mo); yes = PingMessage.isPingResp(msg, processor); assertTrue(yes); } }
109
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/net/ResponseTest.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.net; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.client.io.OperationStatus; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class ResponseTest { @Test public void testJunoRequest1() { JunoResponse resp1 = new JunoResponse("key1".getBytes(), "value1".getBytes(), 10, 10, 1649784170, OperationStatus.Success); assertEquals(new String(resp1.key()), "key1"); assertEquals(new String(resp1.getValue()),"value1"); assertEquals(resp1.getVersion(),10); assertEquals(resp1.getTtl(),10); assertEquals(resp1.getCreationTime(),1649784170); assertEquals(resp1.getStatus(),OperationStatus.Success); assertEquals(new String(resp1.getRecordContext().getKey()),"key1"); assertEquals(resp1.getRecordContext().getTtl(),10); assertEquals(resp1.getRecordContext().getVersion(),10); assertEquals(resp1.getRecordContext().getCreationTime(),new Long(1649784170)); assertFalse(resp1.getRecordContext().equals(resp1)); } }
110
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/net/BaseProcessorTest.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.net; import java.net.InetAddress; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; public class BaseProcessorTest { private BaseProcessor p; public BaseProcessorTest() {} @Before public void initialize() throws Exception { p = new BaseProcessor(); } @After public void tearDown() {} @Test public void testUseLTM() { p.useLTM(); assertTrue(true); } @Test public void testPingIp() { String source = ""; String target = ""; for (int i = 0; i < 3; i++) { try { InetAddress ip = p.getPingIp(); if (ip == null) { source = "100.5.0.200"; p.setPingIp(source); continue; } target = ip.toString().substring(1); p.clearPingRespQueue(); break; } catch (Exception e) { continue; } } boolean same = source.equals(target); assertTrue(same); } }
111
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/net/RequestQueueTest.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.net; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClientConfigHolder; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.io.JunoResponse; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.mock.MockJunoUnresponsiveServer; import com.paypal.juno.transport.socket.SocketConfigHolder; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.junit.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import rx.Single; import rx.SingleSubscriber; import static org.junit.Assert.*; @RunWith(MockitoJUnitRunner.Silent.class) public class RequestQueueTest { private RequestQueue unresReqQueue; private boolean recycleEventFired; private boolean connectTimeoutFired; private JunoPropertiesProvider unresJpp; private SocketConfigHolder unresSocCfg; private JunoClientConfigHolder unresClientCfgHldr; private MockJunoUnresponsiveServer mjus; private List<String> responses = new ArrayList<>(); private boolean unfreeze = false, timeoutTriggered = false; private JunoAsyncClient unresClient; private long startTime = System.currentTimeMillis(), endTime = System.currentTimeMillis(); @Before public void initialize() { timeoutTriggered = false; connectTimeoutFired = false; unfreeze = false; responses.clear(); recycleEventFired = false; RequestQueue.clear(); //Unresponsive Server Setup mjus = new MockJunoUnresponsiveServer(15000, false); mjus.start(); // Unresponsive Client Setup URL unresUrl = RequestQueue.class.getClassLoader().getResource("junoUnresponsive.properties"); unresJpp = new JunoPropertiesProvider(unresUrl); unresClientCfgHldr = new JunoClientConfigHolder(unresJpp); unresSocCfg = new SocketConfigHolder(unresClientCfgHldr); unresClient = JunoClientFactory.newJunoAsyncClient(unresUrl); unresReqQueue = RequestQueue.getInstance(unresSocCfg); unresReqQueue.addPropertyChangeListener(evt -> { if(evt.getPropertyName().equals("recycleNow")) { if (timeoutTriggered) { unfreeze = true; endTime = System.currentTimeMillis(); timeoutTriggered = false; } if (unfreeze) mjus.setFreeze(false); recycleEventFired = true; responses.add(evt.getPropertyName()); } if(evt.getPropertyName().equals("RECYCLE_CONNECT_TIMEOUT")) { connectTimeoutFired = true; startTime = System.currentTimeMillis(); timeoutTriggered = true; } }); } @After public void tearDown() { if(mjus != null) { mjus.stop(); mjus.stopMockServer(); } } @Test public void testCheckForUnresponsiveConnection_withOneServerFreeze() { final int[] j = {0}; int i = 0; SingleSubscriber<JunoResponse> getSubscriber = new SingleSubscriber<JunoResponse>() { @Override public void onSuccess(JunoResponse res) { j[0]++;; } @Override public void onError(Throwable e) { } }; long triggerFreeze = 10000; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { //System.out.println("Mock Server Freeze Triggered"); mjus.setFreeze(true); unfreeze = true; } }; timer.schedule(task, triggerFreeze); for(int k = 0; k < 20; k++) { for (i = 0; i < 100; i++) { try { Single<JunoResponse> response = unresClient.get("insertTest".getBytes()); response.subscribe(getSubscriber); try { Thread.sleep(10); // 2 Seconds } catch (Exception e) {} } catch (Exception e) { } } } assertTrue(recycleEventFired); assertTrue(responses.size() > 0); for(String response : responses){ assertEquals("recycleNow", response); } mjus.setFreeze(false); } @Test public void testCheckForUnresponsiveConnection_withFrozenServer() { final int[] j = {0}; int i = 0; SingleSubscriber<JunoResponse> getSubscriber = new SingleSubscriber<JunoResponse>() { @Override public void onSuccess(JunoResponse res) { j[0]++;; } @Override public void onError(Throwable e) { } }; long triggerFreeze = 10000; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { //System.out.println("Mock Server Freeze Triggered"); mjus.setFreeze(true); } }; timer.schedule(task, triggerFreeze); for(int k = 0; k < 20; k++) { for (i = 0; i < 100; i++) { try { Single<JunoResponse> response = unresClient.get("insertTest".getBytes()); response.subscribe(getSubscriber); try { Thread.sleep(10); // 2 Seconds } catch (Exception e) {} } catch (Exception e) { } } } assertTrue(recycleEventFired); assertTrue(responses.size() > 0); for(String response : responses){ assertEquals("recycleNow", response); } mjus.setFreeze(false); } @Test public void testCheckForUnresponsiveConnection_with2ServerFreeze() { final int[] j = {0}; int i = 0; SingleSubscriber<JunoResponse> getSubscriber = new SingleSubscriber<JunoResponse>() { @Override public void onSuccess(JunoResponse res) { j[0]++;; } @Override public void onError(Throwable e) { } }; long triggerFreeze = 10000; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { //System.out.println("Mock Server Freeze Triggered"); mjus.setFreeze(true); } }; timer.schedule(task, triggerFreeze); for(int k = 0; k < 30; k++) { if(responses.size() >= 1) unfreeze = true; for (i = 0; i < 100; i++) { try { Single<JunoResponse> response = unresClient.get("insertTest".getBytes()); response.subscribe(getSubscriber); try { Thread.sleep(10); // 2 Seconds } catch (Exception e) {} } catch (Exception e) { } } } assertTrue(recycleEventFired); assertTrue(responses.size() > 0); for(String response : responses){ assertEquals("recycleNow", response); } mjus.setFreeze(false); } @Test public void testCheckForUnresponsiveConnection_withUnresponsiveServerAndConnectionTimeoutIntervalTriggered() { final int[] j = {0}; int i = 0; SingleSubscriber<JunoResponse> getSubscriber = new SingleSubscriber<JunoResponse>() { @Override public void onSuccess(JunoResponse res) { j[0]++;; } @Override public void onError(Throwable e) { } }; long triggerFreeze = 10000; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { //System.out.println("Mock Server Freeze Triggered"); mjus.setFreeze(true); } }; timer.schedule(task, triggerFreeze); for(int k = 0; k < 200; k++) { for (i = 0; i < 100; i++) { try { Single<JunoResponse> response = unresClient.get("insertTest".getBytes()); response.subscribe(getSubscriber); try { Thread.sleep(10); // 2 Seconds } catch (Exception e) {} } catch (Exception e) { } } } assertTrue(recycleEventFired); assertTrue(responses.size() > 0); assertTrue(connectTimeoutFired); mjus.setFreeze(false); } @Test public void testCheckForUnresponsiveConnection_withNoFailures() throws InterruptedException { final int[] j = {0}; int i = 0; SingleSubscriber<JunoResponse> getSubscriber = new SingleSubscriber<JunoResponse>() { @Override public void onSuccess(JunoResponse res) { j[0]++;; } @Override public void onError(Throwable e) { } }; for(int k = 0; k < 20; k++) { for (i = 0; i < 500; i++) { try { Single<JunoResponse> response = unresClient.get("insertTest".getBytes()); response.subscribe(getSubscriber); } catch (Exception e) { } } try { Thread.sleep(2 * unresSocCfg.getResponseTimeout()); } catch (Exception e) { } } assertEquals(responses.size(), 0); assertFalse(recycleEventFired); } @Test public void testCheckForUnresponsiveConnection_withZeroMessages() throws InterruptedException { for(int i = 0; i < 20; i++){ Thread.sleep(1000); } assertEquals(responses.size(), 0); assertFalse(recycleEventFired); } }
112
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/transport/TransportConfigHolderTest.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.transport; public class TransportConfigHolderTest{ }
113
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/transport
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/transport/socket/SocketConfigHolderTest.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.transport.socket; import com.paypal.juno.client.JunoClientConfigHolder; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.conf.JunoPropertiesProviderTest; import com.paypal.juno.exception.JunoException; import java.net.InetSocketAddress; import java.net.URL; import org.junit.Test; import org.testng.AssertJUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class SocketConfigHolderTest{ URL url = JunoPropertiesProviderTest.class.getClassLoader().getResource("juno.properties"); JunoPropertiesProvider jpp = new JunoPropertiesProvider(url); @Test public void TestSocketConfigHolder(){ try{ JunoClientConfigHolder jch = new JunoClientConfigHolder(jpp); SocketConfigHolder sch = new SocketConfigHolder(jch); assertEquals(sch.getConnectionLifeTime(),5000); InetSocketAddress addr = sch.getInetAddress(); assertNotNull(addr); assertEquals(sch.getConnectTimeout(),1000); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception :"+e.getMessage(), false); } } }
114
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/transport
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/transport/socket/SocketConfig.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.transport.socket; public class SocketConfig extends SocketConfigHolder { public SocketConfig(boolean mode) { host = "localhost"; port = 8080; useSSL = false; connectTimeout = 1000; connectionLifeTime = 10000; connectionPoolSize = 1; responseTimeout = 1000; bypassLTM = mode; } public void setResponseTimeout(int w) { responseTimeout = w; } public void enableSSL() { useSSL = true; } public boolean isTestMode() { return bypassLTM; } }
115
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/mock/MockJunoRecord.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.mock; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicLong; /** * Just a simple class to hold the mayfly records * @author dufox * */ final class MockJunoRecord { public String namespace; public byte[] opaque_data; public long lifetime; public String key; public AtomicLong version = new AtomicLong(0); public long createTime; public int opaque; public ByteBuffer reqId = ByteBuffer.allocate(16); public String compType; }
116
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/mock/MockJunoServer.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.mock; import com.paypal.juno.io.protocol.MessageHeader.MessageRQ; import com.paypal.juno.io.protocol.MessageHeader; import com.paypal.juno.io.protocol.MetaMessageFixedField; import com.paypal.juno.io.protocol.MetaMessageTagAndType.FieldType; import com.paypal.juno.io.protocol.MetaMessageTagAndType; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.io.protocol.PayloadOperationMessage.CompressionType; import com.paypal.juno.io.protocol.PayloadOperationMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Act like a Mayfly20 server * * This server is implemented just well enough to pass our unit tests, and should not be used * to forsake integration testing. * * @author dufox * */ public class MockJunoServer extends Thread { private static final short DATATAG_MAGIC = 0x5050; static private Map<String, Map<String, MockJunoRecord>> myMap = new HashMap<String, Map<String, MockJunoRecord>>(); //final private AtomicLong fakeTimeStamp = new AtomicLong(); //static ServerSocket variable private static ServerSocket server; //socket server port on which it will listen private static int port = 8090; private int socketTimeout; public MockJunoServer(int sockTimeout) { //create the socket server object try { server = new ServerSocket(port); socketTimeout = sockTimeout; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void stopMockServer(){ try { myMap.clear(); server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void run(){ while(true){ //creating socket and waiting for client connection try { Socket socket = server.accept(); processRequest processor = new processRequest(socket,socketTimeout); processor.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class processRequest extends Thread{ Socket socket; int socketSoTimeout; public processRequest(Socket socket,int sockTimeout){ this.socket = socket; socketSoTimeout = sockTimeout; } @Override public void run() { try{ while(socket.isConnected()){ ByteBuf header = Unpooled.buffer(16); ByteBuffer buff = ByteBuffer.allocate(16); if(socketSoTimeout > 0) socket.setSoTimeout(socketSoTimeout); // Read Header first int bytesRead = socket.getInputStream().read(buff.array()); if(bytesRead != 16){ throw new Exception("Header not found"); } header.writeBytes(buff); //Read the Body MessageHeader msgHdr = new MessageHeader(); msgHdr.readBuf(header); ByteBuf body = Unpooled.buffer(msgHdr.getMessageSize() - 16); buff = ByteBuffer.allocate(msgHdr.getMessageSize() - 16); bytesRead = socket.getInputStream().read(buff.array()); if(bytesRead != (msgHdr.getMessageSize() - 16)){ throw new Exception("body not found"); } body.writeBytes(buff); ByteBuffer resp = readAndProcessMessage(msgHdr,body); socket.getOutputStream().write(resp.array()); } } catch(Exception e){ e.printStackTrace(); } } /** * Handle the client request and return a response * * @param bais the input stream containing the serialized the message from the client * @return An input stream containing the serialized response for the client. * @throws Exception */ public ByteBuffer readAndProcessMessage(MessageHeader msgHdr,ByteBuf in) throws Exception { String appName = null; OperationMessage opMsg = new OperationMessage(); opMsg.setHeader(msgHdr); opMsg.readBuf(in); /* opcode list: * 0x00 Nop * 0x01 Create * 0x02 Get * 0x03 Update * 0x04 Set * 0x05 Destroy * 0x81 PrepareCreate * 0x82 Read * 0x83 PrepareUpdate * 0x84 PrepareSet * 0x85 Delete * 0xC1 Commit * 0xC2 Abort (Rollback) * 0xC3 Repair * 0xFE MockSetParam * oxFF MockReSet */ switch (msgHdr.getOpcode()) { case 0: // - No-op break; case 1: // - Create return handleCreate(opMsg); case 2: // - Get return handleGet(opMsg); case 3: // - Update return handleUpdate(opMsg); case 4: // - Set return handleSet(opMsg); case 5: // - Destroy return handleDestory(opMsg); default: break; } return null; } /** * Check to see if the key already exists. * * @param namespace outer key * @param key inner key * @return true if we have both keys in our map, false otherwise */ private boolean keyExists(String namespace, String key) { if (myMap.containsKey(namespace)) { Map<String, MockJunoRecord> innerMap = myMap.get(namespace); if (innerMap.containsKey(key)) { return true; } } return false; } /** * Return our mock record based on the namespace and key. * * @param namespace outer key * @param key inner key * @return the mock record if we have it, otherwise null. */ private MockJunoRecord getRecord(String namespace, String key) { MockJunoRecord mmr = null; if (keyExists(namespace, key)) { Map<String, MockJunoRecord> innerMap = myMap.get(namespace); mmr = innerMap.get(key); } return mmr; } /** * Store the record based on namespace and key. * * @param namespace outer key * @param key inner key * @param mmr the record to store */ private void addRecord(String namespace, String key, MockJunoRecord mmr) { if (!myMap.containsKey(namespace)) { myMap.put(namespace, new HashMap<String, MockJunoRecord>()); } myMap.get(namespace).put(key, mmr); } /** * Remove the record with the given namespace and key. Removing the same * namespace and key twice is safe to do, but the second one has no effect. * @param namespace outer key * @param key inner key */ private void removeRecord(String namespace, String key) { if (keyExists(namespace, key)) { Map<String, MockJunoRecord> innerMap = myMap.get(namespace); innerMap.remove(key); } } /** * Serialize a response to send back to the client * * @param mmheader the header for the message * @param appName the appname of the client * @param mom the operation message * @return The input stream containing the serialized response. * @throws java.io.IOException */ private ByteBuffer serializeResponse(OperationMessage opMsg) throws IOException { ByteBuf buff = Unpooled.buffer(opMsg.getHeader().getMessageSize()); opMsg.writeBuf(buff); ByteBuffer bbuff = buff.nioBuffer(); return bbuff; } /** * Given a mock mayfly record build an operation message for the response * @param mmr * @param status * @return */ private OperationMessage buildMockOperationMessage(MockJunoRecord mmr, int status) { OperationMessage opMsg = new OperationMessage(); MetaOperationMessage metaComponents = new MetaOperationMessage(0L, (byte) 0x2); opMsg.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = opMsg.getMetaComponent().getFieldList(); //Check for version and add int version = (int) mmr.version.get(); if (version != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.Version.ordinal()) | (1 << 5))); field.setContent(version); list.add(field); } // Check for Creation time and add long createTime = mmr.createTime; if (createTime != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.CreationTime.ordinal()) | (1 << 5))); field.setContent(createTime); list.add(field); } MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestHandlingTime.ordinal()) | (1 << 5))); field.setContent(126); list.add(field); field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(mmr.reqId.array()); list.add(field); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)status); msgHdr.setVersion((short)1); msgHdr.setMagic(DATATAG_MAGIC); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(mmr.opaque); PayloadOperationMessage plOpMsg = new PayloadOperationMessage(0L,(byte)0x1); plOpMsg.setKey(mmr.key.getBytes()); plOpMsg.setValue(mmr.opaque_data); plOpMsg.setNamespace(mmr.namespace.getBytes()); plOpMsg.setKeyLength(mmr.key.length()); plOpMsg.setCompressionType(CompressionType.getCompressionType(mmr.compType)); if(mmr.opaque_data != null) plOpMsg.setValueLength(mmr.opaque_data.length); opMsg.setPayloadComponent(plOpMsg); msgHdr.setMessageSize(plOpMsg.getBufferLength()+opMsg.getMetaComponent().getBufferLength()+16); opMsg.setHeader(msgHdr); return opMsg; } /** * Take the message from the client and handle creating a record * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleCreate(OperationMessage msg) throws IOException { OperationMessage op = null; if (!keyExists(new String(msg.getPayloadComponent().getNamespace()), new String(msg.getPayloadComponent().getKey()))) { MockJunoRecord mmr = new MockJunoRecord(); mmr.namespace = new String(msg.getPayloadComponent().getNamespace()); mmr.key = new String(msg.getPayloadComponent().getKey()); if( msg.getPayloadComponent().getValue() != null ) { mmr.compType = msg.getPayloadComponent().getCompressedType().toString(); mmr.opaque_data = msg.getPayloadComponent().getValue().clone(); } mmr.version.incrementAndGet(); //mmr.createTime = fakeTimeStamp.incrementAndGet(); mmr.createTime = msg.getMetaComponent().getCreationTime(); mmr.lifetime = msg.getMetaComponent().getTtl(); mmr.opaque = msg.getHeader().getOpaque(); if(msg.getMetaComponent().getRequestId() != null){ mmr.reqId.put(msg.getMetaComponent().getRequestId()); }else{ //System.out.println("req ID is null....."); } op = buildMockOperationMessage(mmr, 0); addRecord(mmr.namespace, mmr.key, mmr); } else { op = new OperationMessage(); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)4); // Set Duplicate msgHdr.setMagic(DATATAG_MAGIC); //System.out.println("Message header size :"+MessageHeader.size()); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(msg.getHeader().getOpaque()); op.setHeader(msgHdr); //Set the req_id in response MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); op.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = op.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(msg.getMetaComponent().getRequestId()); list.add(field); msgHdr.setMessageSize(MessageHeader.size()+metaComponents.getBufferLength()); } return serializeResponse(op); } /** * Given a message from a client handle getting a mayfly record. * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleGet(OperationMessage opMsg) throws IOException { OperationMessage op = null; MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); //System.out.println("Req ID in mock:"+Hex.encodeHexString(opMsg.getMetaComponent().getRequestId())); op = buildMockOperationMessage(mmr, 0); } else { mmr = new MockJunoRecord(); mmr.key = new String(opMsg.getPayloadComponent().getKey()); mmr.namespace = new String(opMsg.getPayloadComponent().getNamespace()); mmr.createTime = opMsg.getMetaComponent().getCreationTime(); mmr.lifetime = opMsg.getMetaComponent().getTtl(); mmr.opaque = opMsg.getHeader().getOpaque(); mmr.opaque_data = new byte[0]; if(opMsg.getMetaComponent().getRequestId() != null){ mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); }else{ //System.out.println("req ID is null....."); } op = buildMockOperationMessage(mmr, 3); } return serializeResponse(op); } /** * Destroy a mayfly record * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleDestory(OperationMessage opMsg) throws IOException { MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); removeRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); OperationMessage op = null; if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); op = buildMockOperationMessage(mmr, 0); } else { op = new OperationMessage(); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)0); //Set Success msgHdr.setMagic(DATATAG_MAGIC); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(opMsg.getHeader().getOpaque()); op.setHeader(msgHdr); //Set the req_id in response MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); op.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = op.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(opMsg.getMetaComponent().getRequestId()); list.add(field); msgHdr.setMessageSize(MessageHeader.size()+metaComponents.getBufferLength()); } return serializeResponse(op); } /** * Update a mayfly record. * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleUpdate(OperationMessage opMsg) throws IOException { MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); OperationMessage op = null; if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); if (mmr.version.get() == opMsg.getMetaComponent().getVersion() || opMsg.getMetaComponent().getVersion() == 0) { mmr.version.incrementAndGet(); mmr.opaque_data = opMsg.getPayloadComponent().getValue().clone(); op = buildMockOperationMessage(mmr, 0); } else { op = buildMockOperationMessage(mmr, 19); // version too old } }else{ op = new OperationMessage(); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)3); //Set Success msgHdr.setMagic(DATATAG_MAGIC); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(opMsg.getHeader().getOpaque()); op.setHeader(msgHdr); //Set the req_id in response MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); op.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = op.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(opMsg.getMetaComponent().getRequestId()); list.add(field); msgHdr.setMessageSize(MessageHeader.size()+metaComponents.getBufferLength()); } return serializeResponse(op); } /** * Set a mayfly record. * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleSet(OperationMessage opMsg) throws IOException { MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); OperationMessage op = null; if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); mmr.version.incrementAndGet(); mmr.opaque_data = opMsg.getPayloadComponent().getValue().clone(); op = buildMockOperationMessage(mmr, 0); return serializeResponse(op); }else{ return handleCreate(opMsg); } } } }
117
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/mock/MockKey.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.mock; import java.util.Arrays; /** * A simple class that allows us to override the hashcode for * a byte[] type, so we can us it as a key in a map * @author dufox * */ final class MockKey { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(b); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MockKey other = (MockKey) obj; if (!Arrays.equals(b, other.b)) return false; return true; } public byte[] b; public MockKey(byte[] bytes) { this.b = bytes; } }
118
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/mock/MockJunoUnresponsiveServer.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.mock; import com.paypal.juno.io.protocol.MessageHeader.MessageRQ; import com.paypal.juno.io.protocol.MessageHeader; import com.paypal.juno.io.protocol.MetaMessageFixedField; import com.paypal.juno.io.protocol.MetaMessageTagAndType.FieldType; import com.paypal.juno.io.protocol.MetaMessageTagAndType; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.io.protocol.PayloadOperationMessage.CompressionType; import com.paypal.juno.io.protocol.PayloadOperationMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Act like a Mayfly20 server * * This server is implemented just well enough to pass our unit tests, and should not be used * to forsake integration testing. * * */ public class MockJunoUnresponsiveServer extends Thread { private static final short DATATAG_MAGIC = 0x5050; private boolean freeze = false; static private Map<String, Map<String, MockJunoRecord>> myMap = new HashMap<String, Map<String, MockJunoRecord>>(); //final private AtomicLong fakeTimeStamp = new AtomicLong(); //static ServerSocket variable private static ServerSocket server; //socket server port on which it will listen private static int port = 8091; private int socketTimeout; public void setFreeze(boolean freeze){ this.freeze = freeze; } public MockJunoUnresponsiveServer(int sockTimeout, boolean freeze) { this.freeze = freeze; //create the socket server object try { server = new ServerSocket(port); socketTimeout = sockTimeout; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void stopMockServer(){ try { myMap.clear(); server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void run(){ while(true){ //creating socket and waiting for client connection try { Socket socket = server.accept(); processRequest processor = new processRequest(socket,socketTimeout); processor.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class processRequest extends Thread{ Socket socket; int socketSoTimeout; public processRequest(Socket socket,int sockTimeout){ this.socket = socket; socketSoTimeout = sockTimeout; } @Override public void run() { try{ while(socket.isConnected()){ ByteBuf header = Unpooled.buffer(16); ByteBuffer buff = ByteBuffer.allocate(16); if(socketSoTimeout > 0) socket.setSoTimeout(socketSoTimeout); // Read Header first int bytesRead = socket.getInputStream().read(buff.array()); if(bytesRead != 16){ throw new Exception("Header not found"); } header.writeBytes(buff); //Read the Body MessageHeader msgHdr = new MessageHeader(); msgHdr.readBuf(header); ByteBuf body = Unpooled.buffer(msgHdr.getMessageSize() - 16); buff = ByteBuffer.allocate(msgHdr.getMessageSize() - 16); bytesRead = socket.getInputStream().read(buff.array()); if(bytesRead != (msgHdr.getMessageSize() - 16)){ throw new Exception("body not found"); } body.writeBytes(buff); ByteBuffer resp = readAndProcessMessage(msgHdr,body); socket.getOutputStream().write(resp.array()); } } catch(Exception e){ e.printStackTrace(); } } /** * Handle the client request and return a response * * @param in the input stream containing the serialized the message from the client * @return An input stream containing the serialized response for the client. * @throws Exception */ public ByteBuffer readAndProcessMessage(MessageHeader msgHdr,ByteBuf in) throws Exception { String appName = null; OperationMessage opMsg = new OperationMessage(); opMsg.setHeader(msgHdr); opMsg.readBuf(in); /* opcode list: * 0x00 Nop * 0x01 Create * 0x02 Get * 0x03 Update * 0x04 Set * 0x05 Destroy * 0x81 PrepareCreate * 0x82 Read * 0x83 PrepareUpdate * 0x84 PrepareSet * 0x85 Delete * 0xC1 Commit * 0xC2 Abort (Rollback) * 0xC3 Repair * 0xFE MockSetParam * oxFF MockReSet */ if(!freeze) { switch (msgHdr.getOpcode()) { case 0: // - No-op break; case 1: // - Create return handleCreate(opMsg); case 2: // - Get return handleGet(opMsg); case 3: // - Update return handleUpdate(opMsg); case 4: // - Set return handleSet(opMsg); case 5: // - Destroy return handleDestory(opMsg); default: break; } } return null; } /** * Check to see if the key already exists. * * @param namespace outer key * @param key inner key * @return true if we have both keys in our map, false otherwise */ private boolean keyExists(String namespace, String key) { if (myMap.containsKey(namespace)) { Map<String, MockJunoRecord> innerMap = myMap.get(namespace); if (innerMap.containsKey(key)) { return true; } } return false; } /** * Return our mock record based on the namespace and key. * * @param namespace outer key * @param key inner key * @return the mock record if we have it, otherwise null. */ private MockJunoRecord getRecord(String namespace, String key) { MockJunoRecord mmr = null; if (keyExists(namespace, key)) { Map<String, MockJunoRecord> innerMap = myMap.get(namespace); mmr = innerMap.get(key); } return mmr; } /** * Store the record based on namespace and key. * * @param namespace outer key * @param key inner key * @param mmr the record to store */ private void addRecord(String namespace, String key, MockJunoRecord mmr) { if (!myMap.containsKey(namespace)) { myMap.put(namespace, new HashMap<String, MockJunoRecord>()); } myMap.get(namespace).put(key, mmr); } /** * Remove the record with the given namespace and key. Removing the same * namespace and key twice is safe to do, but the second one has no effect. * @param namespace outer key * @param key inner key */ private void removeRecord(String namespace, String key) { if (keyExists(namespace, key)) { Map<String, MockJunoRecord> innerMap = myMap.get(namespace); innerMap.remove(key); } } /** * Serialize a response to send back to the client * * @param opMsg * @return The input stream containing the serialized response. * @throws java.io.IOException */ private ByteBuffer serializeResponse(OperationMessage opMsg) throws IOException { ByteBuf buff = Unpooled.buffer(opMsg.getHeader().getMessageSize()); opMsg.writeBuf(buff); ByteBuffer bbuff = buff.nioBuffer(); return bbuff; } /** * Given a mock mayfly record build an operation message for the response * @param mmr * @param status * @return */ private OperationMessage buildMockOperationMessage(MockJunoRecord mmr, int status) { OperationMessage opMsg = new OperationMessage(); MetaOperationMessage metaComponents = new MetaOperationMessage(0L, (byte) 0x2); opMsg.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = opMsg.getMetaComponent().getFieldList(); //Check for version and add int version = (int) mmr.version.get(); if (version != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.Version.ordinal()) | (1 << 5))); field.setContent(version); list.add(field); } // Check for Creation time and add long createTime = mmr.createTime; if (createTime != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.CreationTime.ordinal()) | (1 << 5))); field.setContent(createTime); list.add(field); } MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestHandlingTime.ordinal()) | (1 << 5))); field.setContent(126); list.add(field); field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(mmr.reqId.array()); list.add(field); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)status); msgHdr.setVersion((short)1); msgHdr.setMagic(DATATAG_MAGIC); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(mmr.opaque); PayloadOperationMessage plOpMsg = new PayloadOperationMessage(0L,(byte)0x1); plOpMsg.setKey(mmr.key.getBytes()); plOpMsg.setValue(mmr.opaque_data); plOpMsg.setNamespace(mmr.namespace.getBytes()); plOpMsg.setKeyLength(mmr.key.length()); plOpMsg.setCompressionType(CompressionType.getCompressionType(mmr.compType)); if(mmr.opaque_data != null) plOpMsg.setValueLength(mmr.opaque_data.length); opMsg.setPayloadComponent(plOpMsg); msgHdr.setMessageSize(plOpMsg.getBufferLength()+opMsg.getMetaComponent().getBufferLength()+16); opMsg.setHeader(msgHdr); return opMsg; } /** * Take the message from the client and handle creating a record * * @param msg * @return * @throws java.io.IOException */ private ByteBuffer handleCreate(OperationMessage msg) throws IOException { OperationMessage op = null; if (!keyExists(new String(msg.getPayloadComponent().getNamespace()), new String(msg.getPayloadComponent().getKey()))) { MockJunoRecord mmr = new MockJunoRecord(); mmr.namespace = new String(msg.getPayloadComponent().getNamespace()); mmr.key = new String(msg.getPayloadComponent().getKey()); if( msg.getPayloadComponent().getValue() != null ) { mmr.compType = msg.getPayloadComponent().getCompressedType().toString(); mmr.opaque_data = msg.getPayloadComponent().getValue().clone(); } mmr.version.incrementAndGet(); //mmr.createTime = fakeTimeStamp.incrementAndGet(); mmr.createTime = msg.getMetaComponent().getCreationTime(); mmr.lifetime = msg.getMetaComponent().getTtl(); mmr.opaque = msg.getHeader().getOpaque(); if(msg.getMetaComponent().getRequestId() != null){ mmr.reqId.put(msg.getMetaComponent().getRequestId()); }else{ //System.out.println("req ID is null....."); } op = buildMockOperationMessage(mmr, 0); addRecord(mmr.namespace, mmr.key, mmr); } else { op = new OperationMessage(); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)4); // Set Duplicate msgHdr.setMagic(DATATAG_MAGIC); //System.out.println("Message header size :"+MessageHeader.size()); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(msg.getHeader().getOpaque()); op.setHeader(msgHdr); //Set the req_id in response MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); op.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = op.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(msg.getMetaComponent().getRequestId()); list.add(field); msgHdr.setMessageSize(MessageHeader.size()+metaComponents.getBufferLength()); } return serializeResponse(op); } /** * Given a message from a client handle getting a mayfly record. * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleGet(OperationMessage opMsg) throws IOException { OperationMessage op = null; MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); //System.out.println("Req ID in mock:"+Hex.encodeHexString(opMsg.getMetaComponent().getRequestId())); op = buildMockOperationMessage(mmr, 0); } else { mmr = new MockJunoRecord(); mmr.key = new String(opMsg.getPayloadComponent().getKey()); mmr.namespace = new String(opMsg.getPayloadComponent().getNamespace()); mmr.createTime = opMsg.getMetaComponent().getCreationTime(); mmr.lifetime = opMsg.getMetaComponent().getTtl(); mmr.opaque = opMsg.getHeader().getOpaque(); mmr.opaque_data = new byte[0]; if(opMsg.getMetaComponent().getRequestId() != null){ mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); }else{ //System.out.println("req ID is null....."); } op = buildMockOperationMessage(mmr, 3); } return serializeResponse(op); } /** * Destroy a mayfly record * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleDestory(OperationMessage opMsg) throws IOException { MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); removeRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); OperationMessage op = null; if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); op = buildMockOperationMessage(mmr, 0); } else { op = new OperationMessage(); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)0); //Set Success msgHdr.setMagic(DATATAG_MAGIC); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(opMsg.getHeader().getOpaque()); op.setHeader(msgHdr); //Set the req_id in response MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); op.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = op.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(opMsg.getMetaComponent().getRequestId()); list.add(field); msgHdr.setMessageSize(MessageHeader.size()+metaComponents.getBufferLength()); } return serializeResponse(op); } /** * Update a mayfly record. * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleUpdate(OperationMessage opMsg) throws IOException { MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); OperationMessage op = null; if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); if (mmr.version.get() == opMsg.getMetaComponent().getVersion() || opMsg.getMetaComponent().getVersion() == 0) { mmr.version.incrementAndGet(); mmr.opaque_data = opMsg.getPayloadComponent().getValue().clone(); op = buildMockOperationMessage(mmr, 0); } else { op = buildMockOperationMessage(mmr, 19); // version too old } }else{ op = new OperationMessage(); MessageHeader msgHdr = new MessageHeader(); msgHdr.setStatus((short)3); //Set Success msgHdr.setMagic(DATATAG_MAGIC); msgHdr.setMessageRQ((short)MessageRQ.Response.ordinal()); msgHdr.setOpaque(opMsg.getHeader().getOpaque()); op.setHeader(msgHdr); //Set the req_id in response MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); op.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = op.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(opMsg.getMetaComponent().getRequestId()); list.add(field); msgHdr.setMessageSize(MessageHeader.size()+metaComponents.getBufferLength()); } return serializeResponse(op); } /** * Set a mayfly record. * * @param opMsg * @return * @throws java.io.IOException */ private ByteBuffer handleSet(OperationMessage opMsg) throws IOException { MockJunoRecord mmr = getRecord(new String(opMsg.getPayloadComponent().getNamespace()),new String(opMsg.getPayloadComponent().getKey())); OperationMessage op = null; if (mmr != null) { mmr.opaque = opMsg.getHeader().getOpaque(); mmr.reqId.clear(); mmr.reqId.put(opMsg.getMetaComponent().getRequestId()); mmr.version.incrementAndGet(); mmr.opaque_data = opMsg.getPayloadComponent().getValue().clone(); op = buildMockOperationMessage(mmr, 0); return serializeResponse(op); }else{ return handleCreate(opMsg); } } } }
119
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/protocol/MetaComponentTest.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.protocol; import com.paypal.juno.io.protocol.MessageHeader.MessageOpcode; import com.paypal.juno.io.protocol.MessageHeader.MessageRQ; import com.paypal.juno.io.protocol.MessageHeader; import com.paypal.juno.io.protocol.MetaMessageFixedField; import com.paypal.juno.io.protocol.MetaMessageTagAndType.FieldType; import com.paypal.juno.io.protocol.MetaMessageTagAndType; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class MetaComponentTest { @Before public void initialize() throws Exception { } @After public void tearDown() { } @Test public void requestHandlingTimeTest() { OperationMessage opMsg = new OperationMessage(); MetaOperationMessage mo = new MetaOperationMessage(0L, (byte) 0x2); opMsg.setMetaComponent(mo); List<MetaMessageTagAndType> list = opMsg.getMetaComponent().getFieldList(); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((FieldType.RequestHandlingTime.ordinal()) | (1 << 5))); long rht = 321; field.setContent(rht); list.add(field); field = new MetaMessageFixedField((byte) ((FieldType.Version.ordinal()) | (1 << 5))); long version = 8; field.setContent(version); list.add(field); field = new MetaMessageFixedField((byte) ((FieldType.CreationTime.ordinal()) | (1 << 5))); field.setContent(101); list.add(field); MessageHeader header = new MessageHeader(); header.setOpcode((short)MessageOpcode.Set.ordinal()); header.setVersion((short)1); header.setMessageRQ((short)MessageRQ.Response.ordinal()); int len = opMsg.getMetaComponent().getBufferLength()+16; header.setMessageSize(len); opMsg.setHeader(header); ByteBuf msg = Unpooled.buffer(len); opMsg.writeBuf(msg); OperationMessage resp = new OperationMessage(); resp.readBuf(msg); assertEquals(resp.getMetaComponent().getRequestHandlingTime(), rht); assertEquals(resp.getMetaComponent().getVersion(), version); } }
120
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/conf/JunoPropertiesProviderTest.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.conf; import java.net.URL; import java.util.Properties; import org.junit.Test; import static org.junit.Assert.assertEquals; public class JunoPropertiesProviderTest{ URL url = JunoPropertiesProviderTest.class.getClassLoader().getResource("juno.properties"); JunoPropertiesProvider jpp = new JunoPropertiesProvider(url); JunoPropertiesProvider jppDefault = new JunoPropertiesProvider(new Properties()); @Test public void TestDefaultValues(){ assertEquals(new Integer(200) ,jppDefault.getConnectionTimeout()); assertEquals(new Long(259200),jppDefault.getDefaultLifetime()); assertEquals(new Integer(1),jppDefault.getConnectionPoolSize()); assertEquals(new Integer(200), jppDefault.getResponseTimeout()); } @Test public void TestValueReadFromPropertiesFile(){ assertEquals(new Integer(1000),jpp.getConnectionTimeout()); assertEquals(new Long(259200),jpp.getDefaultLifetime()); assertEquals("JunoTest",jpp.getAppName()); assertEquals("JunoTest",jpp.getRecordNamespace()); assertEquals("127.0.0.1",jpp.getHost()); assertEquals(new Integer(8090),jpp.getPort()); assertEquals(false,jpp.useSSL()); assertEquals(true,jpp.getOperationRetry()); assertEquals(true,jpp.getByPassLTM()); } @Test public void TestToString(){ //System.out.println("msg1"+jpp.toString()); assertEquals("JunoPropertiesProvider{ connectionTimeoutMS=1000, connectionPoolSize=1, defaultLifetime=259200, maxLifetime=259200, host='127.0.0.1', port='8090', appName='JunoTest, recordNamespace='JunoTest, useSSL = false, usePayloadCompression =true, responseTimeout = 1000, maxConnectionPoolSize=1, maxConnectionLifetime=30000, maxKeySize=128, maxValueSize=204800, maxLifetime=259200, maxNameSpaceLength=64, operationRetry=true, byPassLTM=true, reconnectOnFail=true}",jpp.toString()); } @Test public void TestDefaultToString(){ //System.out.println("msg2"+jppDefault.toString()); assertEquals("JunoPropertiesProvider{ connectionTimeoutMS=200, connectionPoolSize=1, defaultLifetime=259200, maxLifetime=259200, host='', port='0', appName=', recordNamespace=', useSSL = true, usePayloadCompression =false, responseTimeout = 200, maxConnectionPoolSize=1, maxConnectionLifetime=30000, maxKeySize=128, maxValueSize=204800, maxLifetime=259200, maxNameSpaceLength=64, operationRetry=false, byPassLTM=true, reconnectOnFail=false}",jppDefault.toString()); } }
121
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/JunoClientConfigHolderTest.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.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoClientConfigException; import com.paypal.juno.exception.JunoException; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class JunoClientConfigHolderTest { @Before public void initialize() throws Exception { } @After public void tearDown() { } @Test public void NameSpaceSizeTest(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.APP_NAME, "NameSpaceMaxSizeTest"); JunoPropertiesProvider jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Juno configuration value for property, juno.record_namespace cannot be null or empty"); //System.out.println(jce.getMessage()); } prop.setProperty(JunoProperties.RECORD_NAMESPACE, ""); jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Juno configuration value for property, juno.record_namespace cannot be null or empty"); //System.out.println(jce.getMessage()); } prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Namespace length exceeds MAX LENGTH of 64 bytes"); //System.out.println(jce.getMessage()); } } @Test public void AppNameSizeTest(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "AppNameMaxSizeTest"); prop.setProperty(JunoProperties.APP_NAME, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); JunoPropertiesProvider jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals("Application Name length exceeds MAX LENGTH of 32 bytes",jce.getMessage()); //System.out.println(jce.getMessage()); } prop.setProperty(JunoProperties.APP_NAME, ""); jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Juno configuration value for property, juno.application_name cannot be null or empty"); //System.out.println(jce.getMessage()); } } @Test public void ValidateHost(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); JunoPropertiesProvider jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Juno server not configured..."); //System.out.println(jce.getMessage()); } } @Test public void ValidateServerPort(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); prop.setProperty(JunoProperties.HOST, "127.0.0.1"); JunoPropertiesProvider jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Invalid Juno server port..."); //System.out.println(jce.getMessage()); } prop.setProperty(JunoProperties.PORT,"-1"); jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ //System.out.println(jce.getMessage()); assertEquals(jce.getMessage(),"Invalid Juno server port..."); } } @Test public void ValidateSocketConnectionTimout(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); prop.setProperty(JunoProperties.HOST, "127.0.0.1"); prop.setProperty(JunoProperties.PORT, "14368"); prop.setProperty(JunoProperties.CONNECTION_TIMEOUT,""); JunoPropertiesProvider jpp; try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Integer property not valid - Value = "); } prop.setProperty(JunoProperties.CONNECTION_TIMEOUT,"1000"); jpp = new JunoPropertiesProvider(prop); //System.out.println("Message:"+jpp.toString()); assertEquals("JunoPropertiesProvider{ connectionTimeoutMS=1000, connectionPoolSize=1, defaultLifetime=259200, maxLifetime=259200, host='127.0.0.1', port='14368', appName='ValidateAppNameTest, recordNamespace='abcdefghijklmnopqrstuvwxyzabc, useSSL = true, usePayloadCompression =false, responseTimeout = 200, maxConnectionPoolSize=1, maxConnectionLifetime=30000, maxKeySize=128, maxValueSize=204800, maxLifetime=259200, maxNameSpaceLength=64, operationRetry=false, byPassLTM=true, reconnectOnFail=false}",jpp.toString()); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); clientCfgHldr.getConnectionTimeoutMsecs(); }catch(JunoClientConfigException jce){ // We should not be here. As it would use the default send buffer size i.e 0. fail("ValidateSocketConnectionTimout failed for value 1001. Execption:"+jce.getMessage()); //System.out.println(jce.getMessage()); } prop.setProperty(JunoProperties.CONNECTION_TIMEOUT,"-1"); jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); clientCfgHldr.getConnectionTimeoutMsecs(); }catch(JunoClientConfigException jce){ //System.out.println("Exception :"+jce.getMessage()); assertEquals(jce.getMessage(),"Juno configuration value for property juno.connection.timeout_msec cannot be less than 1"); } prop.setProperty(JunoProperties.CONNECTION_TIMEOUT,"10000"); jpp = new JunoPropertiesProvider(prop); try{ JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); clientCfgHldr.getConnectionTimeoutMsecs(); }catch(JunoClientConfigException jce){ //System.out.println("Exception :"+jce.getMessage()); assertEquals(jce.getMessage(),"Juno configuration value for property juno.connection.timeout_msec cannot be greater than 5000"); } } @Test public void ValidateConnectionLifeTime(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); prop.setProperty(JunoProperties.HOST, "127.0.0.1"); prop.setProperty(JunoProperties.PORT, "14368"); prop.setProperty(JunoProperties.CONNECTION_LIFETIME,"0"); JunoPropertiesProvider jpp; try{ jpp = new JunoPropertiesProvider(prop); JunoClientConfigHolder clientCfgHldr = new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ //System.out.println("Exception :"+jce.getMessage()); assertEquals(jce.getMessage(),"Juno configuration value for property juno.connection.recycle_duration_msec cannot be less than 5000"); } } @Test public void ValidateMaxConnectionPoolSize(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); prop.setProperty(JunoProperties.HOST, "127.0.0.1"); prop.setProperty(JunoProperties.PORT, "14368"); prop.setProperty(JunoProperties.CONNECTION_TIMEOUT,"1000"); prop.setProperty(JunoProperties.CONNECTION_POOL_SIZE,"0"); JunoPropertiesProvider jpp; try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoException e){ assertTrue(e instanceof JunoClientConfigException); assertEquals(e.getMessage(),"Juno configuration value for property juno.connection.pool_size cannot be less than 1"); } prop.setProperty(JunoProperties.CONNECTION_POOL_SIZE,"100"); try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoException e){ assertTrue(e instanceof JunoClientConfigException); assertEquals("Juno configuration value for property juno.connection.pool_size cannot be greater than 3",e.getMessage()); } } @Test public void ValidateResponseTimeout(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); prop.setProperty(JunoProperties.HOST, "127.0.0.1"); prop.setProperty(JunoProperties.PORT, "14368"); prop.setProperty(JunoProperties.RESPONSE_TIMEOUT,"0"); JunoPropertiesProvider jpp; try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoException e){ assertTrue(e instanceof JunoClientConfigException); //System.out.println("msg1 :"+e.getMessage()); assertEquals(e.getMessage(),"Juno configuration value for property juno.response.timeout_msec cannot be less than 1"); } prop.setProperty(JunoProperties.RESPONSE_TIMEOUT,"10000"); try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoException e){ assertTrue(e instanceof JunoClientConfigException); //System.out.println("msg2 :"+e.getMessage()); assertEquals(e.getMessage(),"Juno configuration value for property juno.response.timeout_msec cannot be greater than 5000"); } } @Test public void ValidateTTL(){ Properties prop = new Properties(); prop.setProperty(JunoProperties.RECORD_NAMESPACE, "abcdefghijklmnopqrstuvwxyzabc"); prop.setProperty(JunoProperties.APP_NAME, "ValidateAppNameTest"); prop.setProperty(JunoProperties.HOST, "127.0.0.1"); prop.setProperty(JunoProperties.PORT, "14368"); prop.setProperty(JunoProperties.RESPONSE_TIMEOUT,"0"); prop.setProperty(JunoProperties.DEFAULT_LIFETIME,"-1"); JunoPropertiesProvider jpp; try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoException e){ assertTrue(e instanceof JunoClientConfigException); assertEquals(e.getMessage(),"Juno configuration value for property juno.default_record_lifetime_sec cannot be less than 1"); } prop.setProperty(JunoProperties.DEFAULT_LIFETIME,"999999"); try{ jpp = new JunoPropertiesProvider(prop); new JunoClientConfigHolder(jpp); }catch(JunoClientConfigException jce){ assertEquals(jce.getMessage(),"Juno configuration value for property juno.default_record_lifetime_sec cannot be greater than 259200"); } } }
122
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/JunoMultiClientTest.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 javax.inject.Inject; import javax.inject.Named; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.junit.Assert.*; /** * Test multiple JunoClient implementations being instanatiated * into the Spring Bean Context. The config xml references a Commons * Configuration implemetnation that references a properties * file with more than 1 set of Juno client configuration * properties. */ //@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring-config-multi-client.xml") //@ContextConfiguration(locations= {"/spring-config-multi-client.xml"}) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Component public class JunoMultiClientTest extends AbstractJUnit4SpringContextTests{ @Inject JunoClient junoClnt; @Inject JunoClient junoClnt1; @Inject @Named("junoClient2") JunoClient junoClnt2; @Inject @Named("junoClient3") JunoAsyncClient junoAsyncClient3; @Inject JunoAsyncClient junoAsyncClient; @BeforeClass public static void initialize() throws Exception { System.setProperty("keymaker.test.appname","Juno-UnitTest"); //DO nothing } @AfterClass public static void tearDown() { Thread.currentThread().getThreadGroup().interrupt(); } @Test public void testJunoSyncClientNotNull() { assertNotNull(junoClnt); assertNotNull(junoClnt1); assertNotNull(junoClnt2); try{ junoClnt2.create("Joseph".getBytes(), "Antony".getBytes()); }catch(Exception e){ //System.out.println("Exception123 :"+e.getMessage()); assertTrue("testJunoSyncClientNotNull test failed",e.getMessage().contains("Connection Error")); } } @Test public void testJunoAsyncClientNotNull() { assertNotNull(junoAsyncClient3); assertNotNull(junoAsyncClient); try{ junoAsyncClient3.create("Joseph".getBytes(), "Antony".getBytes()).toBlocking().value(); }catch(Exception e){ //System.out.println("Exception :"+e.getMessage()); assertTrue("testJunoAsyncClientNotNull test failed",e.getMessage().contains("Connection Error")); } } @Test public void testConstructorTest(){ JunoClient junoClnt = ConstuctorTest.getObject1(); assertNotNull(junoClnt); JunoClient junoClnt1 = ConstuctorTest.getObject2(); assertNotNull(junoClnt1); } @Component public static class ConstuctorTest { private static JunoClient junoClnt; private static JunoClient junoClnt1; public ConstuctorTest(@Named("junoClient2")JunoClient junoCl,@Named("junoClient4")JunoClient junoCl1){ junoClnt = junoCl; junoClnt1 = junoCl1; } public static JunoClient getObject1(){ return junoClnt; } public static JunoClient getObject2(){ return junoClnt1; } } }
123
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/impl/JunoReactClientImplTest.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.impl; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientConfigHolder; 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.client.io.RecordContext; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.io.protocol.JunoMessage.OperationType; import com.paypal.juno.io.protocol.JunoMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.mock.MockJunoServer; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.JunoClientUtil; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.testng.AssertJUnit; import reactor.core.publisher.Mono; import static org.junit.Assert.*; @RunWith(PowerMockRunner.class) public class JunoReactClientImplTest { private JunoClientConfigHolder clientCfgHldr; private JunoReactClient client; private Method methodValidate; private Method methodCreateOpMsg; private Method methodDecodeOpMsg; private JunoPropertiesProvider jpp; private SocketConfigHolder socCfg; private static MockJunoServer mjs; public String longKey = new String("InsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegative"); /** * Initialize tests */ @Before public void initialize() throws Exception { URL url = JunoClientImpl.class.getClassLoader().getResource("juno.properties"); jpp = new JunoPropertiesProvider(url); clientCfgHldr = new JunoClientConfigHolder(jpp); socCfg = new SocketConfigHolder(clientCfgHldr); //client = PowerMockito.spy(new JunoAsyncClientImpl(clientCfgHldr)); methodValidate = JunoClientUtil.class.getDeclaredMethod("validateInput", JunoRequest.class,OperationType.class, JunoClientConfigHolder.class); methodValidate.setAccessible(true); //Start the Mock server mjs = new MockJunoServer(15000); mjs.start(); client = JunoClientFactory.newJunoReactClient(url); } @After public void tearDown() { clientCfgHldr = null; if(mjs != null) { mjs.stop(); mjs.stopMockServer(); } } public static String generateRandomChars(String candidateChars, int length) { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { sb.append(candidateChars.charAt(random.nextInt(candidateChars .length()))); } return sb.toString(); } @Test public void insertTest() { JunoResponse resp = client.create("insertTest".getBytes(), "Antony".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.create("insertTest".getBytes(), "Antony".getBytes()).block(); assertEquals(OperationStatus.UniqueKeyViolation,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for UniqueKeyViolation", false); } } @Test public void insertTest_withTTL() { JunoResponse resp = client.create("insertTest".getBytes(), "Antony".getBytes(),20).block(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.create("insertTest".getBytes(), "Antony".getBytes(),30).block(); assertEquals(OperationStatus.UniqueKeyViolation,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for UniqueKeyViolation", false); } } @Test public void GetTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("GetTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.get("GetTest".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.get("GetTest1".getBytes()).block(); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for NoKey", false); } } @Test public void OpaqueResMapClearTest(){ JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("OpaqueResMapClearTest".getBytes(), "Test".getBytes(),20); ConcurrentHashMap<Integer, BlockingQueue<OperationMessage>> trial = null; for(int i =0; i< 100; i++){ Mono<JunoResponse> response = client.get("OpaqueResMapClearTest".getBytes()); response.subscribe(res -> { assertEquals(OperationStatus.Success,res.getStatus()); }, error -> { assertEquals(OperationStatus.InternalError.getErrorText(), error.getMessage()); }); } Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for(Thread thread : threadSet){ if(thread.getName().contains("boundedElastic")){ thread.interrupt(); } } try{ Thread.sleep(3000); Field opaqueResMapField = client.getClass().getDeclaredField("opaqueResMap"); opaqueResMapField.setAccessible(true); trial = (ConcurrentHashMap) opaqueResMapField.get(client); assertEquals(0, trial.size()); }catch(Exception e){ AssertJUnit.assertTrue("Exception for getDeclaredField or Sleep", false); } } @Test public void GetTest_withTTL() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("GetTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.get("GetTest_withTTL".getBytes(),20).block(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.get("GetTest_withTTL1".getBytes(),10).block(); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for NoKey", false); } } @Test public void UpdateTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpdateTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.update("UpdateTest".getBytes(),"Updated".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); //Try to updated a record which is not present in DB try{ resp = client.update("UpdateTest1".getBytes(),"Updated".getBytes()).block(); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for NoKey", false); } } @Test public void CompateAndSetTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); JunoResponse resp=jclient.create("CompateAndSetTest".getBytes(), "Antony".getBytes(),20); //System.out.println("The response version is:"+resp.getRecordContext().getVersion()); resp = client.compareAndSet(resp.getRecordContext(),"Updated".getBytes(),20).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); RecordContext rctx = new RecordContext(resp.key(),1,resp.getCreationTime(),resp.getTtl()); //Try to updated a record with a lower version try{ resp = client.compareAndSet(rctx,"Updated".getBytes(),20).block(); assertEquals(OperationStatus.ConditionViolation,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for VersionMismatch", false); } } @Test public void UpdateTest_withTTL() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpdateTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.update("UpdateTest_withTTL".getBytes(),"Updated".getBytes(),20).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); } @Test public void UpsertTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpsertTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.set("UpsertTest".getBytes(),"Updated".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); resp = client.set("UpsertTest1".getBytes(),"Created".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Created",(new String(resp.getValue()))); assertEquals(1,resp.getVersion()); } @Test public void UpsertTest_withTTL() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpsertTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.set("UpsertTest_withTTL".getBytes(),"Updated".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); resp = client.set("UpsertTest_withTTL1".getBytes(),"Created".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Created",(new String(resp.getValue()))); assertEquals(1,resp.getVersion()); } @Test public void DestroyTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("DestroyTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.delete("DestroyTest".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); // try to destroy a record which is not present in DB. try{ resp = client.delete("DestroyTest1".getBytes()).block(); assertEquals(OperationStatus.Success,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for Destroy", false); } } @Test public void CreateNegativeTest() { try{ client.create("".getBytes(), "InsertNegativeValue".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.create(longKey.getBytes(),"".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ // byte[] array = new byte[804900]; // length is bounded by String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; String payload = generateRandomChars(candidateChars,204900); client.create("Test".getBytes(),payload.getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for large Payload", false); }catch(JunoException e){ //System.out.println("Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be larger than 204800 bytes. Current value size=204900"); } try{ client.create("".getBytes(), "InsertNegativeValue".getBytes(),10).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ //System.out.println("Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.create("InsertNegative".getBytes(), "InsertNegativeValue".getBytes(),0).block(); AssertJUnit.assertTrue ("Exception not seen for 0 TTL", false); }catch(JunoException e){ // //System.out.println("Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be 0 or negative."); } } @Test public void GetNegativeTest(){ try{ client.get("".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e) { //System.out.println("get Error is:" + e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document key must not be null or empty"); } try{ client.get(longKey.getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.get("".getBytes(),200).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e) { //System.out.println("get Error is:" + e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document key must not be null or empty"); } try{ client.get("getNegative".getBytes(),900000000).block(); }catch(JunoException e){ //System.out.println("get Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"Invalid lifetime. current lifetime=900000000, max configured lifetime=259200"); } } @Test public void UpdateNegativeTest() { try{ client.update("UpdateNegative".getBytes(), "UpdateNegativeValue".getBytes(),-1).block(); AssertJUnit.assertTrue ("Exception not seen for negative TTL", false); }catch(JunoException e){ //System.out.println("update1 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be negative. Current lifetime=-1"); } try{ client.update("".getBytes(), "UpdateNegativeValue".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ //System.out.println("update2 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.update(longKey.getBytes(),"".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.update("UpdateNegative".getBytes(), new String(new char[204900]).replace('\0', 'a').getBytes()).block(); }catch(JunoException e){ //System.out.println("update3 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be larger than 204800 bytes. Current value size=204900"); } try{ client.update("".getBytes(), "UpdateNegativeValue".getBytes(),10).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ //System.out.println("update4 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.update("UpdateNegative".getBytes(), new String(new char[204900]).replace('\0', 'a').getBytes(),0).block(); }catch(JunoException e) { //System.out.println("update5 Error is:" + e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document Value must not be larger than 204800 bytes. Current value size=204900"); } } @Test public void SetNegativeTest() { try{ JunoResponse res = client.set("SetNegative".getBytes(), "".getBytes()).block(); assertEquals(OperationStatus.Success,res.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception seen for empty paylaod"+e, false); } try{ client.set("".getBytes(), "".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.set(longKey.getBytes(),"".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ JunoResponse res = client.set("".getBytes(), "".getBytes(),10).block(); assertEquals(OperationStatus.Success,res.getStatus()); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.set(longKey.getBytes(),"".getBytes(),10).block(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.set("SetNegative".getBytes(), "SetNegativeValue".getBytes(),-1).block(); }catch(JunoException e) { assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document's TTL cannot be negative. Current lifetime=-1"); } } @Test public void CompareAndSetNegativeTest() { try{ RecordContext rctx = new RecordContext("Test".getBytes(),1,100,100); JunoResponse res = client.compareAndSet(rctx, "CompareAndSetKeyNotInDb".getBytes(),1200).block(); assertEquals(OperationStatus.NoKey,res.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for no key", false); } try{ RecordContext rctx = new RecordContext(longKey.getBytes(),1,100,100); client.compareAndSet(rctx, "CompareAndSetKeyNotInDb".getBytes(),1200).block(); AssertJUnit.assertTrue ("Exception not seen for Long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.compareAndSet(null, "CompareAndSetKeyNotInDb".getBytes(),1200).block(); AssertJUnit.assertTrue ("Exception not seen for null ctx", false); }catch(JunoException e){ //System.out.println("Error :"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"Record Context cannot be null"); } try{ RecordContext rctx = new RecordContext("".getBytes(),1,100,100); client.compareAndSet(rctx, "CompareAndSetKeyNotInDb".getBytes(),1200).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ RecordContext rctx = new RecordContext("Test".getBytes(),1,100,100); client.compareAndSet(rctx, "CompareAndSetNegativeValue".getBytes(),-1).block(); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be negative. Current lifetime=-1"); } } @Test public void DestroyNegativeTest() { try{ client.delete("DeleteNegative".getBytes()).block(); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for deletion for nokey in db", false); } try{ client.delete("".getBytes()).block(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.delete(longKey.getBytes()).block(); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } } @Test public void doBatchNegativeTest(){ try{ List<JunoRequest> list = null; client.doBatch(list); AssertJUnit.assertTrue ("Exception not seen for null request list", false); }catch(JunoException e){ //System.out.println("Error1 :"+e.getCause().getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"Request argument is null"); } try{ List<JunoRequest> list = new ArrayList<>(); client.doBatch(list); AssertJUnit.assertTrue ("Exception not seen for empty request list", false); }catch(JunoException e){ //System.out.println("Error2 :"+e.getCause().getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"Empty request list supplied"); } try{ List<JunoRequest> list = new ArrayList<>(); JunoRequest item = new JunoRequest(longKey.getBytes(), "Test".getBytes(), (long)0, 180, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); Iterable<JunoResponse> batchResp = client.doBatch(list).toIterable(); for (JunoResponse mResponse: batchResp) { //System.out.println("Resp :"+mResponse.getStatus().getErrorText()); assertEquals(OperationStatus.IllegalArgument,mResponse.getStatus()); } }catch(JunoException e){ //System.out.println("Exceprtion:"+e.getMessage()); assertEquals(OperationStatus.InternalError.getErrorText(),e.getMessage()); } try{ byte[][] key = new byte[5000][]; byte[][] payload = new byte[5000][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < 5000; i ++) { key[i] = ("Test"+i).getBytes(); payload[i] = "test_payload".getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, 180, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } //System.out.println("Calling do batch"); client.doBatch(list).toIterable(); //AssertJUnit.assertTrue ("Exception not seen for empty request list", false); }catch(JunoException e){ //System.out.println("Error4 :"+e.getCause().getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"Empty request list supplied"); } } @Test public void createAndDecodeOperationMessage() { try{ String key = "TestKey"; String value = "TestValue"; long version = 0; long timeToLiveSec = 200; JunoMessage msg = new JunoMessage(key.getBytes(),value.getBytes(),version,0,timeToLiveSec,OperationType.Create); OperationMessage opMsg = (OperationMessage) methodCreateOpMsg.invoke(client,msg,InetAddress.getLocalHost(),8080); assertNotNull(opMsg); JunoMessage junoMsg = (JunoMessage) methodDecodeOpMsg.invoke(client,opMsg,key.getBytes()); assertNotNull(junoMsg); }catch(InvocationTargetException e){ e.printStackTrace(); assertNotNull(e); }catch(Exception e){ } try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = 200; JunoMessage msg = new JunoMessage(key.getBytes(),value.getBytes(),version,0,timeToLiveSec,OperationType.Update); OperationMessage opMsg = (OperationMessage) methodCreateOpMsg.invoke(client,msg,InetAddress.getLocalHost(),8080); assertNotNull(opMsg); JunoMessage junoMsg = (JunoMessage) methodDecodeOpMsg.invoke(client,opMsg,key.getBytes()); assertNotNull(junoMsg); }catch(InvocationTargetException e){ e.printStackTrace(); assertNotNull(e); }catch(Exception e){ } } @Test public void validateInputPositiveInsert(){ try{ // Happy Path validation -- Insert try{ String key = "TestKey"; String value = "TestValue"; long version = 0; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(JunoException e){ //We shouldn't be here assertNotNull(e); } }catch(Exception e){ } } @Test public void validateInputPayload(){ try{ // Positive case - Empty Payload try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ //We shouldn't be here assertFalse(true); } // Negative case - null Payload try{ String key = "TestKey"; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),null,version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ //We shouldn't be here assertFalse(true); } // Negative case - Max Payload try{ String key = "TestKey"; String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; String payload = generateRandomChars(candidateChars,204801); long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),payload.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNull(msg); }catch(Exception e){ //We should be here assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be larger than 204800 bytes. Current value size=204801"); } }catch(Exception e){ //We shouldn't be here assertFalse(true); } } @Test public void validateInputEmptyPayload(){ try{ //Negative case - Empty Payload for CheckAndSet try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Set); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Update,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } //Negative case - Empty Payload for Update try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Update); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Update,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } //Negative case - Empty Payload for upsert try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Set); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Set,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } //Negative case - Empty Payload for CompareAndSet try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Update); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.CompareAndSet,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputEmptyPayload"); } } @Test public void validateInputEmptyKey(){ try{ // Negative case - Empty key try{ String key = ""; String value = "TestValue"; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } }catch(Exception e){ } } @Test public void validateInputMaxKeySize(){ try{ // Negative case - Max key Size try{ String key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String value = "TestValue"; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputMaxKeySize"); } } @Test public void validateInputMaxTTL(){ try{ //Negative case - Max TTL try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = 259201; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"Invalid lifetime. current lifetime=259201, max configured lifetime=259200"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputMaxTTL"); } } @Test public void validateInput0TTLL(){ try{ //Negative case - 0 TTL try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = 0; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be 0 or negative."); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInput0TTLL"); } } @Test public void validateInputNegativeTTL(){ try{ //Negative case - Negative TTL try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = -1; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create, clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be negative. Current lifetime=-1"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputNegativeTTL"); } } @Test public void validateInputNegativeVersion(){ try{ //Negative case - negative version # try{ String key = "TestKey"; String value = "TestValue"; long version = -1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Update); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.CompareAndSet,clientCfgHldr); //assertNotNull(msg); assertFalse(true); // We should not be here }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document version cannot be less than 1. Current version=-1"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputNegativeVersion"); } } }
124
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/impl/JunoConnectionTest.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.impl; 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.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.mock.MockJunoServer; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testng.AssertJUnit; import static org.junit.Assert.assertEquals; public class JunoConnectionTest { private static MockJunoServer mjs; private JunoPropertiesProvider jpp; /** * Initialize tests */ @Before public void initialize() throws Exception { URL url = JunoClientImpl.class.getClassLoader().getResource("juno.properties"); jpp = new JunoPropertiesProvider(url); } @After public void tearDown() { mjs.stop(); mjs.stopMockServer(); } @Test public void ConnectionTerminationTest() { //Make the socket timeout very less so that the mockserver will //close the connection as soon as it is made mjs = new MockJunoServer(1); mjs.start(); JunoClient client = JunoClientFactory.newJunoClient(jpp); try{ client.create("insertTest1".getBytes(), "Antony".getBytes(),40); AssertJUnit.assertTrue ("Exception not seen for No connection", false); }catch(JunoException e){ //System.out.println("Exception:"+e.getMessage()); assertEquals(e.getMessage(), "Response Timed out"); } } @Test public void ConnectionTerminationBatchTest() { //Make the socket timeout very less so that the mockserver will //close the connection as soon as it is made mjs = new MockJunoServer(1); mjs.start(); JunoClient client = JunoClientFactory.newJunoClient(jpp); try{ List<JunoRequest> jReqList = new ArrayList<JunoRequest>(); jReqList.add(new JunoRequest("insert1".getBytes(),"Test1".getBytes(),0,5,JunoRequest.OperationType.Create)); jReqList.add(new JunoRequest("insert2".getBytes(),"Test2".getBytes(),0,5,JunoRequest.OperationType.Create)); jReqList.add(new JunoRequest("insert3".getBytes(),"Test3".getBytes(),0,5,JunoRequest.OperationType.Create)); Iterable<JunoResponse> jResp = client.doBatch(jReqList); for(JunoResponse jr : jResp){ assertEquals(OperationStatus.ResponseTimeout,jr.getStatus()); } Thread.sleep(1000); //assertEquals(resp.getStatus(),); }catch(JunoException e){ //System.out.println("==============================Exception:"+e.getMessage()); assertEquals(e.getMessage(), "Response Timed out"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
125
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/impl/JunoClientImplTest.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.impl; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientConfigHolder; 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.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.mock.MockJunoServer; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.*; @PowerMockIgnore("javax.management.*") @RunWith(PowerMockRunner.class) public class JunoClientImplTest { private JunoClientConfigHolder clientCfgHldr; private JunoPropertiesProvider jpp; private static MockJunoServer mjs; /** * Initialize tests */ @BeforeClass public static void init() throws Exception { } @AfterClass public static void close() throws Exception { Thread.sleep(2000); } @Before public void initialize() throws Exception { URL url = JunoClientImpl.class.getClassLoader().getResource("juno.properties"); jpp = new JunoPropertiesProvider(url); clientCfgHldr = new JunoClientConfigHolder(jpp); //Start the Mock server mjs = new MockJunoServer(15000); mjs.start(); } @After public void tearDown() { clientCfgHldr = null; mjs.stop(); mjs.stopMockServer(); } @Test public void insertTest() { URL url = JunoClientImpl.class.getClassLoader().getResource("juno.properties"); JunoClient client = JunoClientFactory.newJunoClient(url); JunoResponse resp = client.create("insertTest".getBytes(), "Antony".getBytes()); assertEquals(OperationStatus.Success, resp.getStatus()); try{ resp = client.create("insertTest".getBytes(), "Antony".getBytes()); assertEquals(OperationStatus.UniqueKeyViolation, resp.getStatus()); }catch(JunoException e){ assertTrue("Exception is seen for duplicate key", false); } } @Test public void compressTest() throws IOException { URL url = JunoClientImpl.class.getClassLoader().getResource("juno.properties"); Properties pConfig = new Properties(); pConfig.load(url.openStream()); pConfig.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "true"); JunoClient client1 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig)); pConfig.setProperty(JunoProperties.USE_PAYLOADCOMPRESSION, "false"); JunoClient client2 = JunoClientFactory.newJunoClient(new JunoPropertiesProvider(pConfig)); byte [] value = 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(); JunoResponse resp = client1.create("compressTest1".getBytes(), value); //Create with compression enabled assertEquals(OperationStatus.Success, resp.getStatus()); resp = client2.get("compressTest1".getBytes()); // Read with compression disabled assertEquals(OperationStatus.Success, resp.getStatus()); // //System.out.println("Create:"+String.format("%x", new BigInteger(1,value))); // //System.out.println("Get:"+String.format("%x", new BigInteger(1,resp.getValue()))); assertTrue(Arrays.equals(value, resp.getValue())); resp = client2.create("compressTest2".getBytes(),value); // Create with compression disabled assertEquals(OperationStatus.Success, resp.getStatus()); resp = client1.get("compressTest2".getBytes()); //Read with compression enabled assertEquals(OperationStatus.Success, resp.getStatus()); assertTrue(Arrays.equals(value, resp.getValue())); //System.out.println("Test with uncompressable data."); //Compression on uncompressable data - Check the CAL log for result byte [] value1 = DataGenUtils.genBytes(1025); resp = client1.create("compressTest3".getBytes(), value1); assertEquals(OperationStatus.Success, resp.getStatus()); } @Test public void insertTest_withTTL() { JunoClient client = JunoClientFactory.newJunoClient(jpp); JunoResponse resp = client.create("insertTest".getBytes(), "Antony".getBytes(),20); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.create("insertTest".getBytes(), "Antony".getBytes(),30); assertEquals(OperationStatus.UniqueKeyViolation,resp.getStatus()); }catch(JunoException e){ assertTrue("Exception is seen for duplicate key", false); } } @Test public void GetTest() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("GetTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.get("GetTest".getBytes()); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.get("GetTest1".getBytes()); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ assertTrue("Exception is seen for no key", false); } } @Test public void GetTest_withTTL() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("GetTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.get("GetTest_withTTL".getBytes(),20); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.get("GetTest_withTTL1".getBytes(),10); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ assertTrue("Exception is seen for no key", false); } } @Test public void UpdateTest() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("UpdateTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.update("UpdateTest".getBytes(),"Updated".getBytes()); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); //Try to updated a record which is not present in DB try{ resp = client.update("UpdateTest1".getBytes(),"Updated".getBytes()); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ assertTrue("Exception is seen for no key", false); } } @Test public void CompateAndSetTest() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); JunoResponse resp = client.create("CompateAndSetTest".getBytes(), "Antony".getBytes(),20); resp = client.compareAndSet(resp.getRecordContext(),"Updated".getBytes(),20); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); RecordContext rctx = new RecordContext(resp.key(),1,resp.getCreationTime(),resp.getTtl()); //Try to updated a record with a lower version try{ resp = client.compareAndSet(rctx,"Updated".getBytes(),20); assertEquals(OperationStatus.ConditionViolation,resp.getStatus()); assertFalse(resp.getRecordContext().equals(rctx)); assertFalse(resp.getRecordContext().hashCode() == rctx.hashCode()); RecordContext rc = new RecordContext(resp.getRecordContext().getKey(),resp.getRecordContext().getVersion(),resp.getRecordContext().getCreationTime(),resp.getRecordContext().getTtl()); assertTrue(rc.equals(resp.getRecordContext())); }catch(JunoException e){ assertTrue("Exception is seen for no key", false); } } @Test public void UpdateTest_withTTL() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("UpdateTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.update("UpdateTest_withTTL".getBytes(),"Updated".getBytes(),20); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); } @Test public void UpsertTest() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("UpsertTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.set("UpsertTest".getBytes(),"Updated".getBytes()); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); resp = client.set("UpsertTest1".getBytes(),"Created".getBytes()); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Created",(new String(resp.getValue()))); assertEquals(1,resp.getVersion()); } @Test public void UpsertTest_withTTL() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("UpsertTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.set("UpsertTest_withTTL".getBytes(),"Updated".getBytes(),20); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); JunoResponse resp1 = client.set("UpsertTest_withTTL1".getBytes(),"Created".getBytes(),20); assertFalse(resp.equals(resp1)); assertFalse(resp.hashCode() == resp1.hashCode()); assertFalse(resp.toString().equals(resp1.toString())); assertEquals(OperationStatus.Success,resp1.getStatus()); assertEquals("Created",(new String(resp1.getValue()))); assertEquals(1,resp1.getVersion()); } @Test public void DestroyTest() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); client.create("DestroyTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.delete("DestroyTest".getBytes()); assertEquals(OperationStatus.Success,resp.getStatus()); // try to destroy a record which is not present in DB. resp = client.delete("DestroyTest1".getBytes()); assertEquals(OperationStatus.Success,resp.getStatus()); } @Test public void BatchNegativeTest() { try{ JunoClient client = new JunoClientImpl(clientCfgHldr,null); List<JunoRequest> jReqList = new ArrayList<JunoRequest>(); jReqList.add(new JunoRequest("insert1".getBytes(),"Test1".getBytes(),0,0,JunoRequest.OperationType.Create)); jReqList.add(new JunoRequest("insert2".getBytes(),"Test2".getBytes(),0,5,JunoRequest.OperationType.Create)); jReqList.add(new JunoRequest("insert3".getBytes(),"Test3".getBytes(),0,5,JunoRequest.OperationType.Create)); Iterable<JunoResponse> jResp = client.doBatch(jReqList); for(JunoResponse jr : jResp){ if((new String(jr.getKey())).equals("insert1")){ assertEquals(OperationStatus.IllegalArgument,jr.getStatus()); }else{ assertEquals(OperationStatus.Success,jr.getStatus()); } } }catch(Exception e){ //e.printStackTrace(); //assertEquals(e.getMessage(),"Illegal argument"); //assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be 0 or negative."); } } @Test public void BatchPositiveTest() { JunoClient client = new JunoClientImpl(clientCfgHldr,null); List<JunoRequest> jReqList = new ArrayList<JunoRequest>(); jReqList.add(new JunoRequest("insert1".getBytes(),"Test1".getBytes(),0,5,JunoRequest.OperationType.Create)); jReqList.add(new JunoRequest("insert2".getBytes(),"Test2".getBytes(),0,5,JunoRequest.OperationType.Create)); jReqList.add(new JunoRequest("insert3".getBytes(),"Test3".getBytes(),0,5,JunoRequest.OperationType.Create)); JunoRequest jreq1 = jReqList.get(0); Iterable<JunoResponse> jResp = client.doBatch(jReqList); for(JunoResponse jr : jResp){ assertEquals(OperationStatus.Success,jr.getStatus()); } jReqList.clear(); jReqList.add(new JunoRequest("insert1".getBytes(),"".getBytes(),0,5,JunoRequest.OperationType.Get)); jReqList.add(new JunoRequest("insert2".getBytes(),"Test4".getBytes(),0,5,JunoRequest.OperationType.Update)); jReqList.add(new JunoRequest("insert3".getBytes(),"Test5".getBytes(),0,5,JunoRequest.OperationType.Update)); JunoRequest jreq2 = jReqList.get(0); assertFalse(jreq1.equals(jreq2)); assertFalse(jreq1.hashCode() == jreq2.hashCode()); assertFalse(jreq1.toString().equals(jreq2.toString())); Iterable<JunoResponse> resp = client.doBatch(jReqList); for(JunoResponse response : resp){ assertEquals(OperationStatus.Success,response.getStatus()); } jReqList.remove(2); jReqList.add(new JunoRequest("insert3".getBytes(),"Test6".getBytes(),0,5,JunoRequest.OperationType.Set)); jReqList.add(new JunoRequest("insert4".getBytes(),"Test7".getBytes(),0,5,JunoRequest.OperationType.Set)); jReqList.add(new JunoRequest("insert5".getBytes(),"Test8".getBytes(),0,5,JunoRequest.OperationType.Set)); jReqList.add(new JunoRequest("insert6".getBytes(),"Test9".getBytes(),0,5,JunoRequest.OperationType.Set)); resp = client.doBatch(jReqList); for(JunoResponse response : resp){ assertEquals(OperationStatus.Success,response.getStatus()); } List<JunoRequest> jReq = new ArrayList<JunoRequest>(); jReq.add(new JunoRequest("insert1".getBytes(),null,0,0,JunoRequest.OperationType.Destroy)); jReq.add(new JunoRequest("insert2".getBytes(),null,0,0,JunoRequest.OperationType.Destroy)); resp = client.doBatch(jReq); for(JunoResponse response : resp){ assertEquals(OperationStatus.Success,response.getStatus()); } jReqList.clear(); jReqList.add(new JunoRequest("insert1".getBytes(),null,0,0,JunoRequest.OperationType.Get)); jReqList.add(new JunoRequest("insert2".getBytes(),null,0,0,JunoRequest.OperationType.Get)); jReqList.add(new JunoRequest("insert3".getBytes(),null,0,0,JunoRequest.OperationType.Get)); resp = client.doBatch(jReqList); for(JunoResponse response : resp){ if(Arrays.equals(response.getKey(),"insert1".getBytes()) || Arrays.equals(response.getKey(),"insert2".getBytes())){ assertEquals(OperationStatus.NoKey,response.getStatus()); }else{ assertEquals(OperationStatus.Success,response.getStatus()); } } } @Test public void ConnectionRecycleTest() { JunoClient client = JunoClientFactory.newJunoClient(jpp); JunoResponse resp = client.create("insertTest1".getBytes(), "Antony".getBytes(),40); assertEquals(resp.getStatus(), OperationStatus.Success); //Sleep engough for connection to recycle try { Thread.sleep(15000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } resp = client.get("insertTest1".getBytes()); assertEquals(resp.getStatus(), OperationStatus.Success); } }
126
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/impl/JunoAsyncClientImplTest.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.impl; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientConfigHolder; 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.client.io.RecordContext; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import com.paypal.juno.io.protocol.JunoMessage.OperationType; import com.paypal.juno.io.protocol.JunoMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.mock.MockJunoServer; import com.paypal.juno.mock.MockJunoUnresponsiveServer; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.JunoClientUtil; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import rx.Single; import rx.SingleSubscriber; import static org.junit.Assert.*; @RunWith(PowerMockRunner.class) public class JunoAsyncClientImplTest { private JunoClientConfigHolder clientCfgHldr; private JunoAsyncClient client; private Method methodValidate; private Method methodCreateOpMsg; private Method methodDecodeOpMsg; private JunoPropertiesProvider jpp; private SocketConfigHolder socCfg; private JunoResponse jres; private static MockJunoServer mjs; private static MockJunoUnresponsiveServer mjus; public String longKey = new String("InsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegativeInsertNegative"); private static Logger LOGGER; /** * Initialize tests */ @Before public void initialize() throws Exception { LOGGER = LoggerFactory.getLogger(JunoAsyncClientImplTest.class); URL url = JunoClientImpl.class.getClassLoader().getResource("juno.properties"); jpp = new JunoPropertiesProvider(url); clientCfgHldr = new JunoClientConfigHolder(jpp); socCfg = new SocketConfigHolder(clientCfgHldr); //client = PowerMockito.spy(new JunoAsyncClientImpl(clientCfgHldr)); methodValidate = JunoClientUtil.class.getDeclaredMethod("validateInput", JunoRequest.class,OperationType.class, JunoClientConfigHolder.class); methodValidate.setAccessible(true); //Start the Mock server mjs = new MockJunoServer(15000); mjus = new MockJunoUnresponsiveServer(15000, true); mjs.start(); mjus.start(); client = JunoClientFactory.newJunoAsyncClient(url); } @After public void tearDown() { clientCfgHldr = null; if(mjs != null) { mjs.stop(); mjs.stopMockServer(); } if(mjus != null) { mjus.stop(); mjus.stopMockServer(); } } public static String generateRandomChars(String candidateChars, int length) { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { sb.append(candidateChars.charAt(random.nextInt(candidateChars .length()))); } return sb.toString(); } @Test public void insertTest() { jres = client.create("insertTest".getBytes(), "Antony".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,jres.getStatus()); try{ jres = client.create("insertTest".getBytes(), "Antony".getBytes()).toBlocking().value(); assertEquals(OperationStatus.UniqueKeyViolation,jres.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for UniqueKeyViolation", false); } } @Test public void insertTest_withTTL() { JunoResponse resp = client.create("insertTest".getBytes(), "Antony".getBytes(),20).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.create("insertTest".getBytes(), "Antony".getBytes(),30).toBlocking().value(); assertEquals(OperationStatus.UniqueKeyViolation,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for UniqueKeyViolation", false); } } @Test public void GetTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("GetTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.get("GetTest".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.get("GetTest1".getBytes()).toBlocking().value(); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for NoKey", false); } } @Test public void OpaqueResMapClearTest(){ JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("OpaqueResMapClearTest".getBytes(), "Test".getBytes(),20); URL url = JunoClientImpl.class.getClassLoader().getResource("junoUnresponsive.properties"); JunoAsyncClient unresClient = JunoClientFactory.newJunoAsyncClient(url); ConcurrentHashMap<Integer, BlockingQueue<OperationMessage>> trial = null; SingleSubscriber<JunoResponse> getSubscriber = new SingleSubscriber<JunoResponse>() { @Override public void onSuccess(JunoResponse res) { assertEquals(OperationStatus.Success,res.getStatus()); } @Override public void onError(Throwable e) { assertEquals(OperationStatus.InternalError.getErrorText(), e.getMessage()); } }; for(int i =0; i< 100; i++){ Single<JunoResponse> response = unresClient.get("OpaqueResMapClearTest".getBytes()); response.subscribe(getSubscriber); } Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for(Thread thread : threadSet){ if(thread.getName().contains("RxIoScheduler")){ thread.interrupt(); } } try{ Thread.sleep(3000); Field opaqueResMapField = unresClient.getClass().getDeclaredField("opaqueResMap"); opaqueResMapField.setAccessible(true); trial = (ConcurrentHashMap) opaqueResMapField.get(unresClient); assertEquals(0, trial.size()); }catch(Exception e){ AssertJUnit.assertTrue("Exception for getDeclaredField or Sleep", false); } } @Test public void GetTest_withTTL() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("GetTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.get("GetTest_withTTL".getBytes(),20).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); try{ resp = client.get("GetTest_withTTL1".getBytes(),10).toBlocking().value(); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for NoKey", false); } } @Test public void UpdateTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpdateTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.update("UpdateTest".getBytes(),"Updated".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); //Try to updated a record which is not present in DB try{ resp = client.update("UpdateTest1".getBytes(),"Updated".getBytes()).toBlocking().value(); assertEquals(OperationStatus.NoKey,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for NoKey", false); } } @Test public void CompateAndSetTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); JunoResponse resp=jclient.create("CompateAndSetTest".getBytes(), "Antony".getBytes(),20); //System.out.println("The response version is:"+resp.getRecordContext().getVersion()); resp = client.compareAndSet(resp.getRecordContext(),"Updated".getBytes(),20).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); RecordContext rctx = new RecordContext(resp.key(),1,resp.getCreationTime(),resp.getTtl()); //Try to updated a record with a lower version try{ resp = client.compareAndSet(rctx,"Updated".getBytes(),20).toBlocking().value(); assertEquals(OperationStatus.ConditionViolation,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for VersionMismatch", false); } } @Test public void UpdateTest_withTTL() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpdateTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.update("UpdateTest_withTTL".getBytes(),"Updated".getBytes(),20).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); } @Test public void UpsertTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpsertTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.set("UpsertTest".getBytes(),"Updated".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); resp = client.set("UpsertTest1".getBytes(),"Created".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Created",(new String(resp.getValue()))); assertEquals(1,resp.getVersion()); } @Test public void UpsertTest_withTTL() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("UpsertTest_withTTL".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.set("UpsertTest_withTTL".getBytes(),"Updated".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Updated",(new String(resp.getValue()))); assertEquals(2,resp.getVersion()); resp = client.set("UpsertTest_withTTL1".getBytes(),"Created".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); assertEquals("Created",(new String(resp.getValue()))); assertEquals(1,resp.getVersion()); } @Test public void DestroyTest() { JunoClient jclient = new JunoClientImpl(clientCfgHldr,null); jclient.create("DestroyTest".getBytes(), "Antony".getBytes(),20); JunoResponse resp = client.delete("DestroyTest".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); // try to destroy a record which is not present in DB. try{ resp = client.delete("DestroyTest1".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,resp.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for Destroy", false); } } @Test public void CreateNegativeTest() { try{ client.create("".getBytes(), "InsertNegativeValue".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.create(longKey.getBytes(),"".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ // byte[] array = new byte[804900]; // length is bounded by String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; String payload = generateRandomChars(candidateChars,204900); client.create("Test".getBytes(),payload.getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for large Payload", false); }catch(JunoException e){ //System.out.println("Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be larger than 204800 bytes. Current value size=204900"); } try{ client.create("".getBytes(), "InsertNegativeValue".getBytes(),10).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ //System.out.println("Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.create("InsertNegative".getBytes(), "InsertNegativeValue".getBytes(),0).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for 0 TTL", false); }catch(JunoException e){ // //System.out.println("Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be 0 or negative."); } } @Test public void GetNegativeTest(){ try{ client.get("".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e) { //System.out.println("get Error is:" + e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document key must not be null or empty"); } try{ client.get(longKey.getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.get("".getBytes(),200).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e) { //System.out.println("get Error is:" + e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document key must not be null or empty"); } try{ client.get("getNegative".getBytes(),900000000).toBlocking().value(); }catch(JunoException e){ //System.out.println("get Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"Invalid lifetime. current lifetime=900000000, max configured lifetime=259200"); } } @Test public void UpdateNegativeTest() { try{ client.update("UpdateNegative".getBytes(), "UpdateNegativeValue".getBytes(),-1).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for negative TTL", false); }catch(JunoException e){ //System.out.println("update1 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be negative. Current lifetime=-1"); } try{ client.update("".getBytes(), "UpdateNegativeValue".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ //System.out.println("update2 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.update(longKey.getBytes(),"".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.update("UpdateNegative".getBytes(), new String(new char[204900]).replace('\0', 'a').getBytes()).toBlocking().value(); }catch(JunoException e){ //System.out.println("update3 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be larger than 204800 bytes. Current value size=204900"); } try{ client.update("".getBytes(), "UpdateNegativeValue".getBytes(),10).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ //System.out.println("update4 Error is:"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.update("UpdateNegative".getBytes(), new String(new char[204900]).replace('\0', 'a').getBytes(),0).toBlocking().value(); }catch(JunoException e) { //System.out.println("update5 Error is:" + e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document Value must not be larger than 204800 bytes. Current value size=204900"); } } @Test public void SetNegativeTest() { try{ JunoResponse res = client.set("SetNegative".getBytes(), "".getBytes()).toBlocking().value(); assertEquals(OperationStatus.Success,res.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception seen for empty paylaod"+e, false); } try{ client.set("".getBytes(), "".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.set(longKey.getBytes(),"".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ JunoResponse res = client.set("".getBytes(), "".getBytes(),10).toBlocking().value(); assertEquals(OperationStatus.Success,res.getStatus()); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.set(longKey.getBytes(),"".getBytes(),10).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.set("SetNegative".getBytes(), "SetNegativeValue".getBytes(),-1).toBlocking().value(); }catch(JunoException e) { assertEquals(OperationStatus.IllegalArgument.getErrorText(), e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(), "The Document's TTL cannot be negative. Current lifetime=-1"); } } @Test public void CompareAndSetNegativeTest() { try{ RecordContext rctx = new RecordContext("Test".getBytes(),1,100,100); JunoResponse res = client.compareAndSet(rctx, "CompareAndSetKeyNotInDb".getBytes(),1200).toBlocking().value(); assertEquals(OperationStatus.NoKey,res.getStatus()); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for no key", false); } try{ RecordContext rctx = new RecordContext(longKey.getBytes(),1,100,100); client.compareAndSet(rctx, "CompareAndSetKeyNotInDb".getBytes(),1200).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for Long key", false); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } try{ client.compareAndSet(null, "CompareAndSetKeyNotInDb".getBytes(),1200).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for null ctx", false); }catch(JunoException e){ //System.out.println("Error :"+e.getCause().getMessage()); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"Record Context cannot be null"); } try{ RecordContext rctx = new RecordContext("".getBytes(),1,100,100); client.compareAndSet(rctx, "CompareAndSetKeyNotInDb".getBytes(),1200).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ RecordContext rctx = new RecordContext("Test".getBytes(),1,100,100); client.compareAndSet(rctx, "CompareAndSetNegativeValue".getBytes(),-1).toBlocking().value(); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be negative. Current lifetime=-1"); } } @Test public void DestroyNegativeTest() { try{ client.delete("DeleteNegative".getBytes()).toBlocking().value(); }catch(JunoException e){ AssertJUnit.assertTrue ("Exception for deletion for nokey in db", false); } try{ client.delete("".getBytes()).toBlocking().value(); AssertJUnit.assertTrue ("Exception not seen for empty key", false); }catch(JunoException e){ assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } try{ client.delete(longKey.getBytes()).toBlocking().value(); }catch(JunoException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } } @Test public void doBatchNegativeTest(){ try{ List<JunoRequest> list = null; client.doBatch(list).toBlocking(); AssertJUnit.assertTrue ("Exception not seen for null request list", false); }catch(JunoException e){ //System.out.println("Error1 :"+e.getCause().getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"Request argument is null"); } try{ List<JunoRequest> list = new ArrayList<>(); client.doBatch(list).toBlocking(); AssertJUnit.assertTrue ("Exception not seen for empty request list", false); }catch(JunoException e){ //System.out.println("Error2 :"+e.getCause().getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"Empty request list supplied"); } try{ List<JunoRequest> list = new ArrayList<>(); JunoRequest item = new JunoRequest(longKey.getBytes(), "Test".getBytes(), (long)0, 180, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); Iterable<JunoResponse> batchResp = client.doBatch(list).toBlocking().toIterable(); for (JunoResponse mResponse: batchResp) { //System.out.println("Resp :"+mResponse.getStatus().getErrorText()); assertEquals(OperationStatus.IllegalArgument,mResponse.getStatus()); } }catch(JunoException e){ //System.out.println("Exceprtion:"+e.getMessage()); assertEquals(OperationStatus.InternalError.getErrorText(),e.getMessage()); } try{ byte[][] key = new byte[5000][]; byte[][] payload = new byte[5000][]; List<JunoRequest> list = new ArrayList<>(); for (int i = 0; i < 5000; i ++) { key[i] = ("Test"+i).getBytes(); payload[i] = "test_payload".getBytes(); JunoRequest item = new JunoRequest(key[i], payload[i], (long)0, 180, System.currentTimeMillis(), JunoRequest.OperationType.Create); list.add(item); } //System.out.println("Calling do batch"); client.doBatch(list).toBlocking().toIterable(); //AssertJUnit.assertTrue ("Exception not seen for empty request list", false); }catch(JunoException e){ //System.out.println("Error4 :"+e.getCause().getMessage()); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(OperationStatus.IllegalArgument.getErrorText(),e.getMessage()); assertEquals(e.getCause().getMessage(),"Empty request list supplied"); } } @Test public void createAndDecodeOperationMessage() { try{ String key = "TestKey"; String value = "TestValue"; long version = 0; long timeToLiveSec = 200; JunoMessage msg = new JunoMessage(key.getBytes(),value.getBytes(),version,0,timeToLiveSec,OperationType.Create); OperationMessage opMsg = (OperationMessage) methodCreateOpMsg.invoke(client,msg,InetAddress.getLocalHost(),8080); assertNotNull(opMsg); JunoMessage junoMsg = (JunoMessage) methodDecodeOpMsg.invoke(client,opMsg,key.getBytes()); assertNotNull(junoMsg); }catch(InvocationTargetException e){ e.printStackTrace(); assertNotNull(e); }catch(Exception e){ } try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = 200; JunoMessage msg = new JunoMessage(key.getBytes(),value.getBytes(),version,0,timeToLiveSec,OperationType.Update); OperationMessage opMsg = (OperationMessage) methodCreateOpMsg.invoke(client,msg,InetAddress.getLocalHost(),8080); assertNotNull(opMsg); JunoMessage junoMsg = (JunoMessage) methodDecodeOpMsg.invoke(client,opMsg,key.getBytes()); assertNotNull(junoMsg); }catch(InvocationTargetException e){ e.printStackTrace(); assertNotNull(e); }catch(Exception e){ } } @Test public void validateInputPositiveInsert(){ try{ // Happy Path validation -- Insert try{ String key = "TestKey"; String value = "TestValue"; long version = 0; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(JunoException e){ //We shouldn't be here assertNotNull(e); } }catch(Exception e){ } } @Test public void validateInputPayload(){ try{ // Positive case - Empty Payload try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ //We shouldn't be here assertFalse(true); } // Negative case - null Payload try{ String key = "TestKey"; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),null,version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ //We shouldn't be here assertFalse(true); } // Negative case - Max Payload try{ String key = "TestKey"; String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; String payload = generateRandomChars(candidateChars,204801); long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),payload.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNull(msg); }catch(Exception e){ //We should be here assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be larger than 204800 bytes. Current value size=204801"); } }catch(Exception e){ //We shouldn't be here assertFalse(true); } } @Test public void validateInputEmptyPayload(){ try{ //Negative case - Empty Payload for CheckAndSet try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Set); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Update,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } //Negative case - Empty Payload for Update try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Update); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Update,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } //Negative case - Empty Payload for upsert try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Set); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Set,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } //Negative case - Empty Payload for CompareAndSet try{ String key = "TestKey"; String value = ""; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Update); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.CompareAndSet,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document Value must not be empty."); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputEmptyPayload"); } } @Test public void validateInputEmptyKey(){ try{ // Negative case - Empty key try{ String key = ""; String value = "TestValue"; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be null or empty"); } }catch(Exception e){ } } @Test public void validateInputMaxKeySize(){ try{ // Negative case - Max key Size try{ String key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String value = "TestValue"; long version = 1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(Exception e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document key must not be larger than 128 bytes"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputMaxKeySize"); } } @Test public void validateInputMaxTTL(){ try{ //Negative case - Max TTL try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = 259201; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"Invalid lifetime. current lifetime=259201, max configured lifetime=259200"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputMaxTTL"); } } @Test public void validateInput0TTLL(){ try{ //Negative case - 0 TTL try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = 0; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create,clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be 0 or negative."); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInput0TTLL"); } } @Test public void validateInputNegativeTTL(){ try{ //Negative case - Negative TTL try{ String key = "TestKey"; String value = "TestValue"; long version = 1; long timeToLiveSec = -1; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Create); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.Create, clientCfgHldr); assertNotNull(msg); }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document's TTL cannot be negative. Current lifetime=-1"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputNegativeTTL"); } } @Test public void validateInputNegativeVersion(){ try{ //Negative case - negative version # try{ String key = "TestKey"; String value = "TestValue"; long version = -1; long timeToLiveSec = 200; JunoRequest req = new JunoRequest(key.getBytes(),value.getBytes(),version,timeToLiveSec,JunoRequest.OperationType.Update); JunoMessage msg = (JunoMessage) methodValidate.invoke(client,req,OperationType.CompareAndSet,clientCfgHldr); //assertNotNull(msg); assertFalse(true); // We should not be here }catch(InvocationTargetException e){ assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals(e.getCause().getMessage(),"The Document version cannot be less than 1. Current version=-1"); } }catch(Exception e){ //System.out.println("Error invoking validateInput : validateInputNegativeVersion"); } } }
127
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/test/java/com/paypal/juno/client/impl/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.juno.client.impl; 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; } }
128
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/JunoClientBeanFactoryPostProcessor.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; 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.conf.JunoPropertiesProvider; import com.paypal.juno.exception.JunoException; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionValidationException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.stereotype.Component; @Component public class JunoClientBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private Logger logger = LoggerFactory.getLogger(JunoClientBeanFactoryPostProcessor.class); private List<Class<?>> junoClients = new ArrayList<>(Arrays.asList(JunoClient.class, JunoAsyncClient.class, JunoReactClient.class)); @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException { // Find the Configuration bean Configuration config = factory.getBean(Configuration.class); JunoPropertiesProvider provider; List<String> qualifiedBeanList = new ArrayList<>(); List<String> nonQualifiedBeanList= new ArrayList<>(); //Scan Juno Client injection points, create bean and register it for (Class<?> junoClass: junoClients) { qualifiedBeanList.clear(); nonQualifiedBeanList.clear(); registerBean(factory,config,qualifiedBeanList,nonQualifiedBeanList,junoClass); } } /** * */ private void registerBean(ConfigurableListableBeanFactory factory,Configuration config, List<String> qualifiedBeanList, List<String> nonQualifiedBeanList, Class<?> junoClass){ JunoPropertiesProvider provider; locateInjectionPoints(factory,qualifiedBeanList,nonQualifiedBeanList,junoClass); // create all beans required for each named injection point for (String qualifiedBean : qualifiedBeanList) { provider = getJunoPropertiesProvider(qualifiedBean, config); provider.setConfig(config); if(logger.isDebugEnabled()){ String msg = String.format("Configuring %s for @Named(%s) with the following properties: %s",junoClass.getName(),qualifiedBean,provider.toString()); logger.debug(msg); } Object junoClient = createJunoBean(provider,junoClass); ((DefaultListableBeanFactory)factory).registerSingleton(qualifiedBean, junoClient); } //Create a single bean for rest of all non qualified beans if(!nonQualifiedBeanList.isEmpty()){ //For non qualified bean just create one object and add provider = getJunoPropertiesProvider(null, config); provider.setConfig(config); if(logger.isDebugEnabled()){ String msg = String.format("Configuring %s without @Named annotations with the following properties: %s",junoClass.getName(),provider.toString()); logger.debug(msg); } Object junoClient = createJunoBean(provider,junoClass); for (String nonQualifedBean : nonQualifiedBeanList){ ((DefaultListableBeanFactory)factory).registerSingleton(nonQualifedBean, junoClient); } } } private Object createJunoBean(JunoPropertiesProvider provider,Class<?> junoClass){ if(junoClass == JunoClient.class){ return JunoClientFactory.newJunoClient(provider); }else if(junoClass == JunoAsyncClient.class){ return JunoClientFactory.newJunoAsyncClient(provider); }else if(junoClass == JunoReactClient.class){ return JunoClientFactory.newJunoReactClient(provider); }else { return null; } } /** * Locate beans that have @Inject or @Autowired injection points for the JunoClient. @Named * is also considered for qualifying injection points. * @param factory * @return * @throws BeansException */ private void locateInjectionPoints(ConfigurableListableBeanFactory factory,List<String> qualifiedBean, List<String> nonQualifiedBean,Class<?> junoClientClass) throws BeansException { // get a list of all the beans in the system for (String beanName : factory.getBeanDefinitionNames()) { Class<?> clazz = null; try { String beanClassName = factory.getBeanDefinition(beanName).getBeanClassName(); if (beanClassName == null) { continue; } clazz = Class.forName(beanClassName); } catch (ClassNotFoundException e) { logger.error("Unable to load injection bean", e); throw new BeanDefinitionValidationException("Unable to load injection bean", e); } //For Field Injection Field[] fields = clazz.getDeclaredFields(); //clazz.getSuperclass() if (fields != null && fields.length != 0 ) { for (Field field : fields) { Inject inject = field.getAnnotation(Inject.class); Autowired autowired = field.getAnnotation(Autowired.class); Named named = field.getAnnotation(Named.class); if ((inject != null || autowired != null) && field.getType() == junoClientClass) { populateBeanLists(qualifiedBean,nonQualifiedBean,named,field.getName()); } } } //For Field Injection of superClass if(clazz.getSuperclass() != null) { fields = clazz.getSuperclass().getDeclaredFields(); if (fields != null && fields.length != 0) { for (Field field : fields) { Inject inject = field.getAnnotation(Inject.class); Autowired autowired = field.getAnnotation(Autowired.class); Named named = field.getAnnotation(Named.class); if ((inject != null || autowired != null) && field.getType() == junoClientClass) { populateBeanLists(qualifiedBean, nonQualifiedBean, named, field.getName()); } } } } //For Constructor Injection Constructor[] Constructors = clazz.getConstructors(); if (Constructors != null && Constructors.length != 0) { for (Constructor constructor : Constructors) { Parameter[] params = constructor.getParameters(); for(Parameter param : params){ if(param.getType() == junoClientClass) { Annotation[] annotate = param.getAnnotations(); if(annotate != null && annotate.length != 0) { for (Annotation annotation : annotate) { if (annotation.annotationType() == Named.class) { populateBeanLists(qualifiedBean, nonQualifiedBean, ((Named) annotation), null); } } } } } } } } } /** * Populate the bean list based on the value How they are declared. If they are declared with @named annotations * then the named value will be put in the qualified annotation and if there is not @Named annotation then the * objects name will be put in nonQualified Bean list. * @param qualifiedBeanList - List of unique named annotations * @param nonQualifiedBeanList - List of unique Object names * @param qualifierName - Value of @Named annotation * @param beanName - Object name specified after @Inject */ void populateBeanLists(List<String> qualifiedBeanList,List<String> nonQualifiedBeanList,Named qualifierName,String beanName){ if (qualifierName == null) { // Add bean name to non qualified list only if not present if(!nonQualifiedBeanList.contains(beanName)){ nonQualifiedBeanList.add(beanName); } } else { // Add qualifier to qualified list only if not present if(!qualifiedBeanList.contains(qualifierName.value())){ qualifiedBeanList.add(qualifierName.value()); } } } /** * Look at the properties contained within the Commons Configuration for Juno client * properties. There can be multiple instances. * <p/> * <p/> * Juno configuration properties as well as defaults will have the form: * Juno.connection.retries=1 * <p/> * Juno configuration properties for a named/qualified injection point will have the form of * <qualifier>.juno.connection.retries=1 * <p/> * Cases: * <p/> * - A default configuration * - A named configuration * - A named configuration for which missing properties will come from a default property name * * @return A map of JunoPropertiesProvider instances keyed by a String value representing the injection point * name which will become the created bean name. */ private JunoPropertiesProvider getJunoPropertiesProvider(String qualifier, Configuration configuration) { Properties properties = new Properties(); JunoPropertiesProvider propertiesProvider = null; /* Must check specifically for unqualified and qualified cases of juno property values that match juno. or <qualifier>.juno. */ Iterator<String> keys = null; if (qualifier == null) { // UNQAULIFIED //Add prefix to the property properties.put("prefix",""); // Get keys prefixed with "juno" keys = configuration.getKeys("juno"); // Look for the property key as is while (keys.hasNext()) { String key = (String) keys.next(); properties.put(key, configuration.getString(key)); } } else { // QUALIFIED properties.put("prefix",qualifier); // Get the subset of keys prefixed by the qualifier which also removes the qualifier from the property key Configuration subset = configuration.subset(qualifier); keys = subset.getKeys("juno"); while (keys.hasNext()) { String key = (String)keys.next(); properties.put(key, subset.getString(key)); } } if (properties.size() == 0) throw new JunoException("No Juno Client properties could be found for qualifying properties: " + qualifier); propertiesProvider = new JunoPropertiesProvider(properties); return propertiesProvider; } }
129
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/MessageDecoder.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.net; import com.paypal.juno.io.protocol.MessageHeader; import com.paypal.juno.io.protocol.OperationMessage; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.net.InetSocketAddress; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * To convert message buffer to OperationMessage. * */ public class MessageDecoder extends ByteToMessageDecoder { private static final Logger LOGGER = LoggerFactory.getLogger(MessageDecoder.class); private boolean parseHeader = true; private MessageHeader header = null; private int bodySize = 0; @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { if (parseHeader) { int len = 16; if (in.readableBytes() < len) { return; } header = new MessageHeader(); header.readBuf(in); bodySize = header.getMessageSize() - len; parseHeader = false; } if (in.readableBytes() < bodySize) { return; } OperationMessage opMsg = new OperationMessage(); opMsg.setHeader(header); header = null; // release reference opMsg.readBuf(in); String serverIp = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress(); opMsg.setServerIp(serverIp); out.add(opMsg); parseHeader = true; bodySize = 0; } }
130
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/BaseProcessor.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.net; import java.net.InetAddress; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class BaseProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(BaseProcessor.class); private BlockingQueue<String> pingRespQueue = new ArrayBlockingQueue<String>(1); boolean useLTM() { return false; } void setPingIp(String ip) { pingRespQueue.offer(ip); } InetAddress getPingIp() throws InterruptedException { String str = pingRespQueue.poll(300, TimeUnit.MILLISECONDS); if (str == null || str.length() == 0) { return null; } InetAddress ip = null; try { ip = InetAddress.getByName(str); } catch (Exception e) { LOGGER.warn("Failed to get InetAddress for "+str+" "+e.toString()); return null; } return ip; } void clearPingRespQueue() throws InterruptedException { pingRespQueue.poll(2, TimeUnit.MILLISECONDS); } }
131
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/Scheduler.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.net; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.JunoLogLevel; import com.paypal.juno.util.JunoStatusCode; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * To synchronize recycle of connections. One scheduler per worker pool. * */ class ConnectLock { ReentrantLock lock; AtomicLong owner; AtomicBoolean connected; ConnectLock() { lock = new ReentrantLock(); owner = new AtomicLong(1); connected = new AtomicBoolean(); } } class Scheduler { private static final Logger LOGGER = LoggerFactory.getLogger(Scheduler.class); private static final SecureRandom ran = new SecureRandom(); private static final long shift = 5000; // milliseconds private long connectionLifeTime; private WorkerPool pool; private SocketConfigHolder config; private ConnectLock[] locks; private BlockingQueue<Object> waitQueue; private volatile boolean ready = false; private final int LOG_CYCLE = 20; Scheduler(int lifeTime, int poolSize, WorkerPool pool, SocketConfigHolder config) { connectionLifeTime = lifeTime; this.pool = pool; this.config = config; locks = new ConnectLock[poolSize]; for (int i = 0; i < poolSize; i++) { locks[i] = new ConnectLock(); } waitQueue = new ArrayBlockingQueue<Object>(poolSize*2); } synchronized private int lockAny() throws InterruptedException { int k = -1; for (int i = 0; i < locks.length; i++) { if (!locks[i].lock.isLocked()) { k = i; break; } } if (WorkerPool.isQuit()) { throw new InterruptedException("Interrupted"); } pool.addWorker(); if (k >= 0) { locks[k].lock.lockInterruptibly(); } return k; } /* * Called before connect. */ int acquireConnectLock(int index) throws InterruptedException { if (index >= 0 && locks[index].lock.isHeldByCurrentThread()) { return index; } while (true) { int k = lockAny(); if (k >= 0) { return k; } while (true) { // Wait for lock release. Object x = waitQueue.poll(2, TimeUnit.SECONDS); if (WorkerPool.isQuit()) { throw new InterruptedException("Interrupted"); } if (x != null) { break; } } } } JunoLogLevel getConnectLogLevel(int lockIndex) { JunoLogLevel level = JunoLogLevel.OFF; if (lockIndex < 0) { return level; } long id = locks[lockIndex].owner.get(); if (id < LOG_CYCLE/2 || (id % LOG_CYCLE) == 0) { level = LOGGER.isDebugEnabled()?JunoLogLevel.INFO:JunoLogLevel.OFF; } return level; } JunoLogLevel getDisconnectLogLevel(long ownerId) { if (ownerId < LOG_CYCLE/2 || (ownerId % LOG_CYCLE) == 0) { return LOGGER.isDebugEnabled()?JunoLogLevel.INFO:JunoLogLevel.OFF; } return JunoLogLevel.OFF; } /* * Set and return the owner of the connection after connection has been created. */ long setConnectOwner(int index) { setConnected(index); return locks[index].owner.incrementAndGet(); } /* * Release the lock for a standby worker to connect. * Check if the connection owner has changed. */ boolean connectOwnerExpired(int index, long ownerId) { if (index < 0) { return true; } if (locks[index].lock.isHeldByCurrentThread()) { locks[index].lock.unlock(); waitQueue.offer(new Object()); return false; } // Check if the owner has changed. // This happens when another worker has acquired the lock and started a new connection. return (locks[index].owner.get() != ownerId); } /* * Select a slot for next disconnect time. */ long selectTimeSlot() { long x = System.currentTimeMillis() + connectionLifeTime; if (connectionLifeTime >= 2 * shift) { x -= (long)(shift * ran.nextFloat()); } return x; } private void setConnected(int index) { if (index < 0 || index >= locks.length) { return; } locks[index].connected.set(true); } void setDisconnected(int index, long ownerId) { if (index < 0 || index >= locks.length) { return; } if (ownerId != locks[index].owner.get()) { return; } locks[index].connected.set(false); } boolean isConnected() { for (int i = 0; i < locks.length; i++) { if (locks[i].connected.get()) { return true; } } return false; } boolean isIndexedChannelConnected(int index) { if (index < 0 || index >= locks.length) { return false; } return locks[index].connected.get(); } boolean waitForReady(int connectionTimeout) { final int waitTime = 50; int count = 3 * connectionTimeout / waitTime; for (int i = 0; i < count; i++) { if (isConnected()) { LOGGER.info("Worker pool ready."); return true; } try { Thread.sleep(waitTime); } catch (Exception e) { } } return false; } boolean isTestMode() { return config.isTestMode(); } boolean onEvent(TestEvent event) { if (!isTestMode()) { return false; } int val = event.maskedValue(); if (val == 0) { return false; } LOGGER.warn("On test event: "+ event); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name","JUNO_TEST"); trans.put("event", Long.toString(val)); trans.put("status", JunoStatusCode.WARNING.toString()); LOGGER.warn(JunoStatusCode.WARNING + " {} ", trans); return true; } void onException(TestEvent event) throws Exception { if (!onEvent(event)) { return; } event.triggerException(); } }
132
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/PingMessage.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.net; import com.paypal.juno.client.ServerOperationStatus; import com.paypal.juno.io.protocol.MessageHeader.MessageOpcode; import com.paypal.juno.io.protocol.MessageHeader.MessageRQ; import com.paypal.juno.io.protocol.MessageHeader.MessageType; import com.paypal.juno.io.protocol.MessageHeader; import com.paypal.juno.io.protocol.MetaMessageSourceField; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.net.InetAddress; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * To send Nop to proxy servers and get server ip. * */ class PingMessage extends OperationMessage { private static final Logger LOGGER = LoggerFactory.getLogger(PingMessage.class); private static byte[] localAddress = null; PingMessage(String appName, int opaque) { MessageHeader header = new MessageHeader(); header.setMsgType((byte)(MessageType.OperationalMessage.ordinal())); header.setFlags((byte) 0); // This field is not significant for client. header.setMessageRQ((byte)(MessageRQ.TwoWayRequest.ordinal())); header.setOpcode((short)(MessageOpcode.Nop.ordinal())); header.setOpaque(opaque); header.setStatus((byte)(ServerOperationStatus.BadMsg.getCode())); setHeader(header); MetaOperationMessage mo = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); if (appName == null) { appName = new String("JunoInternal"); } mo.addSourceField(getLocalAddress(), 0, appName.getBytes()); setMetaComponent(mo); } ByteBuf pack() { ByteBuf out = Unpooled.buffer(getLength()); writeBuf(out); return out; } static byte[] getLocalAddress() { if (localAddress != null) { return localAddress; } try { localAddress = InetAddress.getLocalHost().getAddress(); } catch(Exception e){ localAddress = InetAddress.getLoopbackAddress().getAddress(); } return localAddress; } static boolean isPingResp(OperationMessage op, BaseProcessor processor) { if (processor.useLTM()) { return false; } MessageHeader header = op.getHeader(); if (header == null || (header.getOpcode() != (short)(MessageOpcode.Nop.ordinal()))) { return false; // not a Nop response } MetaOperationMessage mo = op.getMetaComponent(); if (mo == null) { return false; } MetaMessageSourceField source = mo.getSourceField(); if (source == null || source.getAppName() == null) { return false; } String str = new String(source.getAppName()); if (!str.equals("JunoInternal")) { return false; } // Extract ip from ping response. byte[] w = source.getIp4(); if (w == null || w.length < 4) { LOGGER.warn("Ping resp ip=null"); processor.setPingIp(""); return true; } if (w[0] == 127) { LOGGER.warn("Ping resp ip=127.*.*.*"); processor.setPingIp(""); return true; } if (Arrays.equals(PingMessage.getLocalAddress(), w)) { LOGGER.debug("Ping resp ip same as local addr"); processor.setPingIp(""); return true; } str = source.getIp4String(w); // Pass ip to sending thread LOGGER.debug("Ping resp ip="+str); processor.setPingIp(str); return true; } }
133
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/ClientHandler.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.net; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.util.JunoMetrics; import com.paypal.juno.util.JunoStatusCode; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.ReferenceCountUtil; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * To process response from proxy servers. This object is linked to channel pipeline. * */ public class ClientHandler extends ChannelInboundHandlerAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(ClientHandler.class); private IOProcessor processor; // @Autowired // InstanceLocation instanceLocation; // private final String INSTANCE_GEO_PP_US = "PP_US"; ClientHandler(IOProcessor p) { processor = p; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { processor.incrementRecvCount(); if (!(msg instanceof OperationMessage)) { LOGGER.error("Invalid OperationMessage from downstream."); ReferenceCountUtil.release(msg); return; } if (!PingMessage.isPingResp((OperationMessage)msg, processor)) { processor.putResponse((OperationMessage)msg); } ReferenceCountUtil.release(msg); if (processor.onEvent(TestEvent.READ_FAIL)) { exceptionCaught(ctx, new RuntimeException("Test Read Fail")); } } @Override public void channelInactive(ChannelHandlerContext ctx) { processor.validateMsgCount(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof InterruptedException) { ctx.close(); return; } final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); LOGGER.error(cause.toString() + " " + cause.getMessage()); trans.put("name", "JUNO_RECEIVE"); trans.put("server", processor.getServerAddr()); trans.put("error", cause.toString()); trans.put("status", JunoStatusCode.ERROR.toString()); LOGGER.error("ClientHandler Error : {}", trans); ctx.close(); JunoMetrics.recordErrorCount("JUNO_RECEIVE",processor.getRemoteIpAddr(),cause.getClass().getName()); } }
134
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/WorkerPool.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.net; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.SSLUtil; import java.io.*; import java.net.URL; import java.net.URLClassLoader; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * IO Worker pool. * */ class WorkerThreadFactory implements ThreadFactory { private static final AtomicInteger poolId = new AtomicInteger(); private final AtomicInteger nextId = new AtomicInteger(); private final String prefix; private final boolean daemon; WorkerThreadFactory(String poolName, boolean daemon) { this.prefix = poolName + '-' + poolId.incrementAndGet() + '-'; this.daemon = daemon; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, prefix + nextId.incrementAndGet()); t.setDaemon(daemon); return t; } } class WorkerPool { private static final Logger LOGGER = LoggerFactory.getLogger(WorkerPool.class); private static volatile boolean quit = false; private int maxWorkers; private BlockingQueue<Runnable> taskQueue; private ThreadPoolExecutor pool = null; private SocketConfigHolder config; private RequestQueue requestQueue; private Scheduler scheduler; private SSLContext ctx; WorkerPool(SocketConfigHolder cfg, RequestQueue queue) { maxWorkers = 2 * cfg.getConnectionPoolSize(); taskQueue = new ArrayBlockingQueue<Runnable>(maxWorkers); scheduler = new Scheduler(cfg.getConnectionLifeTime(), cfg.getConnectionPoolSize(), this, cfg); init(cfg, queue); scheduler.waitForReady(cfg.getConnectTimeout()); } synchronized void init(SocketConfigHolder cfg, RequestQueue q) { if (pool != null) { return; } config = cfg; requestQueue = q; if (config.useSSL()) { ctx = config.getCtx(); if (ctx != null) { LOGGER.info("Use client ssl context."); } else{ loadSslContext(); } } quit = false; pool = new ThreadPoolExecutor(maxWorkers, maxWorkers, 0, TimeUnit.SECONDS, taskQueue, new WorkerThreadFactory("JunoWorker", true)); // Add all workers. for (int i = 0; i < maxWorkers; i++) { addWorker(); } } synchronized void shutdown() { if (pool == null) { return; } LOGGER.info("Shutdown IO."); quit = true; pool.shutdownNow(); try { pool.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e){ LOGGER.debug("Worker got interrupted."); Thread.currentThread().interrupt(); } pool = null; } private void loadSslContext() { ctx = SSLUtil.getSSLContext(); if (ctx == null) { throw new RuntimeException("unable to get ssl context."); } } public String[] getResourceListing(URL url) { URLClassLoader classLoader = new URLClassLoader(new URL[] { url }); InputStream inputStream = classLoader.getResourceAsStream("secrets"); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); return br.lines().toArray(String[]::new); } void addWorker() { if (pool.getQueue().remainingCapacity() <= 0) { return; } try { pool.submit(new IOProcessor(config, requestQueue, scheduler, ctx, requestQueue.getOpaqueResMap())); } catch (RejectedExecutionException e) { // No more wokers needed. } } boolean isConnected() { return scheduler.isConnected(); } static boolean isQuit() { return quit; } public SocketConfigHolder getConfig(){ return config; } }
135
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/RequestQueue.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.net; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.JunoMetrics; import com.paypal.juno.util.JunoStatusCode; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * To pass messages to IO worker threads. * * Example: requestQueue = RequestQueue.getInstance(config); * boolean ok = requestQueue.enqueue(req); * */ class QueueEntry { ByteBuf msg; String reqId; long enqueueTime; QueueEntry(ByteBuf req, String id) { msg = req; reqId = id; enqueueTime = System.currentTimeMillis(); } } public class RequestQueue { private static final Logger LOGGER = LoggerFactory.getLogger(RequestQueue.class); private static final int MAX_RECYCLE_ATTEMPT = 2; private static final int INITIAL_VALUE_RECYCLE_ATTEMPT = 0; private static final long RECYCLE_CONNECT_TIMEOUT = 180000; // 3 minutes private static final double INITIAL_AVERAGE_VALUE = 0.0; private static Map<InetSocketAddress, RequestQueue> reqMap = new Hashtable<InetSocketAddress, RequestQueue>(); private final ConcurrentHashMap<Integer,BlockingQueue<OperationMessage>> opaqueRespQueueMap = new ConcurrentHashMap<Integer,BlockingQueue<OperationMessage>>(); private final BlockingQueue<QueueEntry> queue = new ArrayBlockingQueue<QueueEntry>(1000); private WorkerPool workerPool; private long responseTimeout; private Timer timer; private AtomicInteger failedAttempts = new AtomicInteger(); private AtomicInteger successfulAttempts = new AtomicInteger(); private double average; private static final double FAILURE_THRESHOLD = 0.3; private static final int INTERVAL = 1000; private static final int SAFETY_BUFFER = 30; private final PropertyChangeSupport changes = new PropertyChangeSupport(this); private int recycleAttempt = INITIAL_VALUE_RECYCLE_ATTEMPT; private long nextRecycleAttemptDue = System.currentTimeMillis(); // @Autowired // InstanceLocation instanceLocation; // private final String INSTANCE_GEO_PP_US = "PP_US"; /* * Get a request queue based on proxy port. */ synchronized public static RequestQueue getInstance(SocketConfigHolder cfg) { InetSocketAddress inetAddress = InetSocketAddress.createUnresolved(cfg.getHost(), cfg.getPort()); RequestQueue q = reqMap.computeIfAbsent(inetAddress, k -> new RequestQueue(cfg)); return q; } public ConcurrentHashMap<Integer, BlockingQueue<OperationMessage>> getOpaqueResMap() { return opaqueRespQueueMap; } /* * Shutdown all worker pools. */ synchronized public static void shutdown() { if (reqMap == null) { return; } for (Map.Entry<InetSocketAddress, RequestQueue> entry : reqMap.entrySet()) { entry.getValue().shutdownWorkerPool(); } reqMap = null; } /* * Serialize an OperationMessage, and put it into the queue. */ public boolean enqueue(OperationMessage req) { ByteBuf out = Unpooled.buffer(req.getLength()); req.writeBuf(out); MetaOperationMessage mo = req.getMetaComponent(); String requestId = "not_set"; if (mo != null) { requestId = mo.getRequestIdString(); } return enqueue(new QueueEntry(out, requestId)); } public boolean isConnected() { return workerPool.isConnected(); } static void clear() { if (reqMap == null) { return; } reqMap.clear(); } private RequestQueue(SocketConfigHolder cfg) { workerPool = new WorkerPool(cfg, this); responseTimeout = cfg.getResponseTimeout(); if(cfg.getReconnectOnFail()){ timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { checkForUnresponsiveConnection(successfulAttempts.getAndSet(0), failedAttempts.getAndSet(0)); } }; timer.schedule(task, INTERVAL, INTERVAL); } } private void checkForUnresponsiveConnection(int success, int failed){ int totalAttempts = success + failed + SAFETY_BUFFER; double alpha = 0.1; double currentValue = ((double)failed/totalAttempts); double ema = alpha * currentValue + (1 - alpha) * average; average = Double.isNaN(ema) || Double.isInfinite(ema) ? average : ema; if(reconnectOnFailEnabled() && average >= FAILURE_THRESHOLD){ recycleAttempt++; nextRecycleAttemptDue = System.currentTimeMillis(); changes.firePropertyChange("recycleNow", -1, 0); } } private boolean reconnectOnFailEnabled() { if(System.currentTimeMillis() < nextRecycleAttemptDue) { return false; } if(recycleAttempt >= MAX_RECYCLE_ATTEMPT){ changes.firePropertyChange("RECYCLE_CONNECT_TIMEOUT", -1, 1); nextRecycleAttemptDue += RECYCLE_CONNECT_TIMEOUT; recycleAttempt = INITIAL_VALUE_RECYCLE_ATTEMPT; return false; } return true; } private void shutdownWorkerPool() { workerPool.shutdown(); } /* * For IO workers to dequeue a request message. */ QueueEntry dequeue() throws InterruptedException { QueueEntry entry = queue.poll(1, TimeUnit.SECONDS); if (entry == null) { return null; } long due = entry.enqueueTime + responseTimeout; if (System.currentTimeMillis() > due) { LOGGER.error( "Expired requests got discarded. "+"req_id="+entry.reqId+ " enqueue_time="+entry.enqueueTime+" resp_timeout="+responseTimeout); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name","JUNO_REQUEST_EXPIRED"); trans.put("req_id", entry.reqId); trans.put("enqueue_time", Long.toString(entry.enqueueTime)); trans.put("resp_timeout", Long.toString(responseTimeout)); trans.put("status", JunoStatusCode.WARNING.toString()); LOGGER.warn(JunoStatusCode.WARNING + " {} ", trans); JunoMetrics.recordErrorCount("JUNO_REQUEST_EXPIRED",workerPool.getConfig().getHost()+":"+workerPool.getConfig().getPort(),JunoMetrics.ERROR); return null; } return entry; } boolean enqueue(QueueEntry msg) { try { boolean ok = queue.offer(msg); if (ok) { return true; } LOGGER.error("Outbound queue is full."); return false; } catch (Exception e) { LOGGER.error("Adding message to request queue:"+e.toString()); return false; } } int size() { return queue.size(); } public void addPropertyChangeListener(PropertyChangeListener l) { changes.addPropertyChangeListener(l); } public void incrementFailedAttempts() { failedAttempts.incrementAndGet(); } public void incrementSuccessfulAttempts() { successfulAttempts.incrementAndGet(); } public void resetValues() { average = INITIAL_AVERAGE_VALUE; } public double getAverage(){ return average; } }
136
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/IOProcessor.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.net; import com.paypal.juno.io.protocol.MetaOperationMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.JunoLogLevel; import com.paypal.juno.util.JunoMetrics; import com.paypal.juno.util.JunoStatusCode; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.JdkSslContext; import io.netty.handler.ssl.SslHandler; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.Future; import java.net.InetAddress; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To process IO messages sent to and received from proxy servers. * * */ class IOProcessor extends BaseProcessor implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(IOProcessor.class); private static AtomicInteger counter = new AtomicInteger(); private static final int INITIAL_BYPASSLTM_RETRY_INTERVAL = 337500; private int bypassLTMRetryInterval = INITIAL_BYPASSLTM_RETRY_INTERVAL; private static final int MAX_BYPASSLTM_RETRY_INTERVAL = 86400000; private int id; private SocketConfigHolder config; private RequestQueue requestQueue; private Scheduler scheduler; private Bootstrap bootstrap; private Channel ch; private int handshakeFail = 0; private String serverAddr = ""; private boolean recycleStarted = false; // stats per connect session. private int sendCount = 0; private int failCount = 0; private AtomicInteger recvCount = new AtomicInteger(); private final int INIT_WAIT_TIME = 200; private final int MAX_WAIT_TIME = 60000; private int reconnectWaitTime = INIT_WAIT_TIME; private long nextReconnectDue; private long nextByPassLTMCheckTime = System.currentTimeMillis(); private final SecureRandom ran = new SecureRandom(); private ConcurrentHashMap<Integer,BlockingQueue<OperationMessage>> opaqueRespQueueMap; private SSLContext ctx; private String remoteConfigAddr; private String remoteIpAddr; private int lockIndex = -1; private long ownerId = -1; private boolean reconnectNow = false; enum Status { CONNECT_FAIL, WAIT_FOR_MESSAGE, SENT_DONE } IOProcessor(SocketConfigHolder config, RequestQueue queue, Scheduler scheduler, SSLContext ctx, ConcurrentHashMap<Integer,BlockingQueue<OperationMessage>> opaqueRespQueueMap) { this.id = counter.getAndIncrement(); this.config = config; this.requestQueue = queue; this.nextReconnectDue = Long.MAX_VALUE; this.scheduler = scheduler; this.opaqueRespQueueMap = opaqueRespQueueMap; this.ctx = ctx; this.remoteConfigAddr = getHost()+":"+getPort(); this.remoteIpAddr = this.remoteConfigAddr; requestQueue.addPropertyChangeListener(evt -> { if(evt.getPropertyName().equals("recycleNow")) { this.reconnectNow = true; } }); } private String getHost() { return config.getHost(); } private int getPort() { return config.getPort(); } private int getConnectTimeout(){ return config.getConnectTimeout(); } boolean useLTM() { if (getHost().equals("127.0.0.1")) { return true; } return !config.getBypassLTM(); } private boolean isBypassLTMDisabled() { long currentTime= System.currentTimeMillis(); if (currentTime > nextByPassLTMCheckTime && bypassLTMRetryInterval < MAX_BYPASSLTM_RETRY_INTERVAL) { return false; } return true; } void putResponse(OperationMessage opMsg) { int opaq = opMsg.getHeader().getOpaque(); BlockingQueue<OperationMessage> respQueue = opaqueRespQueueMap.get(opaq); if (respQueue == null) { LOGGER.debug("The response queue for opaque="+opaq+" no longer exists. Probably response timed out."); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", "JUNO_LATE_RESPONSE"); trans.put("server", serverAddr); trans.put("req_id", opMsg.getMetaComponent().getRequestIdString()); trans.put("opaque", String.valueOf(opaq)); trans.put("ns", config.getRecordNamespace()); trans.put("w", ""+config.getConnectionPoolSize()); trans.put("rht", ""+opMsg.getMetaComponent().getRequestHandlingTime()); trans.put("status", JunoStatusCode.ERROR.toString()); LOGGER.error("Error {} ", trans); JunoMetrics.recordErrorCount("JUNO_LATE_RESPONSE",remoteIpAddr,JunoMetrics.ERROR); return; } try { scheduler.onException(TestEvent.EXCEPTION_3); boolean ok = respQueue.offer(opMsg); if (!ok) { LOGGER.error("Response queue is full."); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", "JUNO_RESPONSE_QUEUE_FULL"); trans.put("server", serverAddr); trans.put("req_id", opMsg.getMetaComponent().getRequestIdString()); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); JunoMetrics.recordErrorCount("JUNO_RESPONSE_QUEUE_FULL",remoteIpAddr,JunoMetrics.ERROR); } } catch (Exception e) { LOGGER.error("Adding response to response queue: "+e.getMessage()); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", "JUNO_RETURN_RESPONSE"); trans.put("server", serverAddr); trans.put("req_id", opMsg.getMetaComponent().getRequestIdString()); trans.put("error", e.toString()); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); JunoMetrics.recordErrorCount("JUNO_RETURN_RESPONSE",remoteIpAddr,e.getClass().getName()); } } boolean onEvent(TestEvent event) { return scheduler.onEvent(event); } void incrementRecvCount() { recvCount.incrementAndGet(); } // This method return the actual Juno box IP when Bypass LTM feature is enabled, else it returns VIP IP:Port String getServerAddr() { return serverAddr; } // This method returns the VIP IP:Port String getRemoteIpAddr(){ return remoteIpAddr; } String getRaddr(Channel chan) { String remote = chan.remoteAddress().toString(); int off = remote.indexOf("/") + 1; return remote.substring(off); } void validateMsgCount() { int numRecv = recvCount.get(); if (sendCount <= numRecv && !scheduler.onEvent(TestEvent.MISSING_RESPONSE)) { recycleStarted = false; return; } String text = "send_count="+sendCount+" fail_count="+failCount+" recv_count="+numRecv+" connection_lost="+!recycleStarted; LOGGER.error("Missing response: "+text); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", "JUNO_MISSING_RESPONSE"); trans.put("server", serverAddr); trans.put("send_count", Long.toString(sendCount)); trans.put("fail_count", Long.toString(failCount)); trans.put("recv_count", Long.toString(numRecv)); trans.put("connection_lost", Boolean.toString(!recycleStarted)); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); JunoMetrics.recordErrorCount("JUNO_MISSING_RESPONSE",remoteIpAddr,(!recycleStarted)?"connection_recycle":"connection_lost"); recycleStarted = false; } private JdkSslContext getSSLContext() { JdkSslContext nettyCtx = new JdkSslContext(ctx, true, ClientAuth.NONE); return nettyCtx; } private void disconnect(Channel other) throws InterruptedException { if (!isOpened()) { return; } recycleStarted = true; Channel chan = this.ch; if (other != null) { recycleStarted = false; chan = other; } String raddr = getRaddr(chan); chan.close().awaitUninterruptibly(); JunoLogLevel level = scheduler.getDisconnectLogLevel(ownerId); if(level != JunoLogLevel.OFF) { LOGGER.info(String.valueOf(scheduler.getDisconnectLogLevel(ownerId)), "Closed connection to " + raddr); } final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", remoteIpAddr); trans.put("framework", "juno"); if (!remoteIpAddr.equals(raddr)) { trans.put("usePingIP", "true"); } trans.put("raddr", raddr); trans.put("id", getConnectID()); trans.put("status",JunoStatusCode.SUCCESS.toString()); LOGGER.info(JunoStatusCode.SUCCESS + " {} ", trans); if (WorkerPool.isQuit()) { throw new InterruptedException("Interrupted"); } reconnectNow = false; requestQueue.resetValues(); } private boolean isOpened() { return (ch != null && ch.isActive()); } private boolean isSSL() { return (ch.pipeline().get(SslHandler.class) != null); } private void setConnectOwner() { ownerId = scheduler.setConnectOwner(lockIndex); } private String getConnectID() { return Long.toString(lockIndex) + "_" + Long.toString(ownerId & 0x1); } private void afterConnect() { reconnectWaitTime = INIT_WAIT_TIME; setNextReconnectDue(); sendCount = 0; failCount = 0; recvCount.set(0); recycleStarted = false; } private boolean connect() throws InterruptedException { if (isOpened() && handshakeFail <= 0) { return true; // already connected and no handshake failure } lockIndex = scheduler.acquireConnectLock(lockIndex); JunoLogLevel level = scheduler.getConnectLogLevel(lockIndex); // Check if any connection is ready for this channel. boolean notConnected = !scheduler.isIndexedChannelConnected(lockIndex); boolean ok = ipConnect(null, level); if (!ok) { return false; } handshakeFail = 0; if (notConnected || useLTM() || isBypassLTMDisabled()) { setConnectOwner(); return true; } // Send a Nop to get server ip. PingMessage req = new PingMessage(null, 0); ByteBuf out = req.pack(); clearPingRespQueue(); ChannelFuture f = ch.writeAndFlush(out.retain().duplicate()).awaitUninterruptibly(); out.release(); if (WorkerPool.isQuit()) { throw new InterruptedException("Interrupted"); } if (!f.isDone() || !f.isSuccess()) { return true; } InetAddress ip = getPingIp(); if (ip == null) { return true; } Channel old = this.ch; this.ch = null; ok = ipConnect(ip, level); if (ok) { LOGGER.debug("connected via ping ip="+ip.toString()); disconnect(old); old = null; bypassLTMRetryInterval = INITIAL_BYPASSLTM_RETRY_INTERVAL; nextByPassLTMCheckTime = System.currentTimeMillis(); } else { this.ch = old; nextByPassLTMCheckTime += bypassLTMRetryInterval; if(bypassLTMRetryInterval < MAX_BYPASSLTM_RETRY_INTERVAL){ bypassLTMRetryInterval = bypassLTMRetryInterval * 2; } } setConnectOwner(); return true; } // Connect and optionally do ssl handshake. private boolean ipConnect(InetAddress ip, JunoLogLevel level) throws InterruptedException { final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); long startTimeInMs = System.currentTimeMillis(); boolean handshakeStarted = false; try { if (!isOpened()) { bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout()); trans.put("framework", "juno"); int qsize = requestQueue.size(); trans.put("cfgAddr", remoteConfigAddr); trans.put("qsize", Long.toString(qsize)); // DNS lookup if (ip == null) { long start = System.currentTimeMillis(); try { ip = InetAddress.getByName(getHost()); }catch(Exception e){ trans.put("name", getHost()+":"+getPort()); throw e; } String remote = ip.toString(); int off = remote.indexOf("/") + 1; remoteIpAddr = remote.substring(off)+":"+getPort(); long duration = System.currentTimeMillis() - start; if (duration >= 500 || scheduler.onEvent(TestEvent.DNS_DELAY)) { // ms final Map<String,CharSequence> transTxn = new HashMap<String, CharSequence>(); transTxn.put("name", "JUNO_DNS_DELAY"); transTxn.put("ip", ip.toString()); transTxn.put("status",JunoStatusCode.WARNING.toString()); transTxn.put("duration", String.valueOf(duration)); LOGGER.warn(JunoStatusCode.WARNING + " {} ", transTxn); JunoMetrics.recordTimer("JUNO_DNS_DELAY",ip.toString(),JunoMetrics.WARNING,duration); } } else { trans.put("usePingIP", "true"); } trans.put("name", getHost()+":"+getPort()); this.ch = bootstrap.connect(ip, getPort()).sync().channel(); String local = ch.localAddress().toString(); int off = local.indexOf("/") + 1; trans.put("laddr", local.substring(off)); serverAddr = getRaddr(ch); String str = serverAddr + "&w=" + Long.toString(config.getConnectionPoolSize()); trans.put("raddr", str); trans.put("id", getConnectID()); int numRecv = recvCount.get(); String qsizeStr = ""; if (qsize > 0) { qsizeStr = " qsize="+Long.toString(qsize); } org.slf4j.event.Level eventLevel; if (sendCount > 0 || failCount > 0) { if (sendCount > numRecv || failCount > 0) { eventLevel = org.slf4j.event.Level.INFO; } else { eventLevel = org.slf4j.event.Level.DEBUG; } LOGGER.atLevel(eventLevel).log("Connected to "+serverAddr+qsizeStr+ " send_count="+sendCount+" fail_count="+failCount+" recv_count="+numRecv); trans.put("send_count", Long.toString(sendCount)); trans.put("fail_count", Long.toString(failCount)); trans.put("recv_count", Long.toString(numRecv)); } else { if (level != JunoLogLevel.OFF) { LOGGER.info("Connected to " + serverAddr + qsizeStr); } } if (isSSL()) { afterConnect(); } } if (scheduler.isTestMode()) { scheduler.onException(TestEvent.INTERRUPTED); scheduler.onException(TestEvent.EXCEPTION); } if (!isSSL()) { // non-ssl trans.put("status",JunoStatusCode.SUCCESS.toString()); LOGGER.info(JunoStatusCode.SUCCESS + " {} ", trans); // Log Metrics timer //JunoMetrics.recordTimer("CONNECT",getHost()+":"+getPort(),JunoMetrics.SUCCESS,System.currentTimeMillis() - startTimeInMs); JunoMetrics.recordConnectCount(remoteIpAddr,JunoMetrics.SUCCESS,"none"); if (!scheduler.isConnected()) { int wait = getConnectTimeout(); if (wait > 1000) { wait = 1000; } Thread.sleep(wait); } if (!isOpened() || scheduler.onEvent(TestEvent.CONNECTION_LOST)) { scheduler.setDisconnected(lockIndex, ownerId); LOGGER.warn("Connection closed by server."); final Map<String,CharSequence> subTrans = new HashMap<String, CharSequence>(); subTrans.put("name", "JUNO_CONNECTION_LOST"); subTrans.put("server", serverAddr); subTrans.put("error", "connection_closed_by_server"); subTrans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", subTrans); JunoMetrics.recordErrorCount("JUNO_CONNECTION_LOST",remoteIpAddr,"connection_closed_by_server"); return false; } handshakeFail = 0; afterConnect(); return true; } // ssl handshake SslHandler sslHandler = this.ch.pipeline().get(SslHandler.class); handshakeStarted = true; //sslHandler.engine().setEnableSessionCreation(false); Instant start = Instant.now(); Future<Channel> f = sslHandler.handshakeFuture().sync(); long elapsed = Duration.between(start, Instant.now()).toMillis(); // succeeded. handshakeFail = 0; if(level != JunoLogLevel.OFF) { LOGGER.info("SSL handshake successfully completed."); } SSLSession sess = sslHandler.engine().getSession(); String cipher = "unknown"; String ver="unknown"; if (sess != null) { cipher = sess.getCipherSuite(); ver = sess.getProtocol(); } String sslInfo = elapsed+"&cipher="+cipher+"&ver="+ver; trans.put("handshake_ms", sslInfo); trans.put("status",JunoStatusCode.SUCCESS.toString()); LOGGER.info(JunoStatusCode.SUCCESS + " {} ", trans); //Log Metrics timer - Its will be logged by Framework //JunoMetrics.recordTimer("CONNECT",getHost()+":"+getPort(),JunoMetrics.SUCCESS,System.currentTimeMillis() - startTimeInMs); JunoMetrics.recordConnectCount(remoteIpAddr,JunoMetrics.SUCCESS,"none"); Thread.sleep(1000); return true; } catch (InterruptedException e) { trans.put("error", "Interrupted"); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); //Log Metrics timer - Its will be logged by Framework //JunoMetrics.recordTimer("CONNECT",getHost()+":"+getPort(),JunoMetrics.ERROR,System.currentTimeMillis() - startTimeInMs); JunoMetrics.recordConnectCount(remoteIpAddr,JunoMetrics.ERROR,"InterruptedException"); throw e; } catch (Exception e) { scheduler.setDisconnected(lockIndex, ownerId); String err; if (handshakeStarted) { err = "SSL handshake with " + serverAddr + " failed: " + e.toString(); handshakeFail++; JunoMetrics.recordConnectCount(remoteIpAddr,JunoMetrics.ERROR,"Handshake_failure"); } else { err = "Connect to "+getHost()+":"+getPort() + " failed. Config Timeout :" + getConnectTimeout() + ". " + e.toString(); JunoMetrics.recordConnectCount(remoteIpAddr,JunoMetrics.ERROR,e.getClass().getName()); } LOGGER.error(err); trans.put("error", err); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); //Log Metrics timer //JunoMetrics.recordTimer("CONNECT",getHost()+":"+getPort(),JunoMetrics.ERROR,System.currentTimeMillis() - startTimeInMs); if (handshakeStarted && handshakeFail > 2) { // Add backoff time before retry. int shift = handshakeFail - 2; if (shift > 9) { shift = 9; } int wait = 20 << shift; Thread.sleep(wait); } if (isOpened()){ try { ch.close().sync(); } catch (InterruptedException ex) { throw ex; } catch (Exception ex) { } } return false; } } // Send messages to proxy. private Status send() throws InterruptedException { if (!connect()) { return Status.CONNECT_FAIL; } // Fetch a message. QueueEntry entry = requestQueue.dequeue(); if (entry == null) { return Status.WAIT_FOR_MESSAGE; } ByteBuf msg = entry.msg; if (!connect()) { boolean ok = requestQueue.enqueue(entry); LOGGER.info("requeue="+ok+" server="+remoteConfigAddr); return Status.CONNECT_FAIL; } // Flush the message. ChannelFuture f = ch.writeAndFlush(msg.retain().duplicate()).awaitUninterruptibly(); if (f.isDone() && f.isSuccess() && !scheduler.onEvent(TestEvent.SEND_FAIL)) { // succeeded sendCount++; LOGGER.debug("netty send ok. server="+serverAddr); } else { // failed failCount++; Throwable cause = f.cause(); if (cause == null) { cause = new RuntimeException("netty failure."); } OperationMessage op = new OperationMessage(); op.readBuf(msg); MetaOperationMessage mo = op.getMetaComponent(); String requestId = "not_set"; String corrId = "not_set"; if (mo != null) { requestId = mo.getRequestIdString(); corrId = mo.getCorrelationIDString(); } LOGGER.error("server="+serverAddr+" req_id="+requestId+" corr_id="+corrId+" Send failed:"+cause); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", "JUNO_SEND"); trans.put("server", serverAddr); trans.put("req_id", requestId); trans.put("corr_id_", corrId); trans.put("error", cause.toString()); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); JunoMetrics.recordErrorCount("JUNO_SEND",remoteIpAddr,cause.getClass().getName()); } msg.release(); if (WorkerPool.isQuit()) { if (f.isSuccess()) { final int DELAY = 2 * config.getResponseTimeout(); // milliseconds Thread.sleep(DELAY); } throw new InterruptedException("Interrupted"); } return Status.SENT_DONE; } private Bootstrap configBootstrap(EventLoopGroup g) { bootstrap = new Bootstrap(); bootstrap.group(g).channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (config.useSSL()) { JdkSslContext sslContext = getSSLContext(); //System.out.println("SSL session cache size:"+sslContext.context().getProtocol()); pipeline.addLast(sslContext.newHandler(ch.alloc())); } pipeline .addLast("decoder", new MessageDecoder()) .addLast("handler", new ClientHandler(IOProcessor.this)); } }); return bootstrap; } private void setNextReconnectDue() { nextReconnectDue = scheduler.selectTimeSlot(); } private boolean reconnectDue() { return System.currentTimeMillis() > nextReconnectDue; } private boolean recycleNow() throws InterruptedException { if (!reconnectDue()) { return false; } if (!scheduler.connectOwnerExpired(lockIndex, ownerId)){ return false; // The other worker has not connected yet. } final int DELAY = (int)(2 * config.getResponseTimeout()); // milliseconds Thread.sleep(DELAY); LOGGER.debug("Recycle connection ..."); return true; } public void run() { LOGGER.info("Start worker_" + this.id); EventLoopGroup clientGroup = new NioEventLoopGroup(2, new DefaultThreadFactory("JunoNioEventLoop", true)); boolean logOnce = scheduler.isConnected(); try{ bootstrap = configBootstrap(clientGroup); while (true) { if (send() == Status.CONNECT_FAIL) { // Wait a little before reconnect. Thread.sleep(reconnectWaitTime); reconnectWaitTime *= 2; if (reconnectWaitTime > MAX_WAIT_TIME) { reconnectWaitTime = MAX_WAIT_TIME; } // Add random adjustment. reconnectWaitTime *= (1 + 0.3 * ran.nextFloat()); } else if (!logOnce && lockIndex == 0 && ownerId <= 2) { String tail = " (tcp)"; if (isSSL()) { tail = ""; } LOGGER.info("Connected to "+serverAddr+tail); logOnce = true; } // Recycle connection if due if (recycleNow() || reconnectNow) { disconnect(null); if (WorkerPool.isQuit()) { return; } } if (scheduler.isTestMode()) { scheduler.onException(TestEvent.INTERRUPTED_2); scheduler.onException(TestEvent.EXCEPTION_2); } } } catch (InterruptedException e) { LOGGER.debug("Worker got interrupted."); Thread.currentThread().interrupt(); return; } catch (Exception e) { LOGGER.error(e.getMessage()); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("name", "JUNO_IO"); trans.put("server", remoteConfigAddr); trans.put("error", e.toString()); trans.put("status",JunoStatusCode.ERROR.toString()); LOGGER.error(" Error : {}", trans); JunoMetrics.recordErrorCount("JUNO_IO",remoteIpAddr,e.getClass().getName()); } finally { LOGGER.info("Shutdown worker_" + this.id); // Release the connect lock if any. scheduler.connectOwnerExpired(lockIndex, ownerId); clientGroup.shutdownGracefully(); try { // terminate threads clientGroup.terminationFuture().sync(); } catch (Exception e) { } } } }
137
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/net/TestEvent.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.net; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * To trigger error handling code. * */ enum TestEvent { INTERRUPTED(1), INTERRUPTED_2(2), EXCEPTION(3), EXCEPTION_2(4), EXCEPTION_3(5), SEND_FAIL(6), READ_FAIL(7), CONNECTION_LOST(8), MISSING_RESPONSE(9), DNS_DELAY(10); private static final Logger LOGGER = LoggerFactory.getLogger(TestEvent.class); private static int mask = 0xffffffff; private final int val; private final int code; // code is a power of 2. TestEvent(int val) { this.val = val; this.code = 2 << val; } int getValue() { return val; } synchronized int maskedValue() { if ((mask & code) == 0) { return 0; } mask ^= code; return val; } void triggerException() throws Exception { switch (val) { case 1: case 2: throw new InterruptedException("Test mode: event "+val); case 3: case 4: case 5: throw new RuntimeException("Test Mode: event "+val); } } }
138
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/transport/TransportConfigHolder.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.transport; import java.net.InetSocketAddress; /** * * * To hold the transport configuration */ public interface TransportConfigHolder { /** * * @return Socket Inet Address of the transport */ public InetSocketAddress getInetAddress(); /** * @return Host name of the Server */ public String getHost(); /** * @return Server port */ public int getPort(); /** * @return true to use SSL */ public boolean useSSL(); }
139
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/transport
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/transport/socket/SocketConfigHolder.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.transport.socket; import com.paypal.juno.client.JunoClientConfigHolder; import com.paypal.juno.transport.TransportConfigHolder; import java.net.InetSocketAddress; import javax.net.ssl.SSLContext; public class SocketConfigHolder implements TransportConfigHolder{ InetSocketAddress inetAddress; String host; int port; boolean useSSL; int connectTimeout; int connectionLifeTime; int connectionPoolSize; int responseTimeout; boolean bypassLTM; String ns; boolean reconnectOnFail; SSLContext ctx; public SocketConfigHolder(JunoClientConfigHolder config){ inetAddress = config.getServer(); connectTimeout = config.getConnectionTimeoutMsecs(); connectionLifeTime = config.getConnectionLifeTime(); useSSL = config.getUseSSL(); port = config.getPort(); host = config.getHost(); connectionPoolSize = config.getConnectionPoolSize(); responseTimeout = config.getResponseTimeout(); bypassLTM = config.getByPassLTM(); ns = config.getRecordNamespace(); reconnectOnFail = config.getReconnectOnFail(); } public SocketConfigHolder() { } public int getPort() { return port; } public String getHost() { return host; } public void setPort(int port) { this.port = port; } public int getConnectTimeout() { return connectTimeout; } public InetSocketAddress getInetAddress() { return inetAddress; } public int getConnectionLifeTime() { return connectionLifeTime; } public boolean useSSL() { return useSSL; } public int getConnectionPoolSize() { return connectionPoolSize; } public int getResponseTimeout() { return responseTimeout; } public SSLContext getCtx() { return ctx; } public void setCtx(SSLContext ctx) { this.ctx = ctx; } public boolean getBypassLTM() { return bypassLTM; } public boolean getReconnectOnFail(){ return reconnectOnFail; } public String getRecordNamespace() { return ns; } public boolean isTestMode() { return false; } public String getJunoPool() { //Check if the hosts name stats with junoserv. If yes then return junoserv-<pool> otherwise //just return the port number if(host.startsWith("junoserv-")){ String junoPool[] = host.split("-",2); return junoPool[0]; }else{ // For all other endpoints that does not have junoserv as the endpoint prefix use host:port return new String(host + ":" + port); } } }
140
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/SendBatch.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.util; import com.paypal.juno.client.ServerOperationStatus; import com.paypal.juno.io.protocol.JunoMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.net.RequestQueue; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is dedicated to send the batch request * in a dedicated thread. */ public class SendBatch implements Callable<Integer> { Integer batchOpaque; RequestQueue reqQueue; ConcurrentHashMap<UUID, JunoMessage> reqIdReqMsgMap; final AtomicInteger reqCount; private static Logger LOGGER = LoggerFactory.getLogger(SendBatch.class); public SendBatch(Integer batchOpaque,RequestQueue reqQueue,ConcurrentHashMap<UUID,JunoMessage> reqIdReqMsgMap,AtomicInteger reqCount){ this.batchOpaque = batchOpaque; this.reqQueue = reqQueue; this.reqIdReqMsgMap = reqIdReqMsgMap; this.reqCount= reqCount; } @Override public Integer call() throws Exception { try{ //long batchStartTime = System.currentTimeMillis(); //Set any port number for(Map.Entry<UUID,JunoMessage> jMs : reqIdReqMsgMap.entrySet()){ //jMs.getValue().setReqStartTime(batchStartTime); OperationMessage operationMessage = JunoClientUtil.createOperationMessage(jMs.getValue(),batchOpaque); // Enqueue the message to netty transport boolean rc = reqQueue.enqueue(operationMessage); if(!rc){ jMs.getValue().setStatus(ServerOperationStatus.QueueFull); }else{ reqCount.incrementAndGet(); } if(reqCount.get() == 1){ synchronized (reqCount) { reqCount.notifyAll(); // Notify only for the first request alone. } } } }catch(Exception e){ LOGGER.info("JUNO_BATCH_SEND", JunoStatusCode.ERROR.toString(), "Exception while enqueuing the request"); } return reqCount.get(); } }
141
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/BasePropertiesProvider.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.util; import com.paypal.juno.exception.JunoClientConfigException; import java.io.IOException; import java.net.URL; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BasePropertiesProvider { private static final Logger logger = LoggerFactory.getLogger(BasePropertiesProvider.class); protected final Properties config; protected BasePropertiesProvider(URL url) { JunoClientUtil.throwIfNull(url, "URL"); this.config = new Properties(); try { this.config.load(url.openStream()); } catch (IOException e) { logger.error( "Unable to read the config properties file", e); throw new JunoClientConfigException( "Unable to read the config properties file", e); } } /** * Constructs the default properties provider. * * @param config properties */ protected BasePropertiesProvider(Properties config) { this.config = config; } protected final Integer getIntProperty(final String key, int defaultValue) { String sval = config.getProperty(key); int ival = defaultValue; if (sval != null) { try { ival = Integer.parseInt(sval.trim()); } catch(Exception e) { throw new JunoClientConfigException("Integer property not valid - Value = " + sval, e); } } return ival; } protected final Integer getIntegerProperty(final String key) { String sval = config.getProperty(key); Integer ival = null; if (sval != null && !sval.trim().equalsIgnoreCase("null")) { try { ival = Integer.parseInt(sval.trim()); } catch(Exception e) { throw new JunoClientConfigException("Integer property not valid - Value = " + sval, e); } } return ival; } protected final Long getLongProperty(final String key, long defaultValue) { String sval = config.getProperty(key); long ival = defaultValue; if (sval != null) { try { ival = Long.parseLong(sval.trim()); } catch(Exception e) { throw new JunoClientConfigException("Long property not valid - Value = " + sval, e); } } return ival; } protected final Long getLongProperty(final String key) { String sval = config.getProperty(key); Long ival = null; if (sval != null) { try { ival = Long.parseLong(sval.trim()); } catch(Exception e) { throw new JunoClientConfigException("Long property not valid - Value = " + sval, e); } } return ival; } protected final Boolean getBooleanProperty(final String key, boolean defaultValue) { String sval = config.getProperty(key); if (sval == null) { return defaultValue; } try { return Boolean.valueOf(sval); } catch(Exception e) { throw new JunoClientConfigException("Boolean property not valid - Value = " + sval, e); } } protected final Boolean getBooleanProperty(final String key) { String sval = config.getProperty(key); if (sval == null) { return null; } try { return Boolean.valueOf(sval); } catch(Exception e) { throw new JunoClientConfigException("Boolean property not valid - Value = " + sval, e); } } protected final String getStringProperty(String key, String defaultValue) { String sval = config.getProperty(key); return (sval != null ? sval : defaultValue); } }
142
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/JunoStatusCode.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.util; public enum JunoStatusCode { SUCCESS("0"), FATAL("1"), ERROR("2"), EXCEPTION("3"), WARNING("4"), UNKNOWN("U"); private final String statusCode; private JunoStatusCode(String code) { this.statusCode = code; } @Override public String toString() { return this.statusCode; } }
143
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/JunoConstants.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.util; public class JunoConstants { public static final int APP_NAME_MAX_LEN = 32; public static final String JUNO_CLIENT = "JUNO_CLIENT"; public static final String JUNO_SSL_CLIENT = "JUNO_SSL_CLIENT"; }
144
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/JunoClientUtil.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.util; import com.paypal.juno.client.JunoClientConfigHolder; import com.paypal.juno.client.ServerOperationStatus; 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.exception.JunoException; import com.paypal.juno.exception.JunoInputException; import com.paypal.juno.io.protocol.*; import com.paypal.juno.transport.socket.SocketConfigHolder; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.codec.binary.Hex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xerial.snappy.Snappy; import reactor.core.publisher.FluxSink; import rx.Subscriber; public class JunoClientUtil { //Juno Input Errors private static final String NULL_OR_EMPTY_KEY = "null_or_empty_key"; private static final String MAX_KEY_SIZE_EXCEEDED = "key_size_exceeded"; private static final String PAYLOAD_EXCEEDS_MAX_LIMIT = "payload_size_exceeded"; private static final String ZERO_OR_NEGATIVE_TTL = "invalid_ttl"; private static final String TTL_EXCEEDS_MAX = "ttl_exceeded_max"; private static final String ZERO_OR_NEGATIVE_VERSION = "invalid_version"; /** * The logger. We make this a non-static member in order to prevent this * from being synchronized. */ private static final Logger LOGGER = LoggerFactory.getLogger(JunoClientUtil.class); public static void throwIfNull(Object value, String name) { notNull(value, name + " must not be null"); } public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } public static boolean checkForRetry(OperationStatus status){ if(status == OperationStatus.RecordLocked || status == OperationStatus.TTLExtendFailure || status == OperationStatus.InternalError || status == OperationStatus.NoStorage ){ return true; }else{ return false; } } /** * Validate all the requests in a batch * @param req - list of requests in a batch * @param t - Subscriber for this batch * @return junoMsgMap - Map of Juno request ID and Juno message */ public static ConcurrentHashMap<UUID,JunoMessage> bulkValidate(Iterable<JunoRequest> req, Subscriber<? super JunoResponse> t, JunoClientConfigHolder configHolder, SocketConfigHolder sockConfig, boolean isAsync) { Iterator<JunoRequest> reqIter = req.iterator(); final ConcurrentHashMap<UUID,JunoMessage> junoMsgMap = new ConcurrentHashMap<UUID,JunoMessage>(); while(reqIter.hasNext()){ JunoRequest request = reqIter.next(); try{ JunoMessage jMsg = validateInput(request, getType(request.getType()),configHolder); jMsg.setStatus(ServerOperationStatus.ResponseTimedout); // Set all request status as response timed out. jMsg.setReqStartTime(System.currentTimeMillis()); junoMsgMap.put(jMsg.getReqId(),jMsg); }catch(Exception e){ final Map<String,CharSequence> childTrans = new HashMap<String, CharSequence>(); if(request.key() !=null && request.key().length != 0) { childTrans.put("hex_key", Hex.encodeHexString(request.key())); } childTrans.put("exception",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " {} ", childTrans); if(e.getCause() != null) JunoMetrics.recordOpCount(sockConfig.getJunoPool(), "B_"+ request.getType().getOpType(), OperationStatus.IllegalArgument.getErrorText(),e.getCause().getMessage()); else JunoMetrics.recordOpCount(sockConfig.getJunoPool(), "B_"+ request.getType().getOpType(), OperationStatus.IllegalArgument.getErrorText()); LOGGER.error(e.getMessage()); JunoResponse resp = new JunoResponse(request.key(),request.getValue(),request.getVersion(),request.getTimeToLiveSec(),request.getCreationTime(),OperationStatus.IllegalArgument); t.onNext(resp); } } return junoMsgMap; } /** * Validate all the requests in a batch * @param req - list of requests in a batch * @param t - Subscriber for this batch * @return junoMsgMap - Map of Juno request ID and Juno message */ public static ConcurrentHashMap<UUID,JunoMessage> bulkValidate(Iterable<JunoRequest> req, FluxSink<JunoResponse> t, JunoClientConfigHolder configHolder, SocketConfigHolder sockConfig, boolean isAsync) { Iterator<JunoRequest> reqIter = req.iterator(); final ConcurrentHashMap<UUID,JunoMessage> junoMsgMap = new ConcurrentHashMap<UUID,JunoMessage>(); while(reqIter.hasNext()){ JunoRequest request = reqIter.next(); try{ JunoMessage jMsg = validateInput(request, getType(request.getType()),configHolder); jMsg.setStatus(ServerOperationStatus.ResponseTimedout); // Set all request status as response timed out. jMsg.setReqStartTime(System.currentTimeMillis()); junoMsgMap.put(jMsg.getReqId(),jMsg); }catch(Exception e){ final Map<String,CharSequence> childTrans = new HashMap<String, CharSequence>(); if(request.key() !=null && request.key().length != 0) { childTrans.put("hex_key", Hex.encodeHexString(request.key())); } childTrans.put("exception",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " {} ", childTrans); if(e.getCause() != null) JunoMetrics.recordOpCount(sockConfig.getJunoPool(), "B_"+ request.getType().getOpType(), OperationStatus.IllegalArgument.getErrorText(),e.getCause().getMessage()); else JunoMetrics.recordOpCount(sockConfig.getJunoPool(), "B_"+ request.getType().getOpType(), OperationStatus.IllegalArgument.getErrorText()); LOGGER.error(e.getMessage()); JunoResponse resp = new JunoResponse(request.key(),request.getValue(),request.getVersion(),request.getTimeToLiveSec(),request.getCreationTime(),OperationStatus.IllegalArgument); t.next(resp); } } return junoMsgMap; } /** * Validate the user supplied inputs for limits based on the operation type * @param req - Request parameters to be validated * @param opr - Type of Operation * @return JunoMessage - JunoMessage object formed out of the request. */ public static JunoMessage validateInput(JunoRequest req, JunoMessage.OperationType opr, JunoClientConfigHolder configHolder) throws IllegalArgumentException{ //Null and empty Key validation is moved from JunoRequest object to here if (req.key() == null || req.key().length == 0) { throw new IllegalArgumentException("The Document key must not be null or empty",new JunoInputException(NULL_OR_EMPTY_KEY)); } long recordTtl = (long)((req.getTimeToLiveSec() == null) ? configHolder.getDefaultLifetimeSecs() : req.getTimeToLiveSec()); JunoMessage junoMsg = new JunoMessage(req.key(),req.getValue(),req.getVersion(),0,recordTtl,opr); if (req.key().length > configHolder.getMaxKeySize()) { throw new IllegalArgumentException("The Document key must not be larger than "+configHolder.getMaxKeySize()+" bytes", new JunoInputException(MAX_KEY_SIZE_EXCEEDED)); } //Validate the Payload. Payload cannot be > 204800 bytes if(opr != JunoMessage.OperationType.Get && opr != JunoMessage.OperationType.Destroy){ byte [] payload = req.getValue(); if(req.getValue() == null){ payload = new byte[0]; }else if(payload != null && payload.length > 1024 && configHolder.getUsePayloadCompression()){ try { byte [] compressedPayload = Snappy.compress(req.getValue()); // Calculate % compression achieved int compPercent = 100 - ((compressedPayload.length * 100)/req.getValue().length); if(compPercent > 0){ // do compression only if its effective payload = compressedPayload; // Currently we have only one compression type junoMsg.setCompressionType(PayloadOperationMessage.CompressionType.Snappy); junoMsg.setPayloadCompressed(true); junoMsg.setCompressionAchieved(compPercent); } } catch (IOException e) { // Exception while compressing so continue without compressing } } if(payload.length > configHolder.getMaxValueSize()) { String error = "The Document Value must not be larger than 204800 bytes. Current value size=" + payload.length; throw new IllegalArgumentException(error, new JunoInputException(PAYLOAD_EXCEEDS_MAX_LIMIT)); } junoMsg.setValue(payload); } //Validate TTL if( recordTtl < 0){ String error = "The Document's TTL cannot be negative. Current lifetime=" + recordTtl; throw new IllegalArgumentException(error,new JunoInputException(ZERO_OR_NEGATIVE_TTL)); }else if(recordTtl > configHolder.getMaxLifetimeSecs() ){ String error = "Invalid lifetime. current lifetime=" + recordTtl + ", max configured lifetime=" + configHolder.getMaxLifetimeSecs(); throw new IllegalArgumentException(error,new JunoInputException(TTL_EXCEEDS_MAX)); } switch(opr){ case Create: if(recordTtl == 0 || recordTtl < 0){ String error = "The Document's TTL cannot be 0 or negative."; throw new IllegalArgumentException(error,new JunoInputException(ZERO_OR_NEGATIVE_TTL)); } break; case Update: case Set: break; case CompareAndSet: if(req.getVersion() < 1){ String error = "The Document version cannot be less than 1. Current version="+req.getVersion(); throw new IllegalArgumentException(error, new JunoInputException(ZERO_OR_NEGATIVE_VERSION)); } break; case Get: case Destroy: break; default: break; } junoMsg.setNameSpace(configHolder.getRecordNamespace()); // Set Name space junoMsg.setApplicationName(configHolder.getApplicationName()); // Set Application name junoMsg.setReqId(UUID.randomUUID()); // Set the Requests ID here itself return junoMsg; } /** * Mapping between the Optype in Request and Optype in JunoMessage * @param opType - JunoRequest.OperationType * @return JunoMesage.OperationType */ private static JunoMessage.OperationType getType(JunoRequest.OperationType opType){ switch(opType){ case Create: return JunoMessage.OperationType.Create; case Get: return JunoMessage.OperationType.Get; case Update: return JunoMessage.OperationType.Update; case Set: return JunoMessage.OperationType.Set; case Destroy: return JunoMessage.OperationType.Destroy; default: return JunoMessage.OperationType.Nop; } } /** * This method creates the Juno operation protocol message object * @param junoMsg - Juno Message object * @param opaque - To identify a request * @return OperationMessage - Operation request message */ public static OperationMessage createOperationMessage(JunoMessage junoMsg, Integer opaque) { OperationMessage opMsg = new OperationMessage(); MessageHeader header = new MessageHeader(); MessageHeader.MessageOpcode code; switch (JunoMessage.OperationType.values()[junoMsg.getOpType().ordinal()]) { case Create: code = MessageHeader.MessageOpcode.Create; break; case Destroy: code = MessageHeader.MessageOpcode.Destroy; break; case Get: code = MessageHeader.MessageOpcode.Get; break; case Set: code = MessageHeader.MessageOpcode.Set; break; case Update: case CompareAndSet: code = MessageHeader.MessageOpcode.Update; break; default: throw new JunoException("internal Error, invalid type: " + junoMsg.getOpType().ordinal()); } //int flags = MessageRQ.TwoWayRequest.ordinal(); header.setMsgType((byte) MessageHeader.MessageType.OperationalMessage.ordinal()); header.setFlags((byte) 0); // This field is not significant for client. header.setMessageRQ((byte) MessageHeader.MessageRQ.TwoWayRequest.ordinal()); header.setOpcode((short)code.ordinal()); header.setOpaque(opaque); header.setStatus((byte) ServerOperationStatus.BadMsg.getCode()); opMsg.setHeader(header); //************************* Form the Meta Component ************************** MetaOperationMessage metaComponents = new MetaOperationMessage(0L,(byte)OperationMessage.Type.Meta.getValue()); opMsg.setMetaComponent(metaComponents); List<MetaMessageTagAndType> list = opMsg.getMetaComponent().getFieldList(); //Check for version and add int version = (int)junoMsg.getVersion(); if (version != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((MetaMessageTagAndType.FieldType.Version.ordinal()) | (1 << 5))); field.setContent(version); list.add(field); } // Check for Creation time and add if(junoMsg.getOpType() == JunoMessage.OperationType.Create || junoMsg.getOpType() == JunoMessage.OperationType.Set){ long createTime = System.currentTimeMillis() / 1000; if (createTime != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((MetaMessageTagAndType.FieldType.CreationTime.ordinal()) | (1 << 5))); field.setContent(createTime); list.add(field); } } // Check for TTL and add long lifetime = junoMsg.getTimeToLiveSec(); if (lifetime != 0) { MetaMessageFixedField field = new MetaMessageFixedField((byte) ((MetaMessageTagAndType.FieldType.TimeToLive.ordinal()) | (1 << 5))); field.setContent(lifetime); list.add(field); } //Add CAL Correlation ID String corrId = String.valueOf(UUID.randomUUID()); if(corrId != null){ //System.out.println("Correlation ID available+++++++++++++++++++++++++++++++++++++++++++"); MetaMessageCorrelationIDField field = new MetaMessageCorrelationIDField((byte) ((MetaMessageTagAndType.FieldType.CorrelationID.ordinal()) | (0 << 5))); field.setCorrelationId(corrId.getBytes()); list.add(field); } // Create request ID and add it UUID uuid = junoMsg.getReqId(); ByteBuffer buf = ByteBuffer.wrap(new byte[16]); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); MetaMessageFixedField field = new MetaMessageFixedField((byte) ((MetaMessageTagAndType.FieldType.RequestID.ordinal()) | (3 << 5))); field.setVariableContent(buf.array()); list.add(field); opMsg.getMetaComponent().setRequestId(buf.array()); // Add source info MetaMessageSourceField meta = new MetaMessageSourceField((byte) (MetaMessageTagAndType.FieldType.SourceInfo.ordinal())); if (junoMsg.getApplicationName() != null) { meta.setAppName(junoMsg.getApplicationName().getBytes()); } InetAddress localAddress = getLocalIp(); meta.setIp4(localAddress.getAddress()); meta.setPort(0); // Set this as 1 as of now. list.add(meta); //*************************** Form the Payload Component ********************** PayloadOperationMessage pp = new PayloadOperationMessage(0L, (byte) OperationMessage.Type.Payload.getValue()); pp.setKey(junoMsg.getKey()); pp.setKeyLength(junoMsg.getKey().length); pp.setNamespace(junoMsg.getNameSpace().getBytes()); pp.setNameSpaceLength((byte) junoMsg.getNameSpace().getBytes().length); byte [] payload = junoMsg.getValue(); if(junoMsg.isPayloadCompressed()){ pp.setCompressionType(junoMsg.getCompressionType()); } pp.setValue(payload); pp.setValueLength(payload == null ? 0 : payload.length); opMsg.setPayloadComponent(pp); int len = metaComponents.getBufferLength()+pp.getBufferLength()+16; opMsg.getHeader().setMessageSize(len); junoMsg.setMessageSize(len); return opMsg; } /** * This method decodes the Operation message got from Juno Server over the I/O channel and * creates the JunoMessage object. * @param opMsg - Operaion message got from Juno Server * @param key - Key of record * @return JunoMessage - Juno Message object */ public static JunoMessage decodeOperationMessage(OperationMessage opMsg, byte[] key, JunoClientConfigHolder configHolder) { JunoMessage message = new JunoMessage(); //Decode the Meta component if(opMsg.getMetaComponent() != null){ List<MetaMessageTagAndType> list = opMsg.getMetaComponent().getFieldList(); long createTime = 0; byte [] appName = null; long lifeTime = 0; long version = 0; long reqHandlingTime = 0; for (int i = 0; i < list.size(); i ++) { MetaMessageTagAndType type = list.get(i); MetaMessageTagAndType.FieldType fieldType = type.getFieldType(); MetaMessageFixedField src; switch (fieldType) { case CreationTime: src = (MetaMessageFixedField)type; createTime = src.getContent(); break; case Dummy: break; case ExpirationTime: break; case RequestID: break; case SourceInfo: MetaMessageSourceField infoSrc = (MetaMessageSourceField)type; appName = infoSrc.getAppName(); break; case TimeToLive: src = (MetaMessageFixedField)type; lifeTime = src.getContent(); break; case Version: src = (MetaMessageFixedField)type; version = src.getContent(); break; case RequestHandlingTime: src = (MetaMessageFixedField)type; reqHandlingTime = src.getContent(); break; default: break; } } message.setVersion((short) version); message.setTimeToLiveSec((int) lifeTime); message.setCreationTime(createTime); message.setApplicationName(configHolder.getApplicationName()); message.setReqHandlingTime(reqHandlingTime); } //Decode the Header int status = (int)opMsg.getHeader().getStatus(); message.setStatus(ServerOperationStatus.get(status)); //Decode the Payload Component PayloadOperationMessage pp = opMsg.getPayloadComponent(); message.setValue("".getBytes()); // Set empty payload and later override with actual if(pp != null){ if (pp.getValueLength() != 0) { if(pp.getCompressedType() == PayloadOperationMessage.CompressionType.Snappy){ try { message.setValue(Snappy.uncompress(pp.getValue())); } catch (IOException e) { // TODO What to do? throw new JunoException("Exception while uncompressing data. "+e.getMessage()); } }else{ message.setValue(pp.getValue()); } } message.setNameSpace(new String(pp.getNamespace())); if(Arrays.equals(key,pp.getKey())){ // Log CAL event for mismatch in key. It should not happen. } message.setKey(pp.getKey()); } // Populate the total message size for this operation message.setMessageSize(opMsg.getHeader().getMessageSize()); return message; } private static InetAddress getLocalIp(){ InetAddress localAddress; try{ localAddress = InetAddress.getLocalHost(); }catch(UnknownHostException e){ localAddress = InetAddress.getLoopbackAddress(); } return localAddress; } }
145
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/JunoMetrics.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.util; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Timer; import java.time.Duration; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JunoMetrics { private static final Logger log = LoggerFactory.getLogger("JunoMetrics"); public static final String JUNO_LATENCY_METRIC = "juno.client.operation"; public static final String JUNO_OPERATION_METRIC = "juno.client.operation.status"; public static final String SUCCESS="SUCCESS"; public static final String ERROR="ERROR"; public static final String WARNING="WARNING"; public static final String EXCEPTION="EXCEPTION"; public static final String TYPE = "type"; public static final String NAME = "name"; public static final String STATUS = "status"; public static final String ERROR_CAUSE = "cause"; public static final String METRIC_PREFIX = "juno.client."; public static final String CONNECT_METRIC = METRIC_PREFIX + "connect.count"; public static final String SPAN_METRIC = METRIC_PREFIX + "span"; public static final String EVENT_METRIC = METRIC_PREFIX + "event.count"; public static final String ERROR_METRIC = METRIC_PREFIX + "error.count"; private static final ConcurrentMap<String, ConcurrentMap<String,Timer>> successOpTimerMetricList = new ConcurrentHashMap(25); private static final ConcurrentMap<String, ConcurrentMap<String,Timer>> failureOpTimerMetricList = new ConcurrentHashMap(25); private Timer timer; private String timerName; private Timer.Builder builder; private JunoMetrics(){ } /** * To record timer based metric for Juno operations. It records the time for JUNO_SSL_CLIENT txns and its status * @param metricName - Name of the metric. "juno.client.txn_latency_ms * @param operation * @param status * @param timeInMs */ public static void recordOpTimer(String metricName, String operation,String pool, String status,long timeInMs){ try { ConcurrentMap<String,Timer> OpTimer = status==SUCCESS?successOpTimerMetricList.get(operation):failureOpTimerMetricList.get(operation); if (OpTimer == null) { OpTimer = new ConcurrentHashMap(5); Timer timer = createNewTimer(metricName,operation,pool,status); OpTimer.putIfAbsent(pool,timer); OpTimer = status==SUCCESS?successOpTimerMetricList.putIfAbsent(operation, OpTimer):failureOpTimerMetricList.putIfAbsent(operation, OpTimer); }else{ Timer timer = OpTimer.get(pool); if(timer == null){ Timer newTimer = createNewTimer(metricName,operation,pool,status); OpTimer.putIfAbsent(pool,newTimer); } } Timer timer = OpTimer.get(pool); timer.record(timeInMs, TimeUnit.MILLISECONDS); }catch(Exception e){ //Do not do anything Just log log.debug("Exception while recording timer metric: "+e.getMessage()); } } private static Timer createNewTimer(String metricName, String operation,String pool, String status){ Timer timer = Timer.builder(metricName) .tags("operation", operation, "pool",pool, "status", status) .serviceLevelObjectives(Duration.ofMillis(1), Duration.ofMillis(3), Duration.ofMillis(5), Duration.ofMillis(10), Duration.ofMillis(100), Duration.ofMillis(500), Duration.ofMillis(1000), Duration.ofMillis(5000)) .distributionStatisticExpiry(Duration.ofSeconds(10)) .distributionStatisticBufferLength(1) .register(Metrics.globalRegistry); return timer; } public static void recordTimer(String type, String name, String status, long timeInMs){ try { Timer.builder(SPAN_METRIC) .tags(TYPE, type, NAME, name, STATUS, status) .register(Metrics.globalRegistry) .record(timeInMs, TimeUnit.MILLISECONDS); }catch(Exception e){ //Do not do anything Just log log.debug("Exception while recording timer metric: "+e.getMessage()); } } public static void recordOpCount(String pool, String op_type, String errorType){ try { Counter counter = Counter .builder(JUNO_OPERATION_METRIC) .description("indicates instance count of the object") .tag("pool",pool) .tag("type",op_type) .tag("status", errorType) .tag("cause","none") .register(Metrics.globalRegistry); counter.increment(); }catch(Exception e){ //Do not do anything Just log log.debug("Exception while recording counter metric: "+e.getMessage()); } } public static void recordOpCount(String pool, String op_type, String errorType, String errorCause){ try { Counter counter = Counter .builder(JUNO_OPERATION_METRIC) .description("indicates instance count of the object") .tag("pool",pool) .tag("type",op_type) .tag("status",errorType) .tag("cause",errorCause) .register(Metrics.globalRegistry); counter.increment(); }catch(Exception e){ //Do not do anything Just log log.debug("Exception while recording counter metric: "+e.getMessage()); } } public static void recordConnectCount(String endpoint, String status, String cause) { try { Counter.builder(CONNECT_METRIC) .tags("endpoint", endpoint, STATUS, status, ERROR_CAUSE,cause) .register(Metrics.globalRegistry) .increment(); } catch (Exception e) { //Do not do anything Just log log.debug("Exception while recording timer metric: " + e.getMessage()); } } public static void recordEventCount(String type, String name, String status) { try { Counter.builder(EVENT_METRIC) .tags(TYPE, type, NAME, name, STATUS, status) .register(Metrics.globalRegistry) .increment(); } catch (Exception e) { //Do not do anything Just log log.debug("Exception while recording timer metric: " + e.getMessage()); } } public static void recordErrorCount(String type, String name, String cause){ try { Counter.builder(ERROR_METRIC) .tags(TYPE, type, NAME, name, ERROR_CAUSE, cause) .register(Metrics.globalRegistry) .increment(); }catch(Exception e){ //Do not do anything Just log log.debug("Exception while recording timer metric: "+e.getMessage()); } } }
146
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/SSLUtil.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.util; import java.io.*; import java.net.URL; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; import java.util.Base64; import java.util.List; import javax.net.ssl.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SSLUtil { private static Logger LOGGER = LoggerFactory.getLogger(SSLUtil.class); public static SSLContext getSSLContext() { SSLContext sslContext = null; InputStream crtInputStream = null; InputStream keyInputStream = null; URL crt = SSLUtil.class.getClassLoader().getResource("secrets/server.crt"); URL key = SSLUtil.class.getClassLoader().getResource("secrets/server.pem"); try { crtInputStream = crt.openStream(); keyInputStream = key.openStream(); if(crtInputStream != null && keyInputStream != null) LOGGER.info("Security Certificated Found! "); sslContext = createSSLFactory(keyInputStream, crtInputStream,"", "name"); } catch (Exception e) { LOGGER.debug("Exception occured " + e.getMessage()); } if(sslContext != null) LOGGER.info("SSLContext Instantiated! "); return sslContext; } public static SSLContext getSSLContext(String crtPath, String keyPath) { SSLContext sslContext = null; try { FileInputStream crtInputStream = new FileInputStream(crtPath); FileInputStream keyInputStream = new FileInputStream(keyPath); if(crtInputStream != null && keyInputStream != null) LOGGER.info("Security Certificated Found! "); sslContext = createSSLFactory(keyInputStream, crtInputStream,"", "name"); } catch (Exception e) { LOGGER.debug("Exception occured " + e.getMessage()); } if(sslContext != null) LOGGER.info("SSLContext Instantiated! "); return sslContext; } private static String readFileAsString(InputStream con) throws IOException { InputStreamReader st = new InputStreamReader(con, "utf-8"); BufferedReader in = new BufferedReader(st); String content = ""; do { String line = in.readLine(); if (line == null) { break; } if (line.contains("BEGIN") && content.isEmpty()) { content += line + "\n"; } else if (line.contains("END") && !content.isEmpty()) { content += "\n" + line; } else { content += line; } } while (true); return content; } private static SSLContext createSSLFactory(InputStream crtPath, InputStream keyPath, String password, String name) throws Exception { String privateKeyPem = readFileAsString(crtPath); String certificatePem = readFileAsString(keyPath); // Convert public certificates and private key into KeyStore final KeyStore keystore = createKeyStore(privateKeyPem, certificatePem, password, name); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, password.toCharArray()); final KeyManager[] km = kmf.getKeyManagers(); final SSLContext context = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) { // Since we only use this in client side, this // method will not be used. LOGGER.info("No client cert verification"); } public void checkServerTrusted(X509Certificate[] chain, String authType) { LOGGER.info("No server cert verification"); } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; TrustManager[] trustAllCerts = new TrustManager[] {tm}; context.init(km, trustAllCerts, null); return context; } private static KeyStore createKeyStore(String privateKeyPem, String certificatePem, final String password, String name) throws Exception, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { final X509Certificate[] cert = createCertificates(certificatePem); final KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(null); // Import private key final PrivateKey key = createPrivateKey(privateKeyPem); keystore.setKeyEntry(name, key, password.toCharArray(), cert); return keystore; } private static PrivateKey createPrivateKey(String privateKeyPem) throws Exception { final Reader reader = new StringReader(privateKeyPem); BufferedReader r = new BufferedReader(reader); String s = r.readLine(); if (s == null || !s.contains("BEGIN PRIVATE KEY")) { r.close(); throw new IllegalArgumentException("No PRIVATE KEY found"); } final StringBuilder b = new StringBuilder(); s = ""; while (s != null) { if (s.contains("END PRIVATE KEY")) { break; } b.append(s); s = r.readLine(); } r.close(); final String hexString = b.toString(); final byte[] bytes = Base64.getDecoder().decode(hexString); return generatePrivateKeyFromDER(bytes); } private static X509Certificate[] createCertificates(String certificatePem) throws Exception { final List<X509Certificate> result = new ArrayList<X509Certificate>(); final Reader reader = new StringReader(certificatePem); BufferedReader r = new BufferedReader(reader); String s = r.readLine(); if (s == null || !s.contains("BEGIN CERTIFICATE")) { r.close(); throw new IllegalArgumentException("No CERTIFICATE found"); } StringBuilder b = new StringBuilder(); while (s != null) { if (s.contains("END CERTIFICATE")) { String hexString = b.toString(); final byte[] bytes = Base64.getDecoder().decode(hexString); X509Certificate cert = generateCertificateFromDER(bytes); result.add(cert); b = new StringBuilder(); } else { if (!s.startsWith("----")) { b.append(s); } } s = r.readLine(); } r.close(); return result.toArray(new X509Certificate[result.size()]); } private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException { final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); final KeyFactory factory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) factory.generatePrivate(spec); } private static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException { final CertificateFactory factory = CertificateFactory.getInstance("X.509"); return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes)); } }
147
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/util/JunoLogLevel.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.util; import ch.qos.logback.classic.Level; public enum JunoLogLevel { DEFAULT(-1, Level.WARN, java.util.logging.Level.WARNING), DEBUG(0, Level.DEBUG, java.util.logging.Level.FINE), INFO(1, Level.INFO, java.util.logging.Level.INFO), WARN(2, Level.WARN, java.util.logging.Level.WARNING), ERROR(3, Level.ERROR, java.util.logging.Level.SEVERE), FATAL(4, Level.ERROR, JunoLogLevelExtension.FATAL), CONFIG(5, Level.INFO, java.util.logging.Level.CONFIG), FINE(6, Level.DEBUG, java.util.logging.Level.FINE), FINER(7, Level.DEBUG, java.util.logging.Level.FINER), FINEST(8, Level.TRACE,java.util.logging.Level.FINEST), ALL(9, Level.ALL, java.util.logging.Level.ALL), OFF(10, Level.OFF,java.util.logging.Level.OFF); private int m_junoLevel; private Level m_logbackLevel; private java.util.logging.Level m_jdkJunoLogLevel; private JunoLogLevel (int junoLevel, Level logbackLevel, java.util.logging.Level jdkJunoLogLevel) { m_junoLevel = junoLevel; m_logbackLevel = logbackLevel; m_jdkJunoLogLevel = jdkJunoLogLevel; } public Level getLogbackLevel() { return m_logbackLevel; } public int getLogbackLevelValue() { return m_logbackLevel.toInt(); } public int getjunoLevelValue() { return m_junoLevel; } public java.util.logging.Level getLevel() { return m_jdkJunoLogLevel; } public int getLevelValue() { return m_jdkJunoLogLevel.intValue(); } private static class JunoLogLevelExtension extends java.util.logging.Level { public final static java.util.logging.Level FATAL = new JunoLogLevel.JunoLogLevelExtension("FATAL", 1100); protected JunoLogLevelExtension(String name, int value) { super(name, value, null); } private static final long serialVersionUID = 9149560934874662806L; } }
148
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/MetaMessageSourceField.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.io.protocol; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MetaMessageSourceField extends MetaMessageTagAndType { private static final Logger logger = LoggerFactory.getLogger(MetaMessageSourceField.class); private byte componentSize; private byte appNameLength; // include one bit for ip type private boolean isIP6; private int port; // 2 bytes private byte [] ip4; // 4 bytes private byte [] ip6; private byte [] appName; // 4 bytes padding public int getPort() { return port; } public void setPort(int port) { this.port = port; } public byte[] getIp4() { return ip4; } public void setIp4(byte[] ip4) { this.ip4 = ip4; } public static String getIp4String(byte[] w) { if (w == null || w.length < 4) { return new String(""); } return (int)(w[0] & 0xff) + "." + (int)(w[1] & 0xff) + "." + (int)(w[2] & 0xff) + "." + (int)(w[3] & 0xff); } public byte[] getAppName() { return appName; } public int getBufferLength() { componentSize = (byte) (1 + 1 + 2 + (this.isIP6 ? 16 : 4) + ((appName == null) ? 0 : appName.length)); int offset = componentSize % 4; if (offset != 0) { componentSize += 4 - offset; } return componentSize; } public void setAppName(byte[] appName) { this.appName = appName; appNameLength = (byte)appName.length; } public MetaMessageSourceField(byte tagAndSizeType) { super(tagAndSizeType); } public MetaMessageSourceField readBuf(ByteBuf in) { int index = in.readerIndex(); componentSize = in.readByte(); appNameLength = in.readByte(); this.isIP6 = (appNameLength & 0x80) == 0x80; appNameLength = (byte) (appNameLength & 0x7F); port = in.readUnsignedShort(); // int if (this.isIP6) { ip6 = new byte[16]; in.readBytes(ip6); } else { ip4 = new byte[4]; in.readBytes(ip4); } appName = new byte[appNameLength]; in.readBytes(appName); int tail = index + ((int)(componentSize & 0xff) - in.readerIndex()); //Skip the padding if any if (tail > 0) { ByteBuf buf = in.readBytes(tail); buf.release(); } return this; } public void writeBuf(ByteBuf out) { int indexStart = out.writerIndex(); out.writeByte(componentSize); out.writeByte((byte)(appNameLength | (this.isIP6 ? 0x80 : 0))); out.writeShort((short)port); if (this.isIP6) { Assert.isTrue("IP6",ip6 != null); out.writeBytes(ip6); } else { out.writeBytes(ip4); } if (appName != null) { out.writeBytes(appName); if (logger.isDebugEnabled()) { logger.debug("Application Name: " + new String(appName)); } } // Add padding if needed OperationMessage.writeBufPadding(indexStart, out, 4); } }
149
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/MetaMessageCorrelationIDField.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.io.protocol; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * Correlation ID field structure. Correlation ID field Tag : 0x09 SizeType: 0x0 Tag: 0x09 +----+------------------------------------------- | 0 | field size (including padding) +----+------------------------------------------- | 1 | octet sequence length +----+------------------------------------------- | | octet sequence, padding to 4-byte aligned +----+------------------------------------------- */ public class MetaMessageCorrelationIDField extends MetaMessageTagAndType { private static final Logger logger = LoggerFactory.getLogger(MetaMessageSourceField.class); private byte componentSize; private byte correlationIdLength; private byte [] correlationId; // 4 bytes padding public void setCorrelationId(byte[] correlationId) { this.correlationId = correlationId; this.correlationIdLength = (byte)correlationId.length; componentSize = (byte) (1 + 1 + correlationId.length); // 1 byte is for total size and 1 byte for correlationId length //Add padding for size if the total size if not a multiple of 4 int offset = componentSize % 4; if (offset != 0) { componentSize += 4 - offset; } } public int getBufferLength() { return componentSize; } public byte[] getCorrelationId() { return correlationId; } public static Logger getLogger() { return logger; } public MetaMessageCorrelationIDField(byte tagAndSizeType) { super(tagAndSizeType); } public void writeBuf(ByteBuf out) { int indexStart = out.writerIndex(); out.writeByte(componentSize); out.writeByte(correlationIdLength); if (correlationId != null) { out.writeBytes(correlationId); } //Add padding if needed OperationMessage.writeBufPadding(indexStart, out, 4); } }
150
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/OperationMessage.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.io.protocol; import com.paypal.juno.exception.JunoException; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OperationMessage { private static final Logger logger = LoggerFactory.getLogger(OperationMessage.class); // Payload Tag/ID: 0x01 // Meta Tag/ID: 0x02 public static enum Type { Payload(0x1), Meta(0x02); int type; Type(int type) { this.type = type; } public int getValue(){ return type; } } private MessageHeader header = null; private PayloadOperationMessage payloadComponent; private MetaOperationMessage metaComponent; private String serverIp; public MessageHeader getHeader() { return header; } public void setHeader(MessageHeader header) { this.header = header; } public int getLength() { return (int)getHeader().getMessageSize(); } public PayloadOperationMessage getPayloadComponent() { return payloadComponent; } public void setPayloadComponent(PayloadOperationMessage payloadComponent) { this.payloadComponent = payloadComponent; } public MetaOperationMessage getMetaComponent() { return metaComponent; } public void setMetaComponent(MetaOperationMessage metaComponent) { this.metaComponent = metaComponent; } public String getServerIp() { return serverIp; } public void setServerIp(String serverIp) { this.serverIp = serverIp; } // Read the message body which may have an set of components. There are currently // two types of components one is Payload and other is Metadata. The 1 byte tag // indicates the type of component. // ** Component ** // // +-----------------------+-------------------------+-----------------+----------------+--------------+ // | 4-byte component size | 1 byte component Tag/ID | component header| component body | padding to 8 | // +-----------------------+-------------------------+-----------------+----------------+--------------+ public OperationMessage readBuf(ByteBuf in) { if (logger.isDebugEnabled()) { logger.debug("Index position: " + in.readerIndex()); } int start = in.readerIndex(); if (this.header == null) { this.header = new MessageHeader(); header.readBuf(in); } long total = start + header.getMessageSize() - MessageHeader.size(); int index = in.readerIndex(); while (total - in.readerIndex() > 0) { long componentSize = in.readUnsignedInt(); // long byte tag = in.readByte(); switch (OperationMessage.Type.values()[(short)(tag & 0xff) - 1]) { case Payload: this.payloadComponent = new PayloadOperationMessage(componentSize, tag); payloadComponent.readBuf(in); break; case Meta: metaComponent = new MetaOperationMessage(componentSize, tag); metaComponent.readBuf(in); break; default: throw new JunoException("Invalid type"); } if (logger.isDebugEnabled()) { logger.debug("Reader Index: " + in.readerIndex() + "; header length: " + MessageHeader.size()); } readBufPadding(index, in, 8); index = in.readerIndex(); } return this; } public void writeBuf(ByteBuf out) { int size = 0; //Check if the meta component is not null if (metaComponent != null) { size += metaComponent.getBufferLength();; } //Check if the payload component is not null if (payloadComponent != null) { size += payloadComponent.getBufferLength(); } int offset = size % 8; if (offset != 0) { size += (8 - offset); } size += MessageHeader.size(); header.setMessageSize(size); // Header header.writeBuf(out); //Add meta Component int index = out.writerIndex(); if(metaComponent != null){ metaComponent.writeBuf(out); writeBufPadding(index, out, 8); } //Add Payload Component index = out.writerIndex(); if (payloadComponent != null) { payloadComponent.writeBuf(out); writeBufPadding(index, out, 8); } } static public void readBufPadding(int start, ByteBuf in, int padding) { int endIndex = in.readerIndex(); int offset = (endIndex - start) % padding; if (offset != 0) { ByteBuf buf = in.readBytes(padding - offset); buf.release(); } } static public void writeBufPadding(int start, ByteBuf out, int padding) { int endIndex = out.writerIndex(); int offset = (endIndex - start) % padding; if (offset != 0) { out.writeZero(padding - offset); } } }
151
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/MetaMessageTagAndType.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.io.protocol; import io.netty.buffer.ByteBuf; import java.nio.ByteBuffer; // This class represents the MetaData Component public class MetaMessageTagAndType { public enum FieldType { Dummy(0x0), TimeToLive (0x1), Version(0x2), CreationTime(0x3), ExpirationTime(0x4), RequestID(0x5), SourceInfo(0x6), LastModificationTime(0x7), OriginatorReqID(0x8), CorrelationID(0x9), RequestHandlingTime(0xa); FieldType(int type) { } }; final private FieldType fieldType; final private byte fieldSize; final private boolean isVariable; public boolean isVariable() { return isVariable; } public MetaMessageTagAndType(byte tagAndSizeType) { byte tmp = (byte)(0xFF & tagAndSizeType); // Check if the Field Tag is not in our enum then mark it Dummy to skip it. if((tmp & 0x1F) > 0xa){ fieldType = FieldType.values()[0]; }else{ //System.out.println("The tmp is:"+((tmp & 0x1F))); fieldType = FieldType.values()[(tmp & 0x1F)]; } if ((tmp >> 5) == 0) { this.isVariable = true; fieldSize = 0; } else { fieldSize = (byte) (tmp >> 5); this.isVariable = false; } } public FieldType getFieldType() { return fieldType; } public byte getFieldSize() { byte rt = (byte) (1 << (1 + fieldSize)); return rt; } public byte getValue() { byte value = (byte) (fieldType.ordinal()); if (!this.isVariable) { value |= fieldSize << 5; } return value; } // Will be overridden by the sub class public void writeValue(ByteBuffer out) { //byte value = (byte) ((fieldType.ordinal() + 1) | ((fieldSize) << 5)); //out.put(value); } public void writeBuf(ByteBuf out) { throw new RuntimeException("writeBuf not implemented in sub class."); } // Will be overridden by the sub class public int getBufferLength() { return 0; } }
152
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/MetaOperationMessage.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.io.protocol; import io.netty.buffer.ByteBuf; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** ** MetaData Component ** A variable length header followed by a set of meta data fields Tag/ID: 0x02 * Header * | 0| 1| 2| 3| 4| 5| 6| 7| 0 | size | 4 bytes ----+-----------------------+--------- 4 | Tag/ID (0x02) | 1 byte ----+-----------------------+--------- 5 | Number of fields | 1 byte ----+--------------+--------+--------- 6 | Field tag |SizeType| 1 byte ----+--------------+--------+--------- | ... | ----+-----------------------+--------- | padding to 4 | ----+-----------------------+--------- (Don't think we need a header size. ) SizeType: 0 variable length field, for that case, the first 1 byte of the field MUST be the size of the field(padding to 4 byte). The max is 255. n Fixed length: 2 ^ (n+1) bytes * Body * ----+-----------------------+--------- | Field data | defined by Field tag ----+-----------------------+--------- | ... | ----+-----------------------+--------- | padding to 8 | ----+-----------------------+--------- * Predefined Field Types * TimeToLive Field Tag : 0x01 SizeType: 0x01 Version Field Tag : 0x02 SizeType: 0x01 Creation Time Field Tag : 0x03 SizeType: 0x01 Expiration Time Field Tag : 0x04 SizeType: 0x01 RequestID/UUID Field Tag : 0x05 SizeType: 0x03 Source Info Field Tag : 0x06 SizeType: 0 | 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| | 0| 1| 2| 3| +-----------+-----------+--------------------+--+-----------------------+-----------------------+ | size (include padding)| app name length | T| Port | +-----------------------+--------------------+--+-----------------------------------------------+ | IPv4 address if T is 0 or IPv6 address if T is 1 | +-----------------------------------------------------------------------------------------------+ | application name, padding to 4-bytes aligned | +-----------------------------------------------------------------------------------------------+ */ public class MetaOperationMessage { public long getComponentSize() { return componentSize; } // Not for serialize/deserialize long version; long ttl; long creationTime; long expirationTime; long requestHandlingTime; // millisecond duration on JunoServ byte[] requestId; UUID requestUuid; long componentSize; final byte tag; // serialize/deserialize final private List<MetaMessageTagAndType> fieldList = new ArrayList<>(); public List<MetaMessageTagAndType> getFieldList() { return fieldList; } public MetaOperationMessage(long componentSize, byte tag) { this.componentSize = componentSize; this.tag = tag; } public long getVersion() { return version; } public long getTtl() { return ttl; } public long getCreationTime() { return creationTime; } public long getExpirationTime() { return expirationTime; } public long getRequestHandlingTime() { return requestHandlingTime; } public byte[] getRequestId() { return requestId; } public UUID getRequestUuid(){ return requestUuid; } public String getRequestIdString() { if (requestUuid == null) { return new String("not_set"); } return requestUuid.toString(); } public void setRequestId(byte [] reqId) { requestId = reqId; if(requestUuid == null){ ByteBuffer buf = ByteBuffer.wrap(requestId); UUID uuid = new UUID(buf.getLong(0), buf.getLong(8)); requestUuid = uuid; } } public void setRequestUuid(UUID id) { requestUuid = id; if(requestId == null){ ByteBuffer buf = ByteBuffer.wrap(new byte[16]); buf.putLong(id.getMostSignificantBits()); buf.putLong(id.getLeastSignificantBits()); requestId = buf.array(); } } public String getCorrelationIDString() { byte[] id = null; for (int i = 0; i < fieldList.size(); i++) { MetaMessageTagAndType item = fieldList.get(i); if (item instanceof MetaMessageCorrelationIDField) { id = ((MetaMessageCorrelationIDField)item).getCorrelationId(); break; } } if (id == null) { return new String("not_set"); } return new String(id); } public void addSourceField(byte[] ip4, int port, byte[] appName) { MetaMessageSourceField source = new MetaMessageSourceField((byte) (MetaMessageTagAndType.FieldType.SourceInfo.ordinal())); source.setIp4(ip4); source.setPort(port); source.setAppName(appName); fieldList.add(source); } public MetaMessageSourceField getSourceField() { for (int i = 0; i < fieldList.size(); i++) { MetaMessageTagAndType item = fieldList.get(i); if (item instanceof MetaMessageSourceField) { return (MetaMessageSourceField)item; } } return null; } public int getBufferLength() { // Header // componentSize(4) + tag(1) + Number of fields(1) + number Of fields bytes + padding 4 int size = 6 + this.fieldList.size(); int offset = size % 4; if (offset != 0) { size += 4 - offset; } // Data for (int i = 0; i < this.fieldList.size(); i ++) { MetaMessageTagAndType tagAndSizeType = this.fieldList.get(i); if (!tagAndSizeType.isVariable()) { size += tagAndSizeType.getFieldSize(); } else { size += (tagAndSizeType).getBufferLength(); } } offset = size % 8; if (offset != 0) { size += 8 - offset; } this.componentSize = size; return size; } public MetaOperationMessage readBuf(ByteBuf in) { int indexStart = in.readerIndex(); short fields = in.readUnsignedByte(); byte [] tagAndSizeTypes = new byte[fields]; in.readBytes(tagAndSizeTypes); // Header is done // escape padding here, padding to 4 bytes. OperationMessage.readBufPadding(indexStart - 4 - 1 , in, 4); for (int i = 0; i < fields; i ++) { MetaMessageTagAndType tagAndSizeType = new MetaMessageTagAndType(tagAndSizeTypes[i]); MetaMessageTagAndType.FieldType type = tagAndSizeType.getFieldType(); switch(type) { case CreationTime: case ExpirationTime: case RequestHandlingTime: case RequestID: case TimeToLive: case Version: { MetaMessageFixedField field = new MetaMessageFixedField(tagAndSizeTypes[i]); field.readBuf(in); fieldList.add(field); if(type.equals(MetaMessageTagAndType.FieldType.CreationTime)){ creationTime=field.getContent(); }else if(type.equals(MetaMessageTagAndType.FieldType.ExpirationTime)){ expirationTime=field.getContent(); }else if(type.equals(MetaMessageTagAndType.FieldType.RequestHandlingTime)) { requestHandlingTime=field.getContent(); }else if(type.equals(MetaMessageTagAndType.FieldType.RequestID)){ setRequestId(field.getVariableContent()); }else if(type.equals(MetaMessageTagAndType.FieldType.TimeToLive)){ ttl=field.getContent(); }else if(type.equals(MetaMessageTagAndType.FieldType.Version)){ version=field.getContent(); } break; } case SourceInfo: { MetaMessageSourceField field = new MetaMessageSourceField(tagAndSizeTypes[i]); field.readBuf(in); fieldList.add(field); break; } // case CorrelationID: { // MetaMessageCorrelationIDField field = new MetaMessageCorrelationIDField(tagAndSizeTypes[i]); // field.readBuf(in); // fieldList.add(field); // break; // } default: //Here we just need to skip the bytes for unknown Field type if(tagAndSizeType.isVariable()){ short size = in.readUnsignedByte(); // The size of the variable length tag is found at the first byte of the Tag body ByteBuf buf = in.readBytes(size - 1); //Since the size if inclusive of itself so (size - 1). buf.release(); }else{ int len = tagAndSizeType.getFieldSize(); ByteBuf buf = in.readBytes(len); buf.release(); } break; } } return this; } public void writeBuf(ByteBuf out) { //Populate the Header int indexStart = out.writerIndex(); out.writeInt((int) this.componentSize); out.writeByte(this.tag); out.writeByte((byte)this.fieldList.size()); //Write the field Tag and Size Type fields for (int i = 0; i < this.fieldList.size(); i ++) { byte value = this.fieldList.get(i).getValue(); out.writeByte(value); } // Add padding if necessary OperationMessage.writeBufPadding(indexStart, out, 4); // Write the actual Meta data (Body) for (int i = 0; i < this.fieldList.size(); i ++) { MetaMessageTagAndType field = this.fieldList.get(i); field.writeBuf(out); } } }
153
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/Assert.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.io.protocol; public class Assert { public static void isTrue(String msg, boolean expression) { if (!expression) { throw new IllegalArgumentException("[Assertion failed] - this expression must be true. " + msg); } } }
154
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/JunoMessage.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.io.protocol; import com.paypal.juno.client.ServerOperationStatus; import com.paypal.juno.io.protocol.PayloadOperationMessage.CompressionType; import java.util.UUID; public class JunoMessage { private byte[] key; private byte[] value; private long version; private long expiry; private long timeToLiveSec; private String nameSpace; private String applicationName; private OperationType opType; private ServerOperationStatus status; private long creationTime; private long reqStartTime; private long reqHandlingTime; // millisecond duration on JunoServ private long messageSize; private UUID reqId; private boolean isPayloadCompressed; private int compressionAchieved; private CompressionType compressionType; public enum OperationType { Nop(0,"NOP"), Create(1,"CREATE"), Get(2,"GET"), Update(3,"UPDATE"), Set(4,"SET"), CompareAndSet(5,"COMPAREANDSET"), Destroy(6,"DESTROY"); private final int code; private final String opType; /** * Constructor * * @param code * @param opText Type */ OperationType(int code, String opText) { this.code = code; this.opType = opText; } public int getCode() { return code; } public String getOpType() { return opType; } }; public JunoMessage(){ } public JunoMessage(byte[] key, byte[] value, long version,long expiry,long ttl,OperationType opType){ this.key = key; this.value = value; this.version = version; this.expiry = expiry; this.timeToLiveSec = ttl; this.opType = opType; } public byte[] getValue() { return value; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public long getExpiry() { return expiry; } public void setExpiry(long expiry) { this.expiry = expiry; } public long getTimeToLiveSec() { return timeToLiveSec; } public void setTimeToLiveSec(long timeToLiveSec) { this.timeToLiveSec = timeToLiveSec; } public void setValue(byte[] value) { this.value = value; } public byte[] getKey() { return key; } public void setKey(byte[] key) { this.key = key; } public OperationType getOpType() { return opType; } public void setOpType(OperationType opType) { this.opType = opType; } public ServerOperationStatus getStatus() { return status; } public void setStatus(ServerOperationStatus status) { this.status = status; } public String getNameSpace() { return nameSpace; } public void setNameSpace(String nameSpace) { this.nameSpace = nameSpace; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public long getCreationTime() { return creationTime; } public void setCreationTime(long creationTime) { this.creationTime = creationTime; } public long getReqStartTime() { return reqStartTime; } public void setReqStartTime(long reqStartTime) { this.reqStartTime = reqStartTime; } public void setReqHandlingTime(long rht) { this.reqHandlingTime = rht; } public long getReqHandlingTime() { return reqHandlingTime; } public long getMessageSize() { return messageSize; } public void setMessageSize(long messageSize) { this.messageSize = messageSize; } public UUID getReqId() { return reqId; } public void setReqId(UUID reqId) { this.reqId = reqId; } public boolean isPayloadCompressed() { return isPayloadCompressed; } public void setPayloadCompressed(boolean isPayloadCompressed) { this.isPayloadCompressed = isPayloadCompressed; } public int getCompressionAchieved() { return compressionAchieved; } public void setCompressionAchieved(int compressionAchieved) { this.compressionAchieved = compressionAchieved; } public CompressionType getCompressionType() { return compressionType; } public void setCompressionType(CompressionType compressionType) { this.compressionType = compressionType; } }
155
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/MessageHeader.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.io.protocol; import com.paypal.juno.exception.JunoException; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // // Message header // It comprises of the Protocol Header and Operational messager header public class MessageHeader { private static final Logger logger = LoggerFactory.getLogger(PayloadOperationMessage.class); private static final int MESSAGE_HEADER_MAGIC = 0x5050; private static final short PROTOCOL_VERSION = 1; /** * MESSAGE_HEADER_MAGIC * * Unsigned16 */ private int magic = 0; /** * version of entire serialized message * * Unsigned8 */ private short version = 0; /** * msgType of serialized message * * Unsigned8 */ private short msgType = 0; /** * msgType of serialized message * * Unsigned8 */ private short messageRQ = 0; /** * Size of the operationMsg * * Unsigned32 */ private int messageSize = 0; /** * Opaque of the message * * Unsigned32 */ private int opaque = 0; /** * Opcode of the message * * opcode list: * 0x00 Nop * 0x01 Create * 0x02 Get * 0x03 Update * 0x04 Set * 0x05 Destroy * 0x81 PrepareCreate * 0x82 Read * 0x83 PrepareUpdate * 0x84 PrepareSet * 0x85 Delete * 0xC1 Commit * 0xC2 Abort (Rollback) * 0xC3 Repair * 0xFE MockSetParam * oxFF MockReSet * Unsigned8 */ private short opcode; /** * flags of the message * * Value - 1 if it is for replication * Unsigned8 */ private short flags; /** * vbucket id * * Unsigned16 */ private int vbucket; /** * Opaque of the message * * Unsigned8 */ private short status; public MessageHeader() { this.magic = MESSAGE_HEADER_MAGIC; this.version = PROTOCOL_VERSION; //bit 0-5 //Message Type //0: Operational Message //1: Admin Message //2: Cluster Control Message this.msgType = (short)MessageType.OperationalMessage.ordinal(); // bit 6-7 //RQ flag //0: response //1: two way request //3: one way request this.messageRQ = (short)MessageRQ.TwoWayRequest.ordinal(); this.flags = 0; } public short getMagic() { return (short)magic; } public int getMessageSize() { return messageSize; } public void setMessageSize(int messageSize) { this.messageSize = messageSize; } /** * @param version * the version to set */ public void setVersion(short version) { this.version = version; } /** * @param msgType * the msgType to set */ public void setMsgType(short msgType) { this.msgType = msgType; } /** * @param messageRQ * the messageRQ to set */ public void setMessageRQ(short messageRQ) { this.messageRQ = messageRQ; } /** * @return the opaque */ public int getOpaque() { return opaque; } /** * @param opaque * the opaque to set */ public void setOpaque(int opaque) { this.opaque = opaque; } /** * @return the opcode */ public short getOpcode() { return opcode; } /** * @param opcode the opcode to set */ public void setOpcode(short opcode) { this.opcode = opcode; } /** * @param flags the flags to set */ public void setFlags(short flags) { this.flags = flags; } /** * @return the status */ public short getStatus() { return status; } /** * @param status the status to set */ public void setStatus(short status) { this.status = status; } /** * @param magic the magic to set */ public void setMagic(short magic) { this.magic = magic; } public static int size() { return 16; } static public enum MessageOpcode { Nop(0x0), Create(0x1), Get(0x2), Update(0x3), Set(0x4), Destroy(0x5), PrepareCreate(0x81), Read(0x82), PrepareUpdate(0x83), PrepareSet(0x84), PrepareDelete(0x85), Delete(0x86), Commit(0xC1), Abort(0xC2), Repair(0xC3), MarkDelete(0xC4), Clone(0xE1), MockSetParam(0xFE), MockReSet(0xFF); MessageOpcode(int type) { } } public static enum MessageRQ { Response(0), TwoWayRequest(1), OneWayRequest(2); MessageRQ(int type) { } } public static enum MessageType { OperationalMessage(0), AdminMessage(1), CluisterControlMessage(2); MessageType(int type) { } } // Here we are creating the Protocol header and Opertional message header (request to proxy) // Protocol Header - 12 bytes //---------------- // | 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| // byte | 0| 1| 2| 3| //------+-----------------------+-----------------------+-----------------------+-----------------------+ // 0 | magic | version | message type flag | // | | +-----------------+-----+ // | | | type | RQ | //------+-----------------------------------------------+-----------------------+-----------------+-----+ // 4 | message size | //------+-----------------------------------------------------------------------------------------------+ // 8 | opaque | //------+-----------------------------------------------------------------------------------------------+ // // Operational Message Header - 4 bytes //--------------------------- // operational request header // |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7| // byte | 0| 1| 2| 3| //------+---------------+---------------+---------------+---------------+ // 0 | opcode |flag | shard Id or vbucket | // | +-+-------------+ | // | |R| | | //------+---------------+-+-------------+-------------------------------+ // // shared ID or vbucket does not have any significance for this client. Only proxy // will set this field when sending request to SS. // public void writeBuf(ByteBuf out) { out.writeShort((short) getMagic()); out.writeByte((byte) version); byte tmp = (byte) msgType; tmp |= (messageRQ << 6); out.writeByte(tmp); out.writeInt(messageSize); out.writeInt(opaque); out.writeByte((byte) opcode); if (logger.isDebugEnabled()) { logger.debug("Operation: " + opcode); //logger.debug("namespace: " + new String(namespace)); } out.writeByte((byte) flags); if(messageRQ == MessageRQ.Response.ordinal()){ out.writeShort(status); } else { out.writeShort((short) (vbucket & 0xFFFF)); } } // Here we are parsing in the Protocol header and Opertional message header(response from proxy) // Protocol Header 12 bytes //---------------- // | 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| 0| 1| 2| 3| 4| 5| 6| 7| // byte | 0| 1| 2| 3| //------+-----------------------+-----------------------+-----------------------+-----------------------+ // 0 | magic | version | message type flag | // | | +-----------------+-----+ // | | | type | RQ | //------+-----------------------------------------------+-----------------------+-----------------+-----+ // 4 | message size | //------+-----------------------------------------------------------------------------------------------+ // 8 | opaque | //------+-----------------------------------------------------------------------------------------------+ // // Operational Message Header 4 bytes //--------------------------- // // operational response header // |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7| // byte | 0| 1| 2| 3| //------+---------------+---------------+---------------+---------------+ // 0 | opcode |flag | reserved | status | // | +-+-------------+ | | // | |R| | | | //------+---------------+-+-------------+---------------+---------------+ public MessageHeader readBuf(ByteBuf in) throws JunoException { this.magic = in.readShort(); // int //System.out.println("Magic is:"+this.magic); Assert.isTrue("Magic check ", MESSAGE_HEADER_MAGIC == this.magic); this.version = in.readUnsignedByte(); // short short tmp = in.readUnsignedByte(); // short this.msgType = (short)(tmp & 0x3f); this.messageRQ = (short)(tmp >> 6); this.messageSize = in.readInt(); // int //System.out.println("message size is:"+this.messageSize); this.opaque = in.readInt(); // int this.opcode = in.readUnsignedByte(); // short this.flags = in.readUnsignedByte(); // short in.readByte(); this.status = in.readUnsignedByte(); // short return this; } }
156
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/MetaMessageFixedField.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.io.protocol; import io.netty.buffer.ByteBuf; public class MetaMessageFixedField extends MetaMessageTagAndType { private long content; private byte [] variableContent; public long getContent() { return content; } public void setContent(long content) { this.content = content; } public byte[] getVariableContent() { return variableContent; } public void setVariableContent(byte[] variableContent) { this.variableContent = variableContent; } public MetaMessageFixedField(byte tagAndSizeType) { super(tagAndSizeType); } public MetaMessageFixedField readBuf(ByteBuf in) { int size = this.getFieldSize(); if (size == 4) { this.content = in.readUnsignedInt(); // long } else { variableContent = new byte [size]; in.readBytes(variableContent); } return this; } public void writeBuf(ByteBuf out) { int size = this.getFieldSize(); if (size == 4) { int value = (int) (0xFFFFFFFF & content); out.writeInt(value); } else { out.writeBytes(variableContent); } } public int getLength() { if (variableContent != null) { return variableContent.length; } else { return 4; } } }
157
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/io/protocol/PayloadOperationMessage.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.io.protocol; import io.netty.buffer.ByteBuf; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Payload (or KeyValue) Component is a type in which we will have the Namespace, key and value fileds. */ public class PayloadOperationMessage { private static final Logger logger = LoggerFactory.getLogger(PayloadOperationMessage.class); private long componentSize; private final byte tag; private long valueLength; private byte nameSpaceLength; private int keyLength; private byte[] namespace; private byte[] key; private byte[] value; private boolean isPloadCompressed; private CompressionType compType; public enum CompressionType { None("None"), Snappy("Snappy"); // More algorithm to be added in future private final String cmpType; private static final Map<String, CompressionType> lookup = new HashMap<String, CompressionType>(); static { for (CompressionType s : EnumSet .allOf(CompressionType.class)) lookup.put(s.getCompressionType(), s); } CompressionType(String cmpText) { this.cmpType = cmpText; } public String getCompressionType() { return cmpType; } public static CompressionType getCompressionType(String ctype){ return lookup.get(ctype); } }; public long getValueLength() { return valueLength; } public void setValueLength(long valueLength) { this.valueLength = valueLength; } public byte getNameSpaceLength() { return nameSpaceLength; } public void setNameSpaceLength(byte nameSpaceLength) { this.nameSpaceLength = nameSpaceLength; } public int getKeyLength() { return keyLength; } public void setKeyLength(int keyLength) { this.keyLength = keyLength; } public byte[] getNamespace() { return namespace; } public void setNamespace(byte[] namespace) { this.namespace = namespace; this.nameSpaceLength = (byte) this.namespace.length; getBufferLength(); // Calculate the buffer length immediatly } public byte[] getKey() { return key; } public void setKey(byte[] key) { this.key = key; this.keyLength = this.key.length; } public byte[] getValue() { return value; } public void setValue(byte[] value) { this.value = value; this.valueLength = this.value == null ? 0 : this.value.length; } public CompressionType getCompressedType() { return this.compType; } public void setCompressionType(CompressionType compressionType) { this.compType = compressionType; if(compressionType == CompressionType.None){ this.isPloadCompressed = false; }else{ this.isPloadCompressed = true; } } public PayloadOperationMessage(long componentSize, byte tag) { this.componentSize = componentSize; this.tag = tag; this.isPloadCompressed = false; this.compType = CompressionType.None; } public int getBufferLength() { // componentSize(4) + tag(1) + this.nameSpaceLength(1) + // key(2) + value(4) long valueFieldLen = 0; // TO DO. Optimize this section when adding more compression types if(this.valueLength != 0){ valueFieldLen = this.valueLength + 1; // 1 byte for payload type if(this.isPloadCompressed){ // compression enabled valueFieldLen += 1; // 1 byte for size of compression type valueFieldLen += this.compType.getCompressionType().length(); } } int size = (int) (12 + this.namespace.length + this.key.length + valueFieldLen); int offset = size % 8; if (offset != 0) { size += 8 - offset; } this.componentSize = size; return size; } // ** Payload (or KeyValue) Component ** // // A 12-byte header followed by name, key and value // Tag/ID: 0x01 // * Header * // // |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7| // | 0| 1| 2| 3| // ------+---------------+---------------+---------------+---------------+ // 0 | Size | // ------+---------------+---------------+-------------------------------+ // 4 | Tag/ID (0x01) | namespace len | key length | // ------+---------------+---------------+-------------------------------+ // 8 | payload length | // ------+---------------------------------------------------------------+ // // ( // The max namespace length: 255 // payload length = 0 if len(payload data) = 0, otherwise, // payload length = 1 + len(payload data) = len(payload field) // ) // // // * Body * // +---------+-----+---------------+-------------------------+ // |namespace| key | payload field | Padding to align 8-byte | // +---------+-----+---------------+-------------------------+ // // * Payload field* // +---------------------+--------------+ // | 1 byte payload type | Payload data | // +---------------------+--------------+ // // * Payload Type // 0: payload data is the actual value passed from client user // 1: payload data is encrypted by Juno client library, details not specified // 2: payload data is encrypted by Juno proxy with AES-GCM. encryption key length is 256 bits // 3: Payload data is compressed by Juno Client library. // // * Payload data // for payload type 2 // +--------------------------------+----------------+----------------+ // | 4 bytes encryption key version | 12 bytes nonce | encrypted data | // +--------------------------------+----------------+----------------+ // // for payload type 3 // +-------------------------------------+--------------------+------------+ // | 1 byte size of compression type | compression type | compressed data | // +-------------------------------------+--------------------+------------+ // // * compression types // 1) snappy-v1 (default algorithm) // 2) zlib-1.2.3 public PayloadOperationMessage readBuf(ByteBuf in) { this.nameSpaceLength = in.readByte(); // Name space length this.keyLength = in.readUnsignedShort(); // Key length long valueFieldLen = in.readUnsignedInt(); // Payload legth = 1(payload type) + len(payload data) = len(payload field) or Payload legth = 0 if no payload this.namespace = new byte[(short)(this.nameSpaceLength & 0xff)]; //Start reading the body in.readBytes(this.namespace); this.key = new byte[this.keyLength]; in.readBytes(this.key); if (valueFieldLen > 0) { this.valueLength = valueFieldLen - 1; //read Payload type int payloadType = in.readByte(); if(payloadType == 3){ // check for payload compression int compTypeSize = in.readByte(); // read size of compressipn type this.valueLength--; byte [] compType = new byte[compTypeSize]; in.readBytes(compType); //read compression type this.valueLength -= compTypeSize; // This is actual compressed payload size setCompressionType(CompressionType.getCompressionType(new String(compType))); } this.value = new byte[(int) this.valueLength]; in.readBytes(this.value); } else { this.value = null; this.valueLength = 0; } if (logger.isDebugEnabled()) { logger.debug("Key: " + new String(key)); logger.debug("namespace: " + new String(namespace)); } return this; } // Here we construct the full component for the payload. public void writeBuf(ByteBuf out) { out.writeInt((int) this.componentSize); out.writeByte(this.tag); out.writeByte(this.nameSpaceLength); out.writeShort((short)this.keyLength); int payloadLen = 0; if(this.valueLength != 0){ payloadLen = (int)this.valueLength+1; if(this.isPloadCompressed){ // compression enabled payloadLen += 1; // 1 byte for compression type size payloadLen += this.compType.getCompressionType().length(); } } out.writeInt(payloadLen); out.writeBytes(this.namespace); out.writeBytes(this.key); if (logger.isDebugEnabled()) { logger.debug("Key: " + new String(key)); logger.debug("namespace: " + new String(namespace)); } if (payloadLen != 0) { if(isPloadCompressed){ // if compression is enabled out.writeByte(3); out.writeByte(compType.getCompressionType().length()); out.writeBytes(this.compType.getCompressionType().getBytes()); }else{ out.writeZero(1); } out.writeBytes(this.value); } } }
158
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/conf/JunoProperties.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.conf; public final class JunoProperties { // property name definitions public static final String RESPONSE_TIMEOUT = "juno.response.timeout_msec"; public static final String CONNECTION_TIMEOUT = "juno.connection.timeout_msec"; public static final String DEFAULT_LIFETIME = "juno.default_record_lifetime_sec"; public static final String CONNECTION_LIFETIME = "juno.connection.recycle_duration_msec"; public static final String CONNECTION_POOL_SIZE = "juno.connection.pool_size"; public static final String RECONNECT_ON_FAIL = "juno.connection.reconnect_on_fail"; public static final String HOST = "juno.server.host"; public static final String PORT = "juno.server.port"; public static final String APP_NAME = "juno.application_name"; public static final String RECORD_NAMESPACE = "juno.record_namespace"; public static final String USE_SSL = "juno.useSSL"; public static final String USE_PAYLOADCOMPRESSION = "juno.usePayloadCompression"; public static final String ENABLE_RETRY = "juno.operation.retry"; public static final String BYPASS_LTM = "juno.connection.byPassLTM"; public static final String CONFIG_PREFIX = "prefix"; // Max for each property public static final String MAX_LIFETIME = "juno.max_record_lifetime_sec"; public static final String MAX_KEY_SIZE = "juno.max_key_size"; public static final String MAX_VALUE_SIZE = "juno.max_value_size"; public static final String MAX_RESPONSE_TIMEOUT = "juno.response.max_timeout_msec"; public static final String MAX_CONNECTION_TIMEOUT = "juno.connection.max_timeout_msec"; public static final String MAX_CONNECTION_LIFETIME = "juno.connection.max_recycle_duration_msec"; public static final String MAX_CONNECTION_POOL_SIZE = "juno.connection.max_pool_size"; public static final String MAX_NAMESPACE_LENGTH = "juno.max_record_namespace_length"; }
159
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/conf/JunoPropertiesProvider.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.conf; import com.paypal.juno.util.BasePropertiesProvider; import java.net.URL; import java.util.Properties; import org.apache.commons.configuration.Configuration; public final class JunoPropertiesProvider extends BasePropertiesProvider { // Property holders. private Integer responseTimeout; private Integer connectionTimeout; private Integer connectionLifetime; private Integer connectionPoolSize; private Long defaultLifetime; private Long maxLifetime; private Integer maxKeySize; private Integer maxValueSize; private Integer maxNameSpaceLength; private Integer maxResponseTimeout; private Integer maxConnectionTimeout; private Integer maxConnectionPoolSize; private Integer maxConnectionLifetime; private String host; private Integer port; private String appName; private String recordNamespace; private Boolean useSSL; private Boolean usePayloadCompression; private Boolean operationRetry; private Boolean byPassLTM; private Boolean reconnectOnFail; private String configPrefix; private Configuration config; /** * Constructs the default properties provider. * * @param props Juno poperties. */ public JunoPropertiesProvider(Properties props) { super(props); validateAndFillAll(); } /** * Constructs the default properties provider. * * @param url location of the Juno poperties file. */ public JunoPropertiesProvider(URL url) { super(url); validateAndFillAll(); } /** * Validate and populate the juno proprties * */ private void validateAndFillAll() { this.connectionLifetime = getIntProperty(JunoProperties.CONNECTION_LIFETIME,JunoPropertyDefaultValue.connectionLifetimeMS); this.connectionPoolSize = getIntProperty(JunoProperties.CONNECTION_POOL_SIZE,JunoPropertyDefaultValue.connectionPoolSize); this.recordNamespace = getStringProperty(JunoProperties.RECORD_NAMESPACE, JunoPropertyDefaultValue.recordNamespace); this.maxConnectionPoolSize = getIntProperty(JunoProperties.MAX_CONNECTION_POOL_SIZE,JunoPropertyDefaultValue.maxConnectionPoolSize); this.maxNameSpaceLength = getIntProperty(JunoProperties.MAX_NAMESPACE_LENGTH,JunoPropertyDefaultValue.maxNamespaceLength); this.byPassLTM = getBooleanProperty(JunoProperties.BYPASS_LTM,JunoPropertyDefaultValue.byPassLTM); this.configPrefix = getStringProperty(JunoProperties.CONFIG_PREFIX,null); this.host = getStringProperty(JunoProperties.HOST, JunoPropertyDefaultValue.host); this.reconnectOnFail = getBooleanProperty(JunoProperties.RECONNECT_ON_FAIL,JunoPropertyDefaultValue.reconnectOnFail); this.port = getIntProperty(JunoProperties.PORT,JunoPropertyDefaultValue.port); this.appName = getStringProperty(JunoProperties.APP_NAME, JunoPropertyDefaultValue.appName); this.useSSL = getBooleanProperty(JunoProperties.USE_SSL, JunoPropertyDefaultValue.useSSL); this.responseTimeout = getIntProperty(JunoProperties.RESPONSE_TIMEOUT,JunoPropertyDefaultValue.responseTimeoutMS); this.connectionTimeout = getIntProperty(JunoProperties.CONNECTION_TIMEOUT,JunoPropertyDefaultValue.connectionTimeoutMS); this.defaultLifetime = getLongProperty(JunoProperties.DEFAULT_LIFETIME,JunoPropertyDefaultValue.defaultLifetimeS); this.usePayloadCompression = getBooleanProperty(JunoProperties.USE_PAYLOADCOMPRESSION,JunoPropertyDefaultValue.usePayloadCompression); this.maxConnectionLifetime = getIntProperty(JunoProperties.MAX_CONNECTION_LIFETIME,JunoPropertyDefaultValue.maxConnectionLifetimeMS); this.maxKeySize = getIntProperty(JunoProperties.MAX_KEY_SIZE,JunoPropertyDefaultValue.maxKeySizeB); this.maxValueSize = getIntProperty(JunoProperties.MAX_VALUE_SIZE,JunoPropertyDefaultValue.maxValueSizeB); this.maxLifetime = getLongProperty(JunoProperties.MAX_LIFETIME,JunoPropertyDefaultValue.maxLifetimeS); this.operationRetry = getBooleanProperty(JunoProperties.ENABLE_RETRY,JunoPropertyDefaultValue.operationRetry); this.configPrefix = getStringProperty(JunoProperties.CONFIG_PREFIX,""); } @Override public String toString() { return "JunoPropertiesProvider{" + " connectionTimeoutMS=" + connectionTimeout + ", connectionPoolSize=" + connectionPoolSize + ", defaultLifetime=" + defaultLifetime + ", maxLifetime=" + maxLifetime + ", host='" + host + '\'' + ", port='" + port + '\'' + ", appName='" + appName + ", recordNamespace='" + recordNamespace + ", useSSL = " + useSSL + ", usePayloadCompression =" + usePayloadCompression + ", responseTimeout = " + responseTimeout + ", maxConnectionPoolSize=" + connectionPoolSize + ", maxConnectionLifetime=" + maxConnectionLifetime + ", maxKeySize=" + maxKeySize + ", maxValueSize=" + maxValueSize + ", maxLifetime=" + maxLifetime + ", maxNameSpaceLength=" + maxNameSpaceLength + ", operationRetry=" + operationRetry + ", byPassLTM=" + byPassLTM + ", reconnectOnFail=" + reconnectOnFail + '}'; } public Integer getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; } public Integer getConnectionPoolSize() { return connectionPoolSize; } public Long getDefaultLifetime() { return defaultLifetime; } public void setDefaultLifetime(Long defaultLifetime) { this.defaultLifetime = defaultLifetime; } public String getHost() { return host; } public Integer getPort() { return port; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public Integer getConnectionLifetime() { return connectionLifetime; } public Integer getMaxKeySize() { return maxKeySize; } public void setMaxKeySize(Integer maxKeySize) { this.maxKeySize = maxKeySize; } public String getRecordNamespace() { return recordNamespace; } public Boolean useSSL(){ return useSSL; } public Integer getResponseTimeout() { return responseTimeout; } public void setResponseTimeout(Integer responseTimeout) { this.responseTimeout = responseTimeout; } public Long getMaxLifetime() { return maxLifetime; } public void setMaxLifetime(Long maxLifetime) { this.maxLifetime = maxLifetime; } public Integer getMaxValueSize() { return maxValueSize; } public void setMaxValueSize(Integer maxValueSize) { this.maxValueSize = maxValueSize; } public Integer getMaxConnectionPoolSize() { return maxConnectionPoolSize; } public Integer getMaxNameSpaceLength() { return maxNameSpaceLength; } public void setMaxNameSpaceLength(Integer maxNameSpaceLength) { this.maxNameSpaceLength = maxNameSpaceLength; } public Integer getMaxConnectionLifetime() { return maxConnectionLifetime; } public Boolean isUsePayloadCompression() { return usePayloadCompression; } public void SetUsePayloadCompression(Boolean usePayloadCompression) { this.usePayloadCompression = usePayloadCompression; } public Boolean getOperationRetry(){ return operationRetry; } public void setOperationRetry(Boolean operationRetry){ this.operationRetry = operationRetry; } public Boolean getByPassLTM(){ return byPassLTM; } public Boolean getReconnectOnFail(){ return reconnectOnFail; } public String getConfigPrefix() { return configPrefix; } public void setConfig(Configuration config) { this.config = config; } public Configuration getConfig() { return this.config; } }
160
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/conf/JunoPropertyDefaultValue.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. // //if I have comments here, does it break the system? package com.paypal.juno.conf; public final class JunoPropertyDefaultValue { // Default static public final int responseTimeoutMS = 200; static public final int connectionTimeoutMS = 200; static public final int connectionPoolSize = 1; static public final int connectionLifetimeMS = 30000; static public final long defaultLifetimeS = 259200; // Max for all above property static public final int maxResponseTimeoutMS = 5000; static public final int maxConnectionLifetimeMS = 30000; static public final int maxconnectionTimeoutMS = 5000; static public final int maxKeySizeB = 128; static public final int maxValueSizeB = 204800; static public final int maxNamespaceLength = 64; static public final int maxConnectionPoolSize = 3; static public final long maxLifetimeS = 259200; // Required static public final String host = ""; static public final int port = 0; static public final String appName = ""; static public final String recordNamespace = ""; //optional public static final boolean useSSL = true; public static final boolean reconnectOnFail = false; public static final boolean usePayloadCompression = false; public static final boolean operationRetry = false; static public final boolean byPassLTM = true; }
161
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/exception/JunoClientConfigException.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; /** * Exception to represent a Client configuration error. */ public final class JunoClientConfigException extends JunoException { private static final long serialVersionUID = -2773624072814891564L; public JunoClientConfigException(String message) { super(message); } public JunoClientConfigException(String message, Throwable cause) { super(message, cause); } public JunoClientConfigException(Throwable cause) { super(cause); } }
162
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/ServerOperationStatus.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.OperationStatus; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public enum ServerOperationStatus { // Response codes that match the JUNO Server side protocol Success(0, "no error", OperationStatus.Success), BadMsg(1, "bad message",OperationStatus.InternalError), NoKey(3, "key not found",OperationStatus.NoKey), DupKey(4, "dup key",OperationStatus.UniqueKeyViolation), BadParam(7, "bad parameter",OperationStatus.BadParam), RecordLocked(8, "record locked",OperationStatus.RecordLocked), NoStorageServer(12, "no active storage server",OperationStatus.NoStorage), ServerBusy(14, "Server busy",OperationStatus.InternalError), VersionConflict(19, "version conflict",OperationStatus.ConditionViolation), OpStatusSSReadTTLExtendErr(23,"Error extending TTL by SS",OperationStatus.InternalError), CommitFailure(25, "Commit Failure",OperationStatus.InternalError), InconsistentState(26,"Inconsistent State",OperationStatus.Success), Internal(255,"Internal error",OperationStatus.InternalError), //Client specific errors QueueFull(256,"Outbound client queue full",OperationStatus.QueueFull), ConnectionError(257,"Connection error",OperationStatus.ConnectionError), ResponseTimedout(258,"Response timed out",OperationStatus.ResponseTimeout); private final int code; private final String errorText; private OperationStatus resStatus; private static final Map<Integer, ServerOperationStatus> lookup = new HashMap<Integer, ServerOperationStatus>(); static { for (ServerOperationStatus s : EnumSet .allOf(ServerOperationStatus.class)) lookup.put(s.getCode(), s); } /** * Constructor * * @param code * @param errorText */ ServerOperationStatus(int code, String errorText, OperationStatus rs) { this.code = code; this.errorText = errorText; this.resStatus = rs; } public int getCode() { return this.code; } public String getErrorText() { return this.errorText; } public static ServerOperationStatus get(int code) { if(lookup.get(code) == null) return Internal; else return lookup.get(code); } public OperationStatus getOperationStatus() { return resStatus; } }
163
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/JunoClientFactory.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.impl.JunoClientFactoryInternal; import com.paypal.juno.conf.JunoPropertiesProvider; import java.net.URL; import javax.net.ssl.SSLContext; /** * Factory for the various implementations of Juno client operations. * This is a final class with all static methods. * * <p> * Every Juno client user is expected to instantiate the Juno Client * instances using this factory class. * <p> * Before invoking any methods on the JunoClient instances returned by * the methods of this factory class, it is the responsibility of the user to * initialize CAL. * The JunoClient implementations make use of CAL for logging. * */ public final class JunoClientFactory { private static final JunoClientFactoryInternal factory = new JunoClientFactoryInternal(); private JunoClientFactory() { //Cannot be instantiated outside this class. } /** * Instantiates a JunoClient implementation using the Juno config * properties from the given URL. * <p> * Ensure that uKernel CAL Client is initialized. * * @param url URL corresponding to the Juno config properties file. * Cannot be null. * * @return JunoClient instance initialized with the properties from the * given URL. */ public static JunoClient newJunoClient(URL url) { return factory.newJunoClient(url); } /** * Instantiates a JunoClient implementation using the given Juno * property provider. * * @param junoProps Juno configuration properties. * Cannot be null. * * @return JunoClient instance initialized with the properties from the given * Juno configuration properties. */ public static JunoClient newJunoClient(JunoPropertiesProvider junoProps) { return factory.newJunoClient(junoProps); } /** * Instantiates a JunoClient implementation using the given Juno * property provider and client supplied SSLContext. * * @param junoProps Juno configuration properties.Cannot be null. * @param sslCtx - Client supplied SSL context * * @return JunoClient instance initialized with the properties from the given * Juno configuration properties. */ public static JunoClient newJunoClient(JunoPropertiesProvider junoProps,SSLContext sslCtx) { return factory.newJunoClient(junoProps,sslCtx); } /** * Instantiates a JunoAsyncClient implementation using the Juno config * properties from the given URL. * <p> * Ensure that uKernel CAL Client is initialized. * * @param url URL corresponding to the Juno config properties file. * Cannot be null. * * @return JunoAsyncClient instance initialized with the properties from the * given URL. This is not threadsafe. */ public static JunoAsyncClient newJunoAsyncClient(URL url) { return factory.newJunoAsyncClient(url); } /** * Instantiates a JunoAsyncClient implementation using the given Juno * property provider. * * @param junoProps Juno configuration properties. * Cannot be null. * * @return JunoAsyncClient instance initialized with the properties from the given * Juno configuration properties. */ public static JunoAsyncClient newJunoAsyncClient(JunoPropertiesProvider junoProps) { return factory.newJunoAsyncClient(junoProps); } /** * Instantiates a JunoAsyncClient implementation using the given Juno * property provider and client supplied SSLContext. * * @param junoProps Juno configuration properties.Cannot be null. * @param sslCtx - Client supplied SSL context * * @return JunoAsyncClient instance initialized with the properties from the given * Juno configuration properties. */ public static JunoAsyncClient newJunoAsyncClient(JunoPropertiesProvider junoProps,SSLContext sslCtx) { return factory.newJunoAsyncClient(junoProps,sslCtx); } /** * Instantiates a newJunoReactClient implementation using the Juno config * properties from the given URL. * * @param url URL corresponding to the Juno config properties file. * Cannot be null. * * @return JunoReactClient instance initialized with the properties from the * given URL. This is not threadsafe. */ public static JunoReactClient newJunoReactClient(URL url) { return factory.newJunoReactClient(url); } /** * Instantiates a JunoReactClient implementation using the given Juno * property provider. * * @param junoProps Juno configuration properties. * Cannot be null. * * @return JunoReactClient instance initialized with the properties from the given * Juno configuration properties. */ public static JunoReactClient newJunoReactClient(JunoPropertiesProvider junoProps) { return factory.newJunoReactClient(junoProps); } /** * Instantiates a JunoReactClient implementation using the given Juno * property provider and client supplied SSLContext. * * @param junoProps Juno configuration properties.Cannot be null. * @param sslCtx - Client supplied SSL context * * @return JunoReactClient instance initialized with the properties from the given * Juno configuration properties. */ public static JunoReactClient newJunoReactClient(JunoPropertiesProvider junoProps,SSLContext sslCtx) { return factory.newJunoReactClient(junoProps,sslCtx); } }
164
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/JunoClientConfigHolder.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.conf.JunoProperties; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.conf.JunoPropertyDefaultValue; import com.paypal.juno.exception.JunoClientConfigException; import com.paypal.juno.util.JunoClientUtil; import com.paypal.juno.util.JunoConstants; import com.paypal.juno.util.JunoMetrics; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JunoClientConfigHolder { private static final Logger LOGGER = LoggerFactory.getLogger(JunoClientConfigHolder.class); protected final JunoPropertiesProvider junoProp; private final InetSocketAddress serversAddress; private final Configuration config; // @Autowired // InstanceLocation instanceLocation; // private final String INSTANCE_GEO_PP_US = "PP_US"; public JunoClientConfigHolder(JunoPropertiesProvider junoProp) { JunoClientUtil.throwIfNull(junoProp, "config"); try { this.junoProp = junoProp; this.config = junoProp.getConfig(); validateAll(); serversAddress = getServerAddress(this.junoProp); } catch (Exception ce) { throw new JunoClientConfigException(ce); } } public String printProperties(){ return junoProp.toString(); } public Map<String,String> getProperties(){ Map<String,String> prop= new HashMap<>(); prop.put(JunoProperties.RESPONSE_TIMEOUT,String.valueOf(this.getResponseTimeout())); prop.put(JunoProperties.CONNECTION_TIMEOUT,String.valueOf(this.getConnectionTimeoutMsecs())); prop.put(JunoProperties.CONNECTION_POOL_SIZE,String.valueOf(this.getConnectionPoolSize())); prop.put(JunoProperties.DEFAULT_LIFETIME,String.valueOf(this.getDefaultLifetimeSecs())); prop.put(JunoProperties.HOST,this.getHost()); prop.put(JunoProperties.PORT,String.valueOf(this.getPort())); prop.put(JunoProperties.APP_NAME,this.getApplicationName()); prop.put(JunoProperties.RECORD_NAMESPACE,this.getRecordNamespace()); prop.put(JunoProperties.USE_PAYLOADCOMPRESSION,String.valueOf(this.getUsePayloadCompression())); prop.put(JunoProperties.BYPASS_LTM,String.valueOf(this.getByPassLTM())); prop.put(JunoProperties.RECONNECT_ON_FAIL,String.valueOf(this.getReconnectOnFail())); prop.put(JunoProperties.ENABLE_RETRY,String.valueOf(this.isRetryEnabled())); prop.put(JunoProperties.CONFIG_PREFIX,junoProp.getConfigPrefix()); return prop; } protected void validateAll() { // Call all gets triggering all validations.. this.getConnectionTimeoutMsecs(); this.getApplicationName(); this.getRecordNamespace(); this.getDefaultLifetimeSecs(); this.getConnectionLifeTime(); this.getConnectionPoolSize(); this.getHost(); this.getMaxKeySize(); this.getResponseTimeout(); this.getMaxValueSize(); } /** * This config is optional * * @param junoProp * Juno configuration * @return List of server in format of: ip:port */ public static InetSocketAddress getServerAddress(JunoPropertiesProvider junoProp) { InetAddress ipAddress; InetSocketAddress result = null; String host = junoProp.getHost().trim(); int port = junoProp.getPort(); try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Juno servers VIP: "+ host +" and PORT: " + port); } if (host == null || host.isEmpty()) { LOGGER.error("Juno configuration value for property, " + JunoProperties.HOST + " the serevr is not configured"); throw new JunoClientConfigException("Juno server not configured..."); } if (port < 1) { LOGGER.error("Juno configuration value for property, " + JunoProperties.PORT + " the port cannot be null or less than 1"); throw new JunoClientConfigException("Invalid Juno server port..."); } ipAddress = InetAddress.getByName(host); result = new InetSocketAddress(ipAddress,port); } catch (UnknownHostException e) { LOGGER.error("Unable to look up the given host " + host); } return result; } public String getApplicationName() { String appName = this.junoProp.getAppName(); if (appName == null || appName.length() == 0) { throw new JunoClientConfigException("Juno configuration value for property, " + JunoProperties.APP_NAME + " cannot be null or empty"); } if (appName.getBytes().length > JunoConstants.APP_NAME_MAX_LEN) { String msg = "Application Name length exceeds MAX LENGTH of " + JunoConstants.APP_NAME_MAX_LEN + " bytes"; LOGGER.error(msg); throw new JunoClientConfigException(msg); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("JunoClient applicationName: " + appName); } return appName; } private Integer getMaxRecordNameSpaceLength(){ Integer recordNameSpaceLength = validateAndReturnDefaultInt(JunoProperties.MAX_NAMESPACE_LENGTH, this.junoProp.getMaxNameSpaceLength(), 0, Integer.MAX_VALUE,JunoPropertyDefaultValue.maxNamespaceLength); LOGGER.debug("JunoClient max record namespace lenth: " + recordNameSpaceLength); return recordNameSpaceLength; } public String getRecordNamespace() { String ns = this.junoProp.getRecordNamespace(); if (ns == null || ns.length() == 0) { throw new JunoClientConfigException("Juno configuration value for property, " + JunoProperties.RECORD_NAMESPACE + " cannot be null or empty"); } if (ns.getBytes().length > getMaxRecordNameSpaceLength()) { String msg = "Namespace length exceeds MAX LENGTH of " + getMaxRecordNameSpaceLength() + " bytes"; LOGGER.error(msg); throw new JunoClientConfigException(msg); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("JunoClient recordNamespace: " + ns); } return ns; } private Integer getMaxConnectionLifeTime(){ Integer maxConnectionLifeTime = validateAndReturnDefaultInt(JunoProperties.MAX_CONNECTION_LIFETIME, this.junoProp.getMaxConnectionLifetime(), 6000, Integer.MAX_VALUE,JunoPropertyDefaultValue.maxConnectionLifetimeMS); LOGGER.debug("JunoClient max Connection Lifetime (sec): " + maxConnectionLifeTime); return maxConnectionLifeTime; } public Integer getConnectionLifeTime() { Integer connectionLifeTime = validateAndReturnDefaultInt(JunoProperties.CONNECTION_LIFETIME, this.junoProp.getConnectionLifetime(), 5000, getMaxConnectionLifeTime(),JunoPropertyDefaultValue.connectionLifetimeMS); LOGGER.debug("JunoClient Connection Lifetime (sec): " + connectionLifeTime); return connectionLifeTime; } private Integer getMaxConnectionPoolSize(){ Integer maxConnectionPoolSize = validateAndReturnDefaultInt(JunoProperties.MAX_CONNECTION_POOL_SIZE, this.junoProp.getMaxConnectionPoolSize(), 1, Integer.MAX_VALUE,JunoPropertyDefaultValue.maxConnectionPoolSize); LOGGER.debug("JunoClient max Connection pool size: " + maxConnectionPoolSize); return maxConnectionPoolSize; } public Integer getConnectionPoolSize() { Integer connectionPoolSize = validateAndReturnDefaultInt(JunoProperties.CONNECTION_POOL_SIZE, this.junoProp.getConnectionPoolSize(), 1, getMaxConnectionPoolSize(),JunoPropertyDefaultValue.connectionPoolSize); LOGGER.debug("JunoClient Connection pool size: " + connectionPoolSize); return connectionPoolSize; } public String getHost(){ return junoProp.getHost().trim(); } public int getPort(){ return junoProp.getPort(); } public boolean getUseSSL(){ return this.junoProp.useSSL(); } public InetSocketAddress getServer() { return serversAddress; } public boolean getByPassLTM(){ return this.junoProp.getByPassLTM(); } public boolean getReconnectOnFail(){ return this.junoProp.getReconnectOnFail(); } //---------------------------------- Validation Methods-------------------------------------------- protected final Integer validateAndReturnDefaultInt(String key, Integer prop, int min, int max, Integer defaultVal) { if (prop == null) { return defaultVal; } if (prop < min) { throw new JunoClientConfigException( "Juno configuration value for property " + key + " cannot be less than " + min); } if (prop > max) { throw new JunoClientConfigException( "Juno configuration value for property " + key + " cannot be greater than " + max); } return prop; } protected final Long validateAndReturnDefaultLong(String key, Long prop, long min, long max, Long defaultVal) { if (prop == null) { return defaultVal; } if (prop < min) { throw new JunoClientConfigException( "Juno configuration value for property " + key + " cannot be less than " + min); } if (prop > max) { throw new JunoClientConfigException( "Juno configuration value for property " + key + " cannot be greater than " + max); } return prop; } //---------------------------------- Dynamic Config-------------------------------------------- protected final Integer processIntProperty(String property, Integer currentValue, int min,int max, Integer defaultValue){ String propertyWithPrefix = junoProp.getConfigPrefix()!=""?junoProp.getConfigPrefix()+"."+property:property; Integer rcsValue = getRemoteConfigInt(propertyWithPrefix,currentValue); Integer intProperty = currentValue; if(rcsValue != null && !rcsValue.equals(currentValue)){ try { intProperty = validateAndReturnDefaultInt(propertyWithPrefix, rcsValue, min, max, defaultValue); }catch(Exception e){ JunoMetrics.recordEventCount("JUNO_CONFIG",property,JunoMetrics.EXCEPTION); LOGGER.warn("Exception in Dynamic config. "+e.getMessage()); } } else { intProperty = validateAndReturnDefaultInt(propertyWithPrefix, currentValue, min, max,defaultValue); } return intProperty; } protected final Long processLongProperty(String property, Long currentValue, long min,long max, Long defaultValue){ String propertyWithPrefix = junoProp.getConfigPrefix()!=""?junoProp.getConfigPrefix()+"."+property:property; Long rcsValue = getRemoteConfigLong(propertyWithPrefix,currentValue); Long longProperty = currentValue; //If value is updated in RCS then it will not be same as currentValue if(rcsValue != null && !rcsValue.equals(currentValue)){ try { longProperty = validateAndReturnDefaultLong(propertyWithPrefix, rcsValue, min, max, defaultValue); }catch(Exception e){ JunoMetrics.recordEventCount("JUNO_CONFIG",property,JunoMetrics.EXCEPTION); LOGGER.warn("Exception in Dynamic config. "+e.getMessage()); } } else { longProperty = validateAndReturnDefaultLong(propertyWithPrefix, currentValue, min, max,defaultValue); } return longProperty; } protected final Boolean processBoolProperty(String property, Boolean currentValue){ String propertyWithPrefix = junoProp.getConfigPrefix()!=""?junoProp.getConfigPrefix()+"."+property:property; Boolean rcsValue = getRemoteConfigBool(propertyWithPrefix,currentValue); Boolean boolProperty = currentValue; if(rcsValue != null && !rcsValue.equals(currentValue)){ boolProperty = rcsValue; } return boolProperty; } private Integer getRemoteConfigInt(String propertyWithPrefix, Integer currentValue){ if(junoProp.getConfig() != null && junoProp.getConfig().containsKey(propertyWithPrefix)){ try { Integer intProp = junoProp.getConfig().getInt(propertyWithPrefix); return intProp; }catch (Exception e){ LOGGER.error("Error in Config ("+propertyWithPrefix+"). Exception :"+e.getMessage()); } } return currentValue; } private Boolean getRemoteConfigBool(String propertyWithPrefix, Boolean currentValue){ if(junoProp.getConfig() != null && junoProp.getConfig().containsKey(propertyWithPrefix)){ try { Boolean boolProp = junoProp.getConfig().getBoolean(propertyWithPrefix); return boolProp; }catch (Exception e){ LOGGER.error("Error in Config ("+propertyWithPrefix+"). Exception :"+e.getMessage()); } } return currentValue; } private Long getRemoteConfigLong(String propertyWithPrefix, Long currentValue){ if(junoProp.getConfig() != null && junoProp.getConfig().containsKey(propertyWithPrefix)){ try { Long longProp = junoProp.getConfig().getLong(propertyWithPrefix); return longProp; }catch (Exception e){ LOGGER.error("Error in Config ("+propertyWithPrefix+"). Exception :"+e.getMessage()); } } return currentValue; } // ------------------------------- Following Parameters can change Values dynamically-------------------- //Dynamic Config update enabled public Boolean getUsePayloadCompression(){ Boolean usePayloadCompression = processBoolProperty(JunoProperties.USE_PAYLOADCOMPRESSION,junoProp.isUsePayloadCompression()); if(usePayloadCompression !=null && !usePayloadCompression.equals(junoProp.isUsePayloadCompression())){ junoProp.SetUsePayloadCompression(usePayloadCompression); LOGGER.info("JunoClient Payload compression Dynamic updated value: " + usePayloadCompression); LOGGER.debug("JUNO","JUNO_CONFIG", "JunoClient Payload compression Dynamic updated value: " + usePayloadCompression); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.USE_PAYLOADCOMPRESSION,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient use payload compression: " + usePayloadCompression); return usePayloadCompression; } //Dynamic Config update enabled public Integer getConnectionTimeoutMsecs() { Integer connTimeout = processIntProperty(JunoProperties.CONNECTION_TIMEOUT,junoProp.getConnectionTimeout(),1,JunoPropertyDefaultValue.maxconnectionTimeoutMS,JunoPropertyDefaultValue.connectionTimeoutMS); if(connTimeout != null && !connTimeout.equals(junoProp.getConnectionTimeout())){ junoProp.setConnectionTimeout(connTimeout); LOGGER.info("JunoClient Connection Timeout Dynamic updated value: "+connTimeout); LOGGER.debug("JUNO","JUNO_CONFIG", "JunoClient Connection Timeout Dynamic updated value: "+connTimeout); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.CONNECTION_TIMEOUT,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient connection timeout (msecs): " + connTimeout); return connTimeout; } //Dynamic Config update enabled public Long getMaxLifetimeSecs(){ Long maxLifeTime = processLongProperty(JunoProperties.MAX_LIFETIME,junoProp.getMaxLifetime(),1,Long.MAX_VALUE,JunoPropertyDefaultValue.maxLifetimeS); if(maxLifeTime != null && !maxLifeTime.equals(junoProp.getMaxLifetime())){ junoProp.setMaxLifetime(maxLifeTime); LOGGER.info("JunoClient Max TTL Dynamic updated value: "+maxLifeTime); LOGGER.debug("JUNO","JUNO_CONFIG","JunoClient Max TTL Dynamic updated value: "+maxLifeTime); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.MAX_LIFETIME,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient max lifetime (sec): " + maxLifeTime); return maxLifeTime; } //Dynamic Config update enabled public Long getDefaultLifetimeSecs() { Long lifetime = processLongProperty(JunoProperties.DEFAULT_LIFETIME,junoProp.getDefaultLifetime(),1,getMaxLifetimeSecs(),JunoPropertyDefaultValue.defaultLifetimeS); if(lifetime != null && !lifetime.equals(junoProp.getDefaultLifetime())){ junoProp.setDefaultLifetime(lifetime); LOGGER.info("JunoClient TTL Dynamic updated value: "+lifetime); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.DEFAULT_LIFETIME,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient default lifetime (sec): " + lifetime); return lifetime; } //Dynamic Config update enabled public boolean isRetryEnabled(){ Boolean enableRetry = processBoolProperty(JunoProperties.ENABLE_RETRY,junoProp.getOperationRetry()); if(enableRetry != null && !enableRetry.equals(junoProp.getOperationRetry())){ junoProp.setOperationRetry(enableRetry); LOGGER.info("JunoClient Operation retry Dynamic updated value: "+enableRetry); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.ENABLE_RETRY,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient Operation retry: " + enableRetry); return enableRetry; } //Dynamic Config update enabled public Integer getMaxValueSize(){ Integer maxValueSize = processIntProperty(JunoProperties.MAX_VALUE_SIZE,junoProp.getMaxValueSize(),1,Integer.MAX_VALUE,JunoPropertyDefaultValue.maxValueSizeB); if(maxValueSize != null && !maxValueSize.equals(junoProp.getMaxValueSize())){ junoProp.setMaxValueSize(maxValueSize); LOGGER.info("JunoClient max Value size Dynamic updated value: "+maxValueSize); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.MAX_VALUE_SIZE,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient max Value size: " + maxValueSize); return maxValueSize; } //Dynamic Config update enabled public Integer getMaxKeySize() { Integer maxKeySize = processIntProperty(JunoProperties.MAX_KEY_SIZE,junoProp.getMaxKeySize(),1,Integer.MAX_VALUE,JunoPropertyDefaultValue.maxKeySizeB); if(maxKeySize != null && !maxKeySize.equals(junoProp.getMaxKeySize())){ junoProp.setMaxKeySize(maxKeySize); LOGGER.info("JunoClient Key size Dynamic updated value: "+maxKeySize); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.MAX_KEY_SIZE,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient Key size: " + maxKeySize); return maxKeySize; } //Dynamic Config update enabled public Integer getResponseTimeout() { Integer responseTimeout = processIntProperty(JunoProperties.RESPONSE_TIMEOUT,junoProp.getResponseTimeout(),1,JunoPropertyDefaultValue.maxResponseTimeoutMS,JunoPropertyDefaultValue.responseTimeoutMS); if(responseTimeout != null && !responseTimeout.equals(junoProp.getResponseTimeout())){ junoProp.setResponseTimeout(responseTimeout); LOGGER.info("JunoClient Response timeout Dynamic updated value: "+responseTimeout); JunoMetrics.recordEventCount("JUNO_CONFIG",JunoProperties.RESPONSE_TIMEOUT,JunoMetrics.SUCCESS); } LOGGER.debug("JunoClient Response timeout (msec): " + responseTimeout); return responseTimeout; } }
165
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/impl/JunoAsyncClientImpl.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.impl; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClientConfigHolder; 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.client.io.RecordContext; import com.paypal.juno.exception.JunoException; import com.paypal.juno.io.protocol.JunoMessage.OperationType; import com.paypal.juno.io.protocol.JunoMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.net.RequestQueue; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.JunoClientUtil; import com.paypal.juno.util.JunoConstants; import com.paypal.juno.util.JunoMetrics; import com.paypal.juno.util.JunoStatusCode; import com.paypal.juno.util.SendBatch; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import org.apache.commons.codec.binary.Hex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Single; import rx.schedulers.Schedulers; class JunoAsyncClientImpl implements JunoAsyncClient{ private final JunoClientConfigHolder configHolder; private final static AtomicInteger opaqueGenarator = new AtomicInteger(); private final RequestQueue reqQueue; private final ConcurrentHashMap<Integer,BlockingQueue<OperationMessage>> opaqueResMap; ExecutorService executor; private boolean isAsync = true; private static final int MAX_RETRY=1; private static final int MAX_RETRY_INTERVAL=90; private static final int MIN_RETRY_INTERVAL=10; // @Autowired // InstanceLocation instanceLocation; // private final String INSTANCE_GEO_PP_US = "PP_US"; /** * The logger. We make this a non-static member in order to prevent this * from being synchronized. */ private static final Logger LOGGER = LoggerFactory.getLogger(JunoAsyncClientImpl.class); JunoAsyncClientImpl(JunoClientConfigHolder config,SSLContext ctx,boolean isAsync){ this(config,ctx); this.isAsync = isAsync; } protected JunoAsyncClientImpl(JunoClientConfigHolder config,SSLContext ctx){ this.configHolder = config; SocketConfigHolder socCfg = new SocketConfigHolder(configHolder); socCfg.setCtx(ctx); reqQueue = RequestQueue.getInstance(socCfg); opaqueResMap = reqQueue.getOpaqueResMap(); executor = Executors.newCachedThreadPool(); } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,JunoRequest.OperationType.Create); return processSingle(req,OperationType.Create); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); } catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,timeToLiveSec,JunoRequest.OperationType.Create); return processSingle(req,OperationType.Create); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,0,0,JunoRequest.OperationType.Get); return processSingle(req,OperationType.Get); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,0,timeToLiveSec,JunoRequest.OperationType.Get); return processSingle(req,OperationType.Get); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,0,JunoRequest.OperationType.Update); return processSingle(req,OperationType.Update); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,timeToLiveSec,JunoRequest.OperationType.Update); return processSingle(req,OperationType.Update); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,JunoRequest.OperationType.Set); return processSingle(req,OperationType.Set); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,timeToLiveSec,JunoRequest.OperationType.Set); return processSingle(req,OperationType.Set); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,0,0,JunoRequest.OperationType.Destroy); return processSingle(req,OperationType.Destroy); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * Return the configured Juno properties for this current instance in a MAP */ public Map<String, String> getProperties() { return this.configHolder.getProperties(); } /** * 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 - Juno record context * @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 { try{ if(jcx == null){ throw new IllegalArgumentException("Record Context cannot be null"); } final JunoRequest req = new JunoRequest(jcx.getKey(),value,jcx.getVersion(),timeToLiveSec,jcx.getCreationTime(),JunoRequest.OperationType.Update); return processSingle(req,OperationType.CompareAndSet); }catch(JunoException je){ throw je; }catch (IllegalArgumentException iae) { SocketConfigHolder socConfig = new SocketConfigHolder(configHolder); JunoMetrics.recordOpCount(socConfig.getJunoPool(), JunoRequest.OperationType.Update.getOpType(), OperationStatus.IllegalArgument.getErrorText(), iae.getMessage()); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * This is the method for performing a batch of records * @param request- List of requests to be processed * Juno Request object * @return Observable<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ @SuppressWarnings("deprecation") @Override public Observable<JunoResponse> doBatch(final Iterable<JunoRequest> request) throws JunoException { SocketConfigHolder socConfig = new SocketConfigHolder(configHolder); //Check for null and empty argument if(request == null){ JunoMetrics.recordOpCount(socConfig.getJunoPool(),"JUNO_BATCH", OperationStatus.IllegalArgument.getErrorText(),"null_request_list"); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(), new IllegalArgumentException("Request argument is null")); }else if(!request.iterator().hasNext()){ JunoMetrics.recordOpCount(socConfig.getJunoPool(), "JUNO_BATCH", OperationStatus.IllegalArgument.getErrorText(),"empty_request_list"); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(), new IllegalArgumentException("Empty request list supplied")); } long opStartTime = System.currentTimeMillis(); final Map<String,CharSequence> rootTrans = new HashMap<String, CharSequence>(); rootTrans.put("isAsync", String.valueOf(isAsync)); rootTrans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); rootTrans.put("OPTYPE", "JUNO_BATCH"); try{ Observable<JunoResponse> resp = Observable.<JunoResponse>create(t-> { boolean txnFailed = false; //This Map has all the requests along with their UUIDs. final ConcurrentHashMap<UUID,JunoMessage> reqIdReqMsgMap = JunoClientUtil.bulkValidate(request,t,configHolder,socConfig,isAsync); int batchSize = reqIdReqMsgMap.size(); AtomicInteger reqSent = new AtomicInteger(0); // Number of Requests sent //int resCount=0; // Number of Responses received int totalReqSent=0; int totalResReceived=0; Integer batchOpaque=0; try{ int retryCounter=0; boolean operationRetry = configHolder.isRetryEnabled(); rootTrans.put("num_request_for_this_batch",String.valueOf(batchSize)); while(retryCounter <= MAX_RETRY){ retryCounter++; reqSent.set(0); //Initialize the reqSent count to 0 int resCount = 0; //Initialize the resCount count to 0 batchOpaque = opaqueGenarator.incrementAndGet(); // Opaqueue for batch operation // Blocking queue to receive the response BlockingQueue<OperationMessage> respQueue = new ArrayBlockingQueue<OperationMessage>(reqIdReqMsgMap.size()); opaqueResMap.put(batchOpaque,respQueue); // Add the blocking queue to the opaqueRespMap if(!reqQueue.isConnected()){ throw new JunoException(OperationStatus.ConnectionError.getErrorText()); } SendBatch sndBatch = new SendBatch(batchOpaque,reqQueue,reqIdReqMsgMap,reqSent); Future<Integer> reqSender = executor.submit(sndBatch); rootTrans.put("batch_id_"+retryCounter,String.valueOf(batchOpaque)); long respTimeout = configHolder.getResponseTimeout(); //Receive the Responses for requests sent in request queue while (!reqSender.isDone() || reqSent.get() > resCount ){ // wait up to 100ms for the first request to be sent out if(reqSent.get() == 0){ long start = System.currentTimeMillis(); synchronized (reqSent) { reqSent.wait(100); } if((System.currentTimeMillis() - start) > 50) { rootTrans.put("NAME", "JUNO_BATCH_SEND_DELAYED"); rootTrans.put("timeToSendRequest",String.valueOf(System.currentTimeMillis() - start)); LOGGER.warn(JunoStatusCode.WARNING.toString() + " {} ", rootTrans); JunoMetrics.recordEventCount("JUNO_BATCH_SEND_DELAYED","UNKNOWN",JunoMetrics.WARNING); } } long startTime = System.currentTimeMillis(); //wait for response to arrive OperationMessage responseOpeMsg = respQueue.poll(respTimeout, TimeUnit.MILLISECONDS); respTimeout -= (System.currentTimeMillis() - startTime); respTimeout = respTimeout<0?0:respTimeout; //Just in case not to go negative //When response time out, the respQueue will return null if(responseOpeMsg == null){ reqQueue.incrementFailedAttempts(); break; } //Fetch the original request using the request ID JunoMessage reqMsg = reqIdReqMsgMap.get(responseOpeMsg.getMetaComponent().getRequestUuid()); if(reqMsg == null){ //This should not be the case. Do nothing just continue continue; } resCount++; // Got a valid response reqQueue.incrementSuccessfulAttempts(); //Decode the received operation message and create the JunoResponse JunoMessage respMessage = JunoClientUtil.decodeOperationMessage(responseOpeMsg,reqMsg.getKey(),configHolder); JunoResponse junoResp = new JunoResponse(respMessage.getKey(),respMessage.getValue(),respMessage.getVersion(), respMessage.getTimeToLiveSec(),respMessage.getCreationTime(),respMessage.getStatus().getOperationStatus()); if(respMessage.getStatus().getOperationStatus() != OperationStatus.Success){ //Check if retry is configured and the error is a retryable error if(operationRetry && JunoClientUtil.checkForRetry(respMessage.getStatus().getOperationStatus())){ JunoMetrics.recordOpCount(socConfig.getJunoPool(), "B_"+reqMsg.getOpType().getOpType(), respMessage.getStatus().getErrorText()); continue; } } //Remove the request from reqMap once there is a successful response reqIdReqMsgMap.remove(responseOpeMsg.getMetaComponent().getRequestUuid()); //Add CAL for the responses. final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("isAsync", String.valueOf(isAsync)); trans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); trans.put("B_OPTYPE", "B_"+reqMsg.getOpType().getOpType()); trans.put("batch_id",String.valueOf(batchOpaque)); trans.put("hex_key", Hex.encodeHexString(reqMsg.getKey()).toUpperCase()); trans.put("req_id", responseOpeMsg.getMetaComponent().getRequestIdString()); trans.put("req_attempt",String.valueOf(retryCounter)); trans.put("ver", reqMsg.getVersion()+"|"+respMessage.getVersion()); trans.put("ttl", reqMsg.getTimeToLiveSec()+"|"+respMessage.getTimeToLiveSec()); trans.put("msg_size", reqMsg.getMessageSize()+"|"+Long.toString(responseOpeMsg.getHeader().getMessageSize())); if(reqMsg.isPayloadCompressed()){ trans.put("comp_%", Integer.toString(reqMsg.getCompressionAchieved())); } long reqValSize = (reqMsg.getValue() != null)? reqMsg.getValue().length:0; trans.put("val_size", reqValSize+"|"+respMessage.getValue().length); trans.put("server", responseOpeMsg.getServerIp()+":"+String.valueOf(socConfig.getPort())); if(respMessage.getReqHandlingTime() > 0){ trans.put("rht", ""+respMessage.getReqHandlingTime()); } trans.put("status", respMessage.getStatus().getErrorText()); long duration = System.currentTimeMillis() - reqMsg.getReqStartTime(); //Set CAL ok if the error code is acceptable. if(junoResp.getStatus().isTxnOk()){ trans.put("STATUS", JunoStatusCode.SUCCESS.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"B_"+reqMsg.getOpType().getOpType(), socConfig.getJunoPool(),JunoMetrics.SUCCESS,duration); }else{ txnFailed = true; trans.put("STATUS", JunoStatusCode.ERROR.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"B_"+reqMsg.getOpType().getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR,duration); } JunoMetrics.recordOpCount(socConfig.getJunoPool(),"B_"+reqMsg.getOpType().getOpType(),respMessage.getStatus().getErrorText()); trans.put("Duration", String.valueOf(duration)); LOGGER.info("TxnStatus : {}", trans); t.onNext(junoResp); } //remove the respQueue for the current batchOpaque. So that retry will use a different opaque. opaqueResMap.remove(batchOpaque); totalReqSent += reqSent.get(); totalResReceived += resCount; //If not all the requests are processed if(reqIdReqMsgMap.size() != 0){ if(!operationRetry){ txnFailed=true; for(Map.Entry<UUID, JunoMessage> entry : reqIdReqMsgMap.entrySet()){ JunoMessage jMsg = entry.getValue(); JunoResponse junoResp = new JunoResponse(jMsg.getKey(),jMsg.getValue(),0,0,0,jMsg.getStatus().getOperationStatus()); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("isAsync", String.valueOf(isAsync)); trans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); trans.put("B_OPTYPE", "B_"+jMsg.getOpType().getOpType()); trans.put("batch_id",String.valueOf(batchOpaque)); trans.put("hex_key", Hex.encodeHexString(jMsg.getKey())); trans.put("req_id", jMsg.getReqId().toString()); trans.put("req_attempt",String.valueOf(retryCounter)); //trans.put("Operation",jMsg.getOpType().name()); trans.put("msg_size", jMsg.getMessageSize()+"|"+0); if(jMsg.isPayloadCompressed()){ trans.put("comp_%", Integer.toString(jMsg.getCompressionAchieved())); } long reqValSize = (jMsg.getValue() != null)? jMsg.getValue().length:0; trans.put("val_size", reqValSize+"|"+0); trans.put("server", socConfig.getJunoPool()); trans.put("status",jMsg.getStatus().getErrorText()); trans.put("Txn_STATUS", JunoStatusCode.ERROR.toString()); long duration = System.currentTimeMillis() - jMsg.getReqStartTime(); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"B_"+jMsg.getOpType().getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR,duration); trans.put("Duration", String.valueOf(duration)); LOGGER.info("TxnStatus : {}", trans); JunoMetrics.recordOpCount(socConfig.getJunoPool(), "B_"+jMsg.getOpType().getOpType(), junoResp.getStatus().getErrorText()); t.onNext(junoResp); } }else{ operationRetry=false; // Retry intervl will be between 10 - 100 msecs final int randVal = new Random().nextInt(MAX_RETRY_INTERVAL-MIN_RETRY_INTERVAL); Thread.sleep(randVal+MIN_RETRY_INTERVAL); continue; } } break; } rootTrans.put("num_request_sent",String.valueOf(totalReqSent)); rootTrans.put("num_response_received",String.valueOf(totalResReceived)); rootTrans.put("ROOT_TXN_STATUS", txnFailed?JunoStatusCode.ERROR.toString():JunoStatusCode.SUCCESS.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, "JUNO_BATCH",socConfig.getJunoPool(), txnFailed?JunoMetrics.ERROR:JunoMetrics.SUCCESS,System.currentTimeMillis() - opStartTime); LOGGER.info("RootTxnStatus : {}", rootTrans); t.onCompleted(); }catch(Exception e){ rootTrans.put("num_request_sent",String.valueOf(totalReqSent)); rootTrans.put("num_response_received",String.valueOf(totalResReceived)); rootTrans.put("ROOT_TXN_STATUS", JunoStatusCode.ERROR.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, "JUNO_BATCH", socConfig.getJunoPool(), JunoMetrics.ERROR,System.currentTimeMillis() - opStartTime); LOGGER.error("RootTxnStatus : {}", rootTrans); LOGGER.error(e.getMessage() +" ["+ this.configHolder.printProperties()+"]"); t.onError(new JunoException(OperationStatus.InternalError.getErrorText(),e)); }finally{ opaqueResMap.remove(batchOpaque); } }).subscribeOn(isAsync?Schedulers.io():Schedulers.immediate()); return resp; }catch(Exception e){ LOGGER.error(e.getMessage() +" ["+ this.configHolder.printProperties()+"]"); rootTrans.put("exception",e.getMessage()); rootTrans.put("ROOT_TXN_STATUS", JunoStatusCode.ERROR.toString()); LOGGER.error("RootTxnStatus : {}", rootTrans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"JUNO_BATCH", socConfig.getJunoPool(), JunoMetrics.ERROR, System.currentTimeMillis() - opStartTime); throw new JunoException(e.getMessage()); } } /** * Process Single requests in async manner. * @param req - JunoRequest * @param opType - Operation to be performed * @return JunoResponse - Juno response object with status. */ private Single<JunoResponse> processSingle(final JunoRequest req,final OperationType opType){ final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("isAsync", String.valueOf(isAsync)); trans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); trans.put("OPTYPE", opType.getOpType()); long opStartTime = System.currentTimeMillis(); SocketConfigHolder socConfig = new SocketConfigHolder(configHolder); try{ Single<JunoResponse> resp = Single.<JunoResponse>create(t-> { int opaque = 0; try{ final JunoMessage reqMsg = JunoClientUtil.validateInput(req,opType,configHolder); //TODO remove optype trans.put("hex_key", Hex.encodeHexString(reqMsg.getKey())); int retryCounter=0; boolean operationRetry = configHolder.isRetryEnabled(); while(retryCounter <= MAX_RETRY){ retryCounter++; opaque = opaqueGenarator.incrementAndGet(); // Check if connection is available to server if(!reqQueue.isConnected()){ throw new JunoException(OperationStatus.ConnectionError.getErrorText()); } OperationMessage operationMessage = JunoClientUtil.createOperationMessage(reqMsg,opaque); BlockingQueue<OperationMessage> respQueue = new ArrayBlockingQueue<OperationMessage>(1); opaqueResMap.put(opaque,respQueue); // Enqueue the message to netty transport if(!reqQueue.enqueue(operationMessage)){ opaqueResMap.remove(opaque); throw new JunoException(OperationStatus.QueueFull.getErrorText()); } //wait for response to arrive OperationMessage responseOpeMsg = respQueue.poll(configHolder.getResponseTimeout(), TimeUnit.MILLISECONDS); opaqueResMap.remove(opaque); if(responseOpeMsg == null){ if(operationRetry){ operationRetry=false; // Retry interval will be between 10 - 100 msecs final int randVal = new Random().nextInt(MAX_RETRY_INTERVAL-MIN_RETRY_INTERVAL); Thread.sleep(randVal+MIN_RETRY_INTERVAL); continue; } trans.put("req_id", operationMessage.getMetaComponent().getRequestIdString()); trans.put("req_attempt",String.valueOf(retryCounter)); trans.put("server", socConfig.getJunoPool()); trans.put("failRatioAverage", String.valueOf(reqQueue.getAverage())); reqQueue.incrementFailedAttempts(); throw new JunoException(OperationStatus.ResponseTimeout.getErrorText(),new TimeoutException()); } reqQueue.incrementSuccessfulAttempts(); // Decode the formed operation message and create the JunoResponse JunoMessage respMsg = JunoClientUtil.decodeOperationMessage(responseOpeMsg,reqMsg.getKey(),configHolder); if(respMsg.getStatus().getOperationStatus() != OperationStatus.Success){ if(operationRetry && JunoClientUtil.checkForRetry(respMsg.getStatus().getOperationStatus())){ JunoMetrics.recordOpCount(socConfig.getJunoPool(),opType.getOpType(), respMsg.getStatus().getErrorText()); operationRetry=false; // Retry interval will be between 10 - 100 msecs final int randVal = new Random().nextInt(MAX_RETRY_INTERVAL-MIN_RETRY_INTERVAL); Thread.sleep(randVal+MIN_RETRY_INTERVAL); continue; } } trans.put("req_id", operationMessage.getMetaComponent().getRequestIdString()); trans.put("req_attempt",String.valueOf(retryCounter)); JunoResponse junoResp = new JunoResponse(reqMsg.getKey(),respMsg.getValue(),respMsg.getVersion(), respMsg.getTimeToLiveSec(),respMsg.getCreationTime(),respMsg.getStatus().getOperationStatus()); //Check if we got the response only for our request by comparing the ID in request and response. if (!Arrays.equals(operationMessage.getMetaComponent().getRequestId(), responseOpeMsg.getMetaComponent().getRequestId())) { trans.put("resp_id", responseOpeMsg.getMetaComponent().getRequestIdString()); trans.put("server", socConfig.getJunoPool()); throw new JunoException("Response id does not match the request id."); } trans.put("ver", reqMsg.getVersion()+"|"+junoResp.getVersion()); trans.put("ttl", reqMsg.getTimeToLiveSec()+"|"+respMsg.getTimeToLiveSec()); if(reqMsg.isPayloadCompressed()){ trans.put("comp_%", Integer.toString(reqMsg.getCompressionAchieved())); } long reqValSize = (reqMsg.getValue() != null)? reqMsg.getValue().length:0; trans.put("val_size", reqValSize+"|"+respMsg.getValue().length); trans.put("msg_size", reqMsg.getMessageSize()+"|"+Long.toString(responseOpeMsg.getHeader().getMessageSize())); trans.put("server", responseOpeMsg.getServerIp()+":"+String.valueOf(socConfig.getPort())); if(respMsg.getReqHandlingTime() > 0){ trans.put("rht", ""+respMsg.getReqHandlingTime()); } //Return only on acceptable errors else throw exception. Set CAL ok if the error code is acceptable. if(junoResp.getStatus() == OperationStatus.Success || junoResp.getStatus() == OperationStatus.ConditionViolation || junoResp.getStatus() == OperationStatus.NoKey || junoResp.getStatus() == OperationStatus.RecordLocked || junoResp.getStatus() == OperationStatus.UniqueKeyViolation || junoResp.getStatus() == OperationStatus.TTLExtendFailure){ trans.put("status",junoResp.getStatus().getErrorText()); LOGGER.info(JunoStatusCode.SUCCESS + " SUCCESS {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(), JunoMetrics.SUCCESS, System.currentTimeMillis() - opStartTime); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), junoResp.getStatus().getErrorText()); t.onSuccess(junoResp); }else{ trans.put("server", socConfig.getJunoPool()); throw new JunoException(respMsg.getStatus().getErrorText()); } break; } } catch(JunoException e){ trans.put("server", socConfig.getJunoPool()); trans.put("status",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), e.getMessage()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(),JunoMetrics.ERROR,System.currentTimeMillis() - opStartTime); LOGGER.error(e.getMessage() +" ["+ this.configHolder.printProperties()+"]"); t.onError(e); } catch (IllegalArgumentException iae) { trans.put("server", socConfig.getJunoPool()); trans.put("details", iae.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR, System.currentTimeMillis() - opStartTime); if(iae.getCause() != null) JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), OperationStatus.IllegalArgument.getErrorText(),iae.getCause().getMessage()); else JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), OperationStatus.IllegalArgument.getErrorText()); LOGGER.error(iae.getMessage() + " [" + this.configHolder.getProperties() + "]"); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(), iae); } catch(Exception e){ trans.put("server", socConfig.getJunoPool()); trans.put("status",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), OperationStatus.InternalError.getErrorText()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(),JunoMetrics.ERROR, System.currentTimeMillis() - opStartTime); LOGGER.error(e.getMessage()+" [" + this.configHolder.getProperties()+"]"); t.onError(new JunoException(OperationStatus.InternalError.getErrorText(),e)); }finally{ opaqueResMap.remove(opaque); } }).subscribeOn(isAsync?Schedulers.io():Schedulers.immediate()); return resp; } catch (Exception e) { trans.put("server", socConfig.getJunoPool()); trans.put("details",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(),socConfig.getJunoPool(), JunoMetrics.ERROR,System.currentTimeMillis() - opStartTime); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(),OperationStatus.InternalError.getErrorText()); LOGGER.error(e.getMessage()+ " [" + this.configHolder.getProperties()+"]"); throw new JunoException(OperationStatus.InternalError.getErrorText(),e); } } }
166
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/impl/JunoClientFactoryInternal.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.impl; import com.paypal.juno.client.JunoAsyncClient; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientConfigHolder; import com.paypal.juno.client.JunoClientFactory; import com.paypal.juno.client.JunoReactClient; import com.paypal.juno.conf.JunoPropertiesProvider; import com.paypal.juno.util.JunoClientUtil; import java.net.URL; import javax.net.ssl.SSLContext; /** * This is the internal factory class for the JunoClient and is a public * class as an implementation side-effect. * <p> * This class should never be used directly by the Client. * * @see JunoClientFactory */ public final class JunoClientFactoryInternal { /** * Creates an new Juno client object with Juno properties file and with * JunoPropertiesProvider object. * * @param url URL of the Juno client properties file. * @return new Juno client object */ public final JunoClient newJunoClient(URL url) { JunoClientUtil.throwIfNull(url, "URL"); final JunoPropertiesProvider junoProps = new JunoPropertiesProvider(url); return newJunoClient(junoProps); } /** * Creates an new Juno client object with Juno properties file and with * JunoPropertiesProvider object. * * @param junoProps - Juno client properties. * @return new Juno client object */ public final JunoClient newJunoClient(JunoPropertiesProvider junoProps) { JunoClientUtil.throwIfNull(junoProps, "Juno Properties"); final JunoClientConfigHolder cfgHldr = new JunoClientConfigHolder(junoProps); return new JunoClientImpl(cfgHldr,null); } /** * Creates an new Juno client object with Juno properties and client supplied SSLContext. * * @param junoProps - Juno client properties. * @param ctx - Client supplied SSL Context. * @return new Juno client object */ public final JunoClient newJunoClient(JunoPropertiesProvider junoProps,SSLContext ctx) { JunoClientUtil.throwIfNull(junoProps, "Juno Properties"); final JunoClientConfigHolder cfgHldr = new JunoClientConfigHolder(junoProps); return new JunoClientImpl(cfgHldr,ctx); } /** * Creates an new Juno client object with Juno properties file. * * @param url URL of the Juno client properties file. * @return new Juno async client object */ public final JunoAsyncClient newJunoAsyncClient(URL url) { JunoClientUtil.throwIfNull(url, "URL"); final JunoPropertiesProvider junoProps = new JunoPropertiesProvider(url); return newJunoAsyncClient(junoProps); } /** * Creates an new Juno Async client object with J properties. * * @param junoProps - Juno client properties. * @return new Juno async client object */ public final JunoAsyncClient newJunoAsyncClient(JunoPropertiesProvider junoProps) { JunoClientUtil.throwIfNull(junoProps, "Juno Properties"); final JunoClientConfigHolder cfgHldr = new JunoClientConfigHolder(junoProps); return new JunoAsyncClientImpl(cfgHldr,null,true); } /** * Creates an new Juno Async client object with Juno properties and client supplied SSLContext. * * @param junoProps - Juno client properties. * @param ctx - Client supplied SSL Context. * @return new Juno async client object */ public final JunoAsyncClient newJunoAsyncClient(JunoPropertiesProvider junoProps,SSLContext ctx) { JunoClientUtil.throwIfNull(junoProps, "Juno Properties"); final JunoClientConfigHolder cfgHldr = new JunoClientConfigHolder(junoProps); return new JunoAsyncClientImpl(cfgHldr,ctx,true); } /** * Creates an new Juno react client object with Juno properties file. * * @param url URL of the Juno client properties file. * @return new Juno reactor client object */ public final JunoReactClient newJunoReactClient(URL url) { JunoClientUtil.throwIfNull(url, "URL"); final JunoPropertiesProvider junoProps = new JunoPropertiesProvider(url); return newJunoReactClient(junoProps); } /** * Creates an new Juno react client object with Juno properties. * * @param junoProps - Juno client properties. * @return new Juno reactor client object */ public final JunoReactClient newJunoReactClient(JunoPropertiesProvider junoProps) { JunoClientUtil.throwIfNull(junoProps, "Juno Properties"); final JunoClientConfigHolder cfgHldr = new JunoClientConfigHolder(junoProps); return new JunoReactClientImpl(cfgHldr,null,true); } /** * Creates an new Juno react client object with Juno properties and client supplied SSLContext. * * @param junoProps - Juno client properties. * @param ctx - Client supplied SSL Context. * @return new Juno async client object */ public final JunoReactClient newJunoReactClient(JunoPropertiesProvider junoProps, SSLContext ctx) { JunoClientUtil.throwIfNull(junoProps, "Juno Properties"); final JunoClientConfigHolder cfgHldr = new JunoClientConfigHolder(junoProps); return new JunoReactClientImpl(cfgHldr,ctx,true); } }
167
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/impl/JunoReactClientImpl.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.impl; import com.paypal.juno.client.JunoClientConfigHolder; 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.client.io.RecordContext; import com.paypal.juno.exception.JunoException; import com.paypal.juno.io.protocol.JunoMessage; import com.paypal.juno.io.protocol.OperationMessage; import com.paypal.juno.net.RequestQueue; import com.paypal.juno.transport.socket.SocketConfigHolder; import com.paypal.juno.util.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import org.apache.commons.codec.binary.Hex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; public class JunoReactClientImpl implements JunoReactClient { private final JunoClientConfigHolder configHolder; private final static AtomicInteger opaqueGenarator = new AtomicInteger(); private final RequestQueue reqQueue; private final ConcurrentHashMap<Integer, BlockingQueue<OperationMessage>> opaqueResMap; ExecutorService executor; private boolean isAsync = true; private static final int MAX_RETRY=1; private static final int MAX_RETRY_INTERVAL=90; private static final int MIN_RETRY_INTERVAL=10; // @Autowired // InstanceLocation instanceLocation; // private final String INSTANCE_GEO_PP_US = "PP_US"; /** * The logger. We make this a non-static member in order to prevent this * from being synchronized. */ private static final Logger LOGGER = LoggerFactory.getLogger(JunoReactClientImpl.class); JunoReactClientImpl(JunoClientConfigHolder config, SSLContext ctx, boolean isAsync){ this(config,ctx); this.isAsync = isAsync; } protected JunoReactClientImpl(JunoClientConfigHolder config,SSLContext ctx){ this.configHolder = config; SocketConfigHolder socCfg = new SocketConfigHolder(configHolder); socCfg.setCtx(ctx); reqQueue = RequestQueue.getInstance(socCfg); opaqueResMap = reqQueue.getOpaqueResMap(); executor = Executors.newCachedThreadPool(); } /** * 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 Mono<JunoResponse> create(byte[] key, byte[] value) throws JunoException { try{ final JunoRequest req = new JunoRequest(key,value,0,JunoRequest.OperationType.Create); return processSingle(req, JunoMessage.OperationType.Create); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); } catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,timeToLiveSec,JunoRequest.OperationType.Create); return processSingle(req, JunoMessage.OperationType.Create); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,0,0,JunoRequest.OperationType.Get); return processSingle(req, JunoMessage.OperationType.Get); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,0,timeToLiveSec,JunoRequest.OperationType.Get); return processSingle(req, JunoMessage.OperationType.Get); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,0,JunoRequest.OperationType.Update); return processSingle(req, JunoMessage.OperationType.Update); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,timeToLiveSec,JunoRequest.OperationType.Update); return processSingle(req, JunoMessage.OperationType.Update); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,JunoRequest.OperationType.Set); return processSingle(req, JunoMessage.OperationType.Set); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,value,0,timeToLiveSec,JunoRequest.OperationType.Set); return processSingle(req, JunoMessage.OperationType.Set); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * 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 { try{ final JunoRequest req = new JunoRequest(key,0,0,JunoRequest.OperationType.Destroy); return processSingle(req, JunoMessage.OperationType.Destroy); }catch(JunoException je){ throw je; // }catch (IllegalArgumentException iae) { // throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * Return the configured Juno properties for this current instance in a MAP */ public Map<String, String> getProperties() { return this.configHolder.getProperties(); } /** * 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 - Juno record context * @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 { try{ if(jcx == null){ throw new IllegalArgumentException("Record Context cannot be null"); } final JunoRequest req = new JunoRequest(jcx.getKey(),value,jcx.getVersion(),timeToLiveSec,jcx.getCreationTime(),JunoRequest.OperationType.Update); return processSingle(req, JunoMessage.OperationType.CompareAndSet); }catch(JunoException je){ throw je; }catch (IllegalArgumentException iae) { SocketConfigHolder socConfig = new SocketConfigHolder(configHolder); JunoMetrics.recordOpCount(socConfig.getJunoPool(), JunoRequest.OperationType.Update.getOpType(), OperationStatus.IllegalArgument.getErrorText(), iae.getMessage()); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(),iae); }catch(Exception e){ throw new JunoException(e.getMessage()); } } /** * This is the method for performing a batch of records * @param request - List of requests to be processed * Juno Request object * @return Observable<JunoResponse> - Emits a single response or Error with processing the request * @throws JunoException - Throws Exception if any exception while processing the request */ @Override public Flux<JunoResponse> doBatch(final Iterable<JunoRequest> request) throws JunoException { SocketConfigHolder socConfig = new SocketConfigHolder(configHolder); //Check for null and empty argument if(request == null){ JunoMetrics.recordOpCount(socConfig.getJunoPool(),"JUNO_BATCH", OperationStatus.IllegalArgument.getErrorText(),"null_request_list"); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(), new IllegalArgumentException("Request argument is null")); }else if(!request.iterator().hasNext()){ JunoMetrics.recordOpCount(socConfig.getJunoPool(), "JUNO_BATCH", OperationStatus.IllegalArgument.getErrorText(),"empty_request_list"); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(), new IllegalArgumentException("Empty request list supplied")); } long opStartTime = System.currentTimeMillis(); final Map<String,CharSequence> rootTrans = new HashMap<String, CharSequence>(); rootTrans.put("isAsync", String.valueOf(isAsync)); rootTrans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); rootTrans.put("OPTYPE", "JUNO_BATCH"); try{ Flux<JunoResponse> resp = Flux.<JunoResponse>create(t-> { boolean txnFailed = false; //This Map has all the requests along with their UUIDs. final ConcurrentHashMap<UUID,JunoMessage> reqIdReqMsgMap = JunoClientUtil.bulkValidate(request,t,configHolder,socConfig,isAsync); int batchSize = reqIdReqMsgMap.size(); AtomicInteger reqSent = new AtomicInteger(0); // Number of Requests sent //int resCount=0; // Number of Responses received int totalReqSent=0; int totalResReceived=0; Integer batchOpaque=0; try{ int retryCounter=0; boolean operationRetry = configHolder.isRetryEnabled(); rootTrans.put("num_request_for_this_batch",String.valueOf(batchSize)); while(retryCounter <= MAX_RETRY){ retryCounter++; reqSent.set(0); //Initialize the reqSent count to 0 int resCount = 0; //Initialize the resCount count to 0 batchOpaque = opaqueGenarator.incrementAndGet(); // Opaqueue for batch operation // Blocking queue to receive the response BlockingQueue<OperationMessage> respQueue = new ArrayBlockingQueue<OperationMessage>(reqIdReqMsgMap.size()); opaqueResMap.put(batchOpaque,respQueue); // Add the blocking queue to the opaqueRespMap if(!reqQueue.isConnected()){ throw new JunoException(OperationStatus.ConnectionError.getErrorText()); } SendBatch sndBatch = new SendBatch(batchOpaque,reqQueue,reqIdReqMsgMap,reqSent); Future<Integer> reqSender = executor.submit(sndBatch); rootTrans.put("batch_id_"+retryCounter,String.valueOf(batchOpaque)); long respTimeout = configHolder.getResponseTimeout(); //Receive the Responses for requests sent in request queue while (!reqSender.isDone() || reqSent.get() > resCount ){ // wait up to 100ms for the first request to be sent out if(reqSent.get() == 0){ long start = System.currentTimeMillis(); synchronized (reqSent) { reqSent.wait(100); } if((System.currentTimeMillis() - start) > 50) { rootTrans.put("NAME", "JUNO_BATCH_SEND_DELAYED"); rootTrans.put("timeToSendRequest",String.valueOf(System.currentTimeMillis() - start)); LOGGER.warn(JunoStatusCode.WARNING.toString() + " {} ", rootTrans); JunoMetrics.recordEventCount("JUNO_BATCH_SEND_DELAYED","UNKNOWN",JunoMetrics.WARNING); } } long startTime = System.currentTimeMillis(); //wait for response to arrive OperationMessage responseOpeMsg = respQueue.poll(respTimeout, TimeUnit.MILLISECONDS); respTimeout -= (System.currentTimeMillis() - startTime); respTimeout = respTimeout<0?0:respTimeout; //Just in case not to go negative //When response time out, the respQueue will return null if(responseOpeMsg == null){ reqQueue.incrementFailedAttempts(); break; } //Fetch the original request using the request ID JunoMessage reqMsg = reqIdReqMsgMap.get(responseOpeMsg.getMetaComponent().getRequestUuid()); if(reqMsg == null){ //This should not be the case. Do nothing just continue continue; } resCount++; // Got a valid response reqQueue.incrementSuccessfulAttempts(); //Decode the received operation message and create the JunoResponse JunoMessage respMessage = JunoClientUtil.decodeOperationMessage(responseOpeMsg,reqMsg.getKey(),configHolder); JunoResponse junoResp = new JunoResponse(respMessage.getKey(),respMessage.getValue(),respMessage.getVersion(), respMessage.getTimeToLiveSec(),respMessage.getCreationTime(),respMessage.getStatus().getOperationStatus()); if(respMessage.getStatus().getOperationStatus() != OperationStatus.Success){ //Check if retry is configured and the error is a retryable error if(operationRetry && JunoClientUtil.checkForRetry(respMessage.getStatus().getOperationStatus())){ JunoMetrics.recordOpCount(socConfig.getJunoPool(),"B_"+reqMsg.getOpType().getOpType(), respMessage.getStatus().getErrorText()); continue; } } //Remove the request from reqMap once there is a successful response reqIdReqMsgMap.remove(responseOpeMsg.getMetaComponent().getRequestUuid()); //Add CAL for the responses. final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("isAsync", String.valueOf(isAsync)); trans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); trans.put("B_OPTYPE", "B_"+reqMsg.getOpType().getOpType()); trans.put("batch_id",String.valueOf(batchOpaque)); trans.put("hex_key", Hex.encodeHexString(reqMsg.getKey()).toUpperCase()); trans.put("req_id", responseOpeMsg.getMetaComponent().getRequestIdString()); trans.put("req_attempt",String.valueOf(retryCounter)); trans.put("ver", reqMsg.getVersion()+"|"+respMessage.getVersion()); trans.put("ttl", reqMsg.getTimeToLiveSec()+"|"+respMessage.getTimeToLiveSec()); trans.put("msg_size", reqMsg.getMessageSize()+"|"+Long.toString(responseOpeMsg.getHeader().getMessageSize())); if(reqMsg.isPayloadCompressed()){ trans.put("comp_%", Integer.toString(reqMsg.getCompressionAchieved())); } long reqValSize = (reqMsg.getValue() != null)? reqMsg.getValue().length:0; trans.put("val_size", reqValSize+"|"+respMessage.getValue().length); trans.put("server", responseOpeMsg.getServerIp()+":"+String.valueOf(socConfig.getPort())); if(respMessage.getReqHandlingTime() > 0){ trans.put("rht", ""+respMessage.getReqHandlingTime()); } trans.put("status", respMessage.getStatus().getErrorText()); long duration = System.currentTimeMillis() - reqMsg.getReqStartTime(); //Set CAL ok if the error code is acceptable. if(junoResp.getStatus().isTxnOk()){ trans.put("STATUS", JunoStatusCode.SUCCESS.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"B_"+reqMsg.getOpType().getOpType(), socConfig.getJunoPool(), JunoMetrics.SUCCESS, duration); }else{ txnFailed = true; trans.put("STATUS", JunoStatusCode.ERROR.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"B_"+reqMsg.getOpType().getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR, duration); } JunoMetrics.recordOpCount(socConfig.getJunoPool(),"B_"+reqMsg.getOpType().getOpType(),respMessage.getStatus().getErrorText()); trans.put("Duration", String.valueOf(duration)); LOGGER.info("TxnStatus : {}", trans); t.next(junoResp); } //remove the respQueue for the current batchOpaque. So that retry will use a different opaque. opaqueResMap.remove(batchOpaque); totalReqSent += reqSent.get(); totalResReceived += resCount; //If not all the requests are processed if(reqIdReqMsgMap.size() != 0){ if(!operationRetry){ txnFailed=true; for(Map.Entry<UUID, JunoMessage> entry : reqIdReqMsgMap.entrySet()){ JunoMessage jMsg = entry.getValue(); JunoResponse junoResp = new JunoResponse(jMsg.getKey(),jMsg.getValue(),0,0,0,jMsg.getStatus().getOperationStatus()); final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("isAsync", String.valueOf(isAsync)); trans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); trans.put("B_OPTYPE", "B_"+jMsg.getOpType().getOpType()); trans.put("batch_id",String.valueOf(batchOpaque)); trans.put("hex_key", Hex.encodeHexString(jMsg.getKey())); trans.put("req_id", jMsg.getReqId().toString()); trans.put("req_attempt",String.valueOf(retryCounter)); //trans.put("Operation",jMsg.getOpType().getOpType()); trans.put("msg_size", jMsg.getMessageSize()+"|"+0); if(jMsg.isPayloadCompressed()){ trans.put("comp_%", Integer.toString(jMsg.getCompressionAchieved())); } long reqValSize = (jMsg.getValue() != null)? jMsg.getValue().length:0; trans.put("val_size", reqValSize+"|"+0); trans.put("server", socConfig.getJunoPool()); trans.put("status",jMsg.getStatus().getErrorText()); trans.put("Txn_STATUS", JunoStatusCode.ERROR.toString());; long duration = System.currentTimeMillis() - jMsg.getReqStartTime(); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC,"B_"+jMsg.getOpType().getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR,duration); trans.put("Duration", String.valueOf(duration)); LOGGER.info("TxnStatus : {}", trans); JunoMetrics.recordOpCount(socConfig.getJunoPool(), "B_"+jMsg.getOpType().getOpType(), junoResp.getStatus().getErrorText()); t.next(junoResp); } }else{ operationRetry=false; // Retry intervl will be between 10 - 100 msecs final int randVal = new Random().nextInt(MAX_RETRY_INTERVAL-MIN_RETRY_INTERVAL); Thread.sleep(randVal+MIN_RETRY_INTERVAL); continue; } } break; } rootTrans.put("num_request_sent",String.valueOf(totalReqSent)); rootTrans.put("num_response_received",String.valueOf(totalResReceived)); rootTrans.put("ROOT_TXN_STATUS", txnFailed?JunoStatusCode.ERROR.toString():JunoStatusCode.SUCCESS.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, "JUNO_BATCH", socConfig.getJunoPool(), txnFailed?JunoMetrics.ERROR:JunoMetrics.SUCCESS, System.currentTimeMillis() - opStartTime); LOGGER.info("RootTxnStatus : {}", rootTrans); t.complete(); }catch(Exception e){ rootTrans.put("num_request_sent",String.valueOf(totalReqSent)); rootTrans.put("num_response_received",String.valueOf(totalResReceived)); rootTrans.put("ROOT_TXN_STATUS", JunoStatusCode.ERROR.toString()); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, "JUNO_BATCH",socConfig.getJunoPool(), JunoMetrics.ERROR, System.currentTimeMillis() - opStartTime); LOGGER.error("RootTxnStatus : {}", rootTrans); LOGGER.error(e.getMessage() +" ["+ this.configHolder.printProperties()+"]"); t.error(new JunoException(OperationStatus.InternalError.getErrorText(),e)); }finally{ opaqueResMap.remove(batchOpaque); } }).subscribeOn(isAsync? Schedulers.boundedElastic():Schedulers.immediate()); return resp; }catch(Exception e){ LOGGER.error(e.getMessage() +" ["+ this.configHolder.printProperties()+"]"); rootTrans.put("exception",e.getMessage()); rootTrans.put("ROOT_TXN_STATUS", JunoStatusCode.ERROR.toString()); LOGGER.error("RootTxnStatus : {}", rootTrans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, "JUNO_BATCH", socConfig.getJunoPool(), JunoMetrics.ERROR, System.currentTimeMillis() - opStartTime); throw new JunoException(e.getMessage()); } } /** * Process Single requests in async manner. * @param req - JunoRequest * @param opType - Operation to be performed * @return JunoResponse - Juno response object with status. */ private Mono<JunoResponse> processSingle(final JunoRequest req, final JunoMessage.OperationType opType){ // CAL initialization final Map<String,CharSequence> trans = new HashMap<String, CharSequence>(); trans.put("isAsync", String.valueOf(isAsync)); trans.put("USE_SSL", configHolder.getUseSSL()? JunoConstants.JUNO_SSL_CLIENT : JunoConstants.JUNO_CLIENT); trans.put("OPTYPE", opType.getOpType()); long opStartTime = System.currentTimeMillis(); SocketConfigHolder socConfig = new SocketConfigHolder(configHolder); try{ Mono<JunoResponse> resp = Mono.<JunoResponse>create(t-> { int opaque = 0; try{ final JunoMessage reqMsg = JunoClientUtil.validateInput(req, opType, configHolder); //TODO remove optype trans.put("hex_key", Hex.encodeHexString(reqMsg.getKey())); int retryCounter=0; boolean operationRetry = configHolder.isRetryEnabled(); while(retryCounter <= MAX_RETRY){ retryCounter++; opaque = opaqueGenarator.incrementAndGet(); // Check if connection is available to server if(!reqQueue.isConnected()){ throw new JunoException(OperationStatus.ConnectionError.getErrorText()); } OperationMessage operationMessage = JunoClientUtil.createOperationMessage(reqMsg,opaque); BlockingQueue<OperationMessage> respQueue = new ArrayBlockingQueue<OperationMessage>(1); opaqueResMap.put(opaque,respQueue); // Enqueue the message to netty transport if(!reqQueue.enqueue(operationMessage)){ opaqueResMap.remove(opaque); throw new JunoException(OperationStatus.QueueFull.getErrorText()); } //wait for response to arrive OperationMessage responseOpeMsg = respQueue.poll(configHolder.getResponseTimeout(), TimeUnit.MILLISECONDS); opaqueResMap.remove(opaque); if(responseOpeMsg == null){ if(operationRetry){ operationRetry=false; // Retry interval will be between 10 - 100 msecs final int randVal = new Random().nextInt(MAX_RETRY_INTERVAL-MIN_RETRY_INTERVAL); Thread.sleep(randVal+MIN_RETRY_INTERVAL); continue; } trans.put("req_id", operationMessage.getMetaComponent().getRequestIdString()); trans.put("req_attempt",String.valueOf(retryCounter)); trans.put("server", socConfig.getJunoPool()); trans.put("failRatioAverage", String.valueOf(reqQueue.getAverage())); reqQueue.incrementFailedAttempts(); throw new JunoException(OperationStatus.ResponseTimeout.getErrorText(),new TimeoutException()); } reqQueue.incrementSuccessfulAttempts(); // Decode the formed operation message and create the JunoResponse JunoMessage respMsg = JunoClientUtil.decodeOperationMessage(responseOpeMsg,reqMsg.getKey(),configHolder); if(respMsg.getStatus().getOperationStatus() != OperationStatus.Success){ if(operationRetry && JunoClientUtil.checkForRetry(respMsg.getStatus().getOperationStatus())){ JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), respMsg.getStatus().getErrorText()); operationRetry=false; // Retry intervl will be between 10 - 100 msecs final int randVal = new Random().nextInt(MAX_RETRY_INTERVAL-MIN_RETRY_INTERVAL); Thread.sleep(randVal+MIN_RETRY_INTERVAL); continue; } } trans.put("req_id", operationMessage.getMetaComponent().getRequestIdString()); trans.put("req_attempt",String.valueOf(retryCounter)); JunoResponse junoResp = new JunoResponse(reqMsg.getKey(),respMsg.getValue(),respMsg.getVersion(), respMsg.getTimeToLiveSec(),respMsg.getCreationTime(),respMsg.getStatus().getOperationStatus()); //Check if we got the response only for our request by comparing the ID in request and response. if (!Arrays.equals(operationMessage.getMetaComponent().getRequestId(), responseOpeMsg.getMetaComponent().getRequestId())) { trans.put("resp_id", responseOpeMsg.getMetaComponent().getRequestIdString()); trans.put("server", socConfig.getJunoPool()); throw new JunoException("Response id does not match the request id."); } trans.put("ver", reqMsg.getVersion()+"|"+junoResp.getVersion()); trans.put("ttl", reqMsg.getTimeToLiveSec()+"|"+respMsg.getTimeToLiveSec()); if(reqMsg.isPayloadCompressed()){ trans.put("comp_%", Integer.toString(reqMsg.getCompressionAchieved())); } long reqValSize = (reqMsg.getValue() != null)? reqMsg.getValue().length:0; trans.put("val_size", reqValSize+"|"+respMsg.getValue().length); trans.put("msg_size", reqMsg.getMessageSize()+"|"+Long.toString(responseOpeMsg.getHeader().getMessageSize())); trans.put("server", responseOpeMsg.getServerIp()+":"+String.valueOf(socConfig.getPort())); if(respMsg.getReqHandlingTime() > 0){ trans.put("rht", ""+respMsg.getReqHandlingTime()); } //Return only on acceptable errors else throw exception. Set CAL ok if the error code is acceptable. if(junoResp.getStatus() == OperationStatus.Success || junoResp.getStatus() == OperationStatus.ConditionViolation || junoResp.getStatus() == OperationStatus.NoKey || junoResp.getStatus() == OperationStatus.RecordLocked || junoResp.getStatus() == OperationStatus.UniqueKeyViolation || junoResp.getStatus() == OperationStatus.TTLExtendFailure){ trans.put("status",junoResp.getStatus().getErrorText()); LOGGER.info(JunoStatusCode.SUCCESS + " SUCCESS {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(), JunoMetrics.SUCCESS,System.currentTimeMillis() - opStartTime); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), junoResp.getStatus().getErrorText()); t.success(junoResp); }else{ trans.put("server", socConfig.getJunoPool()); throw new JunoException(respMsg.getStatus().getErrorText()); } break; } } catch(JunoException e){ trans.put("server", socConfig.getJunoPool()); trans.put("status",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR,System.currentTimeMillis() - opStartTime); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), e.getMessage()); LOGGER.error(e.getMessage() +" ["+ this.configHolder.printProperties()+"]"); t.error(e); } catch (IllegalArgumentException iae) { trans.put("server", socConfig.getJunoPool()); trans.put("details", iae.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR, System.currentTimeMillis() - opStartTime); if(iae.getCause() != null) JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), OperationStatus.IllegalArgument.getErrorText(), iae.getCause().getMessage()); else JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), OperationStatus.IllegalArgument.getErrorText()); LOGGER.error(iae.getMessage() + " [" + this.configHolder.getProperties() + "]"); throw new JunoException(OperationStatus.IllegalArgument.getErrorText(), iae); } catch(Exception e){ trans.put("server", socConfig.getJunoPool()); trans.put("status",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(), socConfig.getJunoPool(), JunoMetrics.ERROR,System.currentTimeMillis() - opStartTime); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(), OperationStatus.InternalError.getErrorText()); LOGGER.error(e.getMessage()+" [" + this.configHolder.getProperties()+"]"); t.error(new JunoException(OperationStatus.InternalError.getErrorText(),e)); } finally { opaqueResMap.remove(opaque); } }).subscribeOn(isAsync? Schedulers.boundedElastic():Schedulers.immediate()); return resp; } catch (Exception e) { trans.put("server", socConfig.getJunoPool()); trans.put("details",e.getMessage()); LOGGER.error(JunoStatusCode.ERROR + " ERROR {} ", trans); JunoMetrics.recordOpTimer(JunoMetrics.JUNO_LATENCY_METRIC, opType.getOpType(),socConfig.getJunoPool(), JunoMetrics.ERROR,System.currentTimeMillis() - opStartTime); JunoMetrics.recordOpCount(socConfig.getJunoPool(), opType.getOpType(),OperationStatus.InternalError.getErrorText()); LOGGER.error(e.getMessage()+ " [" + this.configHolder.getProperties()+"]"); throw new JunoException(OperationStatus.InternalError.getErrorText(),e); } } }
168
0
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client
Create_ds/junodb/client/Java/Juno/juno-client-impl/src/main/java/com/paypal/juno/client/impl/JunoClientImpl.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.impl; import com.paypal.juno.client.JunoClient; import com.paypal.juno.client.JunoClientConfigHolder; 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.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; class JunoClientImpl implements JunoClient{ JunoReactClientImpl reactClient; /** * Creates JunoReactClient object which will be used for the * rest of the methods to do the blocking call on their respective * async operations * @param config * @pram ctx - SSL context */ public JunoClientImpl(JunoClientConfigHolder config,SSLContext ctx){ reactClient = new JunoReactClientImpl(config,ctx,false); } /** * 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 { return reactClient.create(key,value).block(); } /** * 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 { return reactClient.create(key, value, timeToLiveSec).block(); } /** * 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 { return reactClient.get(key).block(); } /** * 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 { return reactClient.get(key, timeToLiveSec).block(); } /** * 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 { return reactClient.update(key, value).block(); } /** * 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 { return reactClient.update(key, value, timeToLiveSec).block(); } /** * 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 { return reactClient.set(key, value).block(); } /** * 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 { return reactClient.set(key, value, timeToLiveSec).block(); } /** * Perform batch operations * @param request - List of request to be processed * @return List of JunoResponses - Juno Response object which contains the status of the operation * @throws JunoException - Throws Exception if any exception while processing the request */ public Iterable<JunoResponse> doBatch(Iterable<JunoRequest> request) throws JunoException { Iterable<JunoResponse> jRes = reactClient.doBatch(request).toIterable(); List<JunoResponse> respList = new ArrayList<>(); for(JunoResponse resp : jRes){ respList.add(resp); } return respList; } /** * 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 { return reactClient.delete(key).block(); } /** * 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 { return reactClient.compareAndSet(jcx, value, timeToLiveSec).block(); } /** * Return the configured Juno properties for this current instance in a MAP */ public Map<String, String> getProperties() { return reactClient.getProperties(); } }
169
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/TestGraphNode.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.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.test.utils.RandomGraph; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author reto, mir */ @RunWith(JUnitPlatform.class) public class TestGraphNode { @Test public void nodeContext() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); g.add(new TripleImpl(bNode1, property2, property1)); g.add(new TripleImpl(bNode2, property2, bNode1)); g.add(new TripleImpl(property1, property1, bNode2)); g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); GraphNode n = new GraphNode(bNode1, g); Assertions.assertEquals(4, n.getNodeContext().size()); n.deleteNodeContext(); Assertions.assertEquals(1, g.size()); Assertions.assertFalse(n.getObjects(property2).hasNext()); } @Test public void addNode() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); GraphNode n = new GraphNode(bNode1, g); n.addProperty(property1, bNode2); Assertions.assertEquals(1, g.size()); } @Test public void testGetSubjectAndObjectNodes() { RandomGraph graph = new RandomGraph(500, 20, new SimpleGraph()); for (int j = 0; j < 200; j++) { Triple randomTriple = graph.getRandomTriple(); GraphNode node = new GraphNode(randomTriple.getSubject(), graph); Iterator<IRI> properties = node.getProperties(); while (properties.hasNext()) { IRI property = properties.next(); Set<RDFTerm> objects = createSet(node.getObjects(property)); Iterator<GraphNode> objectNodes = node.getObjectNodes(property); while (objectNodes.hasNext()) { GraphNode graphNode = objectNodes.next(); Assertions.assertTrue(objects.contains(graphNode.getNode())); } } } for (int j = 0; j < 200; j++) { Triple randomTriple = graph.getRandomTriple(); GraphNode node = new GraphNode(randomTriple.getObject(), graph); Iterator<IRI> properties = node.getProperties(); while (properties.hasNext()) { IRI property = properties.next(); Set<RDFTerm> subjects = createSet(node.getSubjects(property)); Iterator<GraphNode> subjectNodes = node.getSubjectNodes(property); while (subjectNodes.hasNext()) { GraphNode graphNode = subjectNodes.next(); Assertions.assertTrue(subjects.contains(graphNode.getNode())); } } } } @Test public void getAvailableProperties() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); IRI property3 = new IRI("http://example.org/property3"); IRI property4 = new IRI("http://example.org/property4"); ArrayList<IRI> props = new ArrayList<IRI>(); props.add(property1); props.add(property2); props.add(property3); props.add(property4); GraphNode n = new GraphNode(bNode1, g); n.addProperty(property1, bNode2); n.addProperty(property2, bNode2); n.addProperty(property3, bNode2); n.addProperty(property4, bNode2); Iterator<IRI> properties = n.getProperties(); int i = 0; while (properties.hasNext()) { i++; IRI prop = properties.next(); Assertions.assertTrue(props.contains(prop)); props.remove(prop); } Assertions.assertEquals(i, 4); Assertions.assertEquals(props.size(), 0); } @Test public void deleteAll() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); //the two properties two be deleted g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); //this 3 properties should stay g.add(new TripleImpl(bNode1, property2, property1)); g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); GraphNode n = new GraphNode(bNode1, g); n.deleteProperties(property1); Assertions.assertEquals(3, g.size()); } @Test public void deleteSingleProperty() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); //the properties two be deleted g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); //this 4 properties should stay g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); g.add(new TripleImpl(bNode1, property2, property1)); g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); GraphNode n = new GraphNode(bNode1, g); n.deleteProperty(property1, new PlainLiteralImpl("literal")); Assertions.assertEquals(4, g.size()); } @Test public void replaceWith() { Graph initialGraph = new SimpleGraph(); BlankNode bNode1 = new BlankNode(); BlankNode bNode2 = new BlankNode(); BlankNode newBnode = new BlankNode(); IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); IRI newIRI = new IRI("http://example.org/newName"); Literal literal1 = new PlainLiteralImpl("literal"); Literal literal2 = new PlainLiteralImpl("bla bla"); Triple triple1 = new TripleImpl(bNode1, property1, literal1); Triple triple2 = new TripleImpl(bNode1, property2, property1); Triple triple3 = new TripleImpl(bNode2, property2, bNode1); Triple triple4 = new TripleImpl(property1, property1, bNode2); Triple triple5 = new TripleImpl(property1, property1, literal2); initialGraph.add(triple1); initialGraph.add(triple2); initialGraph.add(triple3); initialGraph.add(triple4); initialGraph.add(triple5); GraphNode node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newIRI, true); Assertions.assertEquals(5, node.getGraph().size()); Triple expectedTriple1 = new TripleImpl(bNode1, newIRI, literal1); Triple expectedTriple2 = new TripleImpl(bNode1, property2, newIRI); Triple expectedTriple3 = new TripleImpl(newIRI, newIRI, bNode2); Triple expectedTriple4 = new TripleImpl(newIRI, newIRI, literal2); Assertions.assertTrue(node.getGraph().contains(expectedTriple1)); Assertions.assertTrue(node.getGraph().contains(expectedTriple2)); Assertions.assertTrue(node.getGraph().contains(expectedTriple3)); Assertions.assertTrue(node.getGraph().contains(expectedTriple4)); Assertions.assertFalse(node.getGraph().contains(triple1)); Assertions.assertFalse(node.getGraph().contains(triple2)); Assertions.assertFalse(node.getGraph().contains(triple4)); Assertions.assertFalse(node.getGraph().contains(triple5)); node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newBnode); Triple expectedTriple5 = new TripleImpl(bNode1, property2, newBnode); Triple expectedTriple6 = new TripleImpl(newBnode, property1, bNode2); Triple expectedTriple7 = new TripleImpl(newBnode, property1, literal2); Assertions.assertTrue(node.getGraph().contains(triple1)); Assertions.assertTrue(node.getGraph().contains(expectedTriple5)); Assertions.assertTrue(node.getGraph().contains(expectedTriple6)); Assertions.assertTrue(node.getGraph().contains(expectedTriple7)); node = new GraphNode(literal1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newBnode); Triple expectedTriple8 = new TripleImpl(bNode1, property1, newBnode); Assertions.assertTrue(node.getGraph().contains(expectedTriple8)); node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newIRI); Triple expectedTriple9 = new TripleImpl(bNode1, property2, newIRI); Triple expectedTriple10 = new TripleImpl(newIRI, property1, bNode2); Triple expectedTriple11 = new TripleImpl(newIRI, property1, literal2); Assertions.assertTrue(node.getGraph().contains(triple1)); Assertions.assertTrue(node.getGraph().contains(expectedTriple9)); Assertions.assertTrue(node.getGraph().contains(expectedTriple10)); Assertions.assertTrue(node.getGraph().contains(expectedTriple11)); } @Test public void equality() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); GraphNode n = new GraphNode(bNode1, g); n.addProperty(property1, bNode2); Assertions.assertTrue(n.equals(new GraphNode(bNode1, g))); Assertions.assertFalse(n.equals(new GraphNode(bNode2, g))); GraphNode n2 = null; Assertions.assertFalse(n.equals(n2)); } private Set<RDFTerm> createSet(Iterator<? extends RDFTerm> resources) { Set<RDFTerm> set = new HashSet<RDFTerm>(); while (resources.hasNext()) { RDFTerm resource = resources.next(); set.add(resource); } return set; } }
170
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/UnionGraphTest.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.clerezza.utils; import org.apache.clerezza.BlankNode; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.Triple; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.Iterator; /** * @author hasan */ @RunWith(JUnitPlatform.class) public class UnionGraphTest { private final IRI uriRef1 = new IRI("http://example.org/ontology#res1"); private final IRI uriRef2 = new IRI("http://example.org/ontology#res2"); private final IRI uriRef3 = new IRI("http://example.org/ontology#res3"); private final IRI uriRef4 = new IRI("http://example.org/ontology#res4"); @Test public void readAccess() { Graph graph = new SimpleGraph(); Graph graph2 = new SimpleGraph(); BlankNode bnode = new BlankNode() { }; graph.add(new TripleImpl(uriRef1, uriRef2, uriRef1)); graph2.add(new TripleImpl(bnode, uriRef1, uriRef3)); Graph unionGraph = new UnionGraph(graph, graph2); Iterator<Triple> unionTriples = unionGraph.iterator(); Assertions.assertTrue(unionTriples.hasNext()); unionTriples.next(); Assertions.assertTrue(unionTriples.hasNext()); unionTriples.next(); Assertions.assertFalse(unionTriples.hasNext()); Assertions.assertEquals(2, unionGraph.size()); } @Test public void writeAccess() { Graph graph = new SimpleGraph(); Graph graph2 = new SimpleGraph(); BlankNode bnode = new BlankNode() { }; graph2.add(new TripleImpl(bnode, uriRef1, uriRef3)); Graph unionGraph = new UnionGraph(graph, graph2); Assertions.assertEquals(1, unionGraph.size()); unionGraph.add(new TripleImpl(uriRef4, uriRef1, uriRef3)); Assertions.assertEquals(1, graph.size()); Assertions.assertEquals(2, unionGraph.size()); Assertions.assertEquals(1, graph2.size()); } }
171
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/GraphUtilsTest.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.clerezza.utils; import org.apache.clerezza.BlankNode; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; /** * @author reto */ @RunWith(JUnitPlatform.class) public class GraphUtilsTest { final IRI u1 = new IRI("http://ex.org/1"); final IRI u2 = new IRI("http://ex.org/2"); final IRI u3 = new IRI("http://ex.org/3"); @Test public void removeSubGraph() throws GraphUtils.NoSuchSubGraphException { Graph baseGraph = createBaseGraph(); Graph subGraph = new SimpleGraph(); { BlankNode bNode1 = new BlankNode(); BlankNode bNode2 = new BlankNode(); subGraph.add(new TripleImpl(u1, u2, bNode2)); subGraph.add(new TripleImpl(bNode2, u2, bNode2)); subGraph.add(new TripleImpl(bNode2, u2, bNode1)); } GraphUtils.removeSubGraph(baseGraph, subGraph); Assertions.assertEquals(1, baseGraph.size()); } private Graph createBaseGraph() { Graph baseGraph = new SimpleGraph(); { BlankNode bNode1 = new BlankNode(); BlankNode bNode2 = new BlankNode(); baseGraph.add(new TripleImpl(u1, u2, bNode2)); baseGraph.add(new TripleImpl(bNode2, u2, bNode2)); baseGraph.add(new TripleImpl(bNode2, u2, bNode1)); baseGraph.add(new TripleImpl(u3, u2, u1)); } return baseGraph; } /** * It is required that the subgraph comprises the whole context of the BNodes it includes * * @throws org.apache.clerezza.utils.GraphUtils.NoSuchSubGraphException */ @Test public void removeIncompleteSubGraph() throws GraphUtils.NoSuchSubGraphException { Graph baseGraph = createBaseGraph(); Graph subGraph = new SimpleGraph(); { BlankNode bNode1 = new BlankNode(); BlankNode bNode2 = new BlankNode(); subGraph.add(new TripleImpl(u1, u2, bNode2)); subGraph.add(new TripleImpl(bNode2, u2, bNode2)); } Assertions.assertThrows( GraphUtils.NoSuchSubGraphException.class, () -> GraphUtils.removeSubGraph(baseGraph, subGraph) ); } @Test public void removeInvalidSubGraph() throws GraphUtils.NoSuchSubGraphException { Graph baseGraph = createBaseGraph(); Graph subGraph = new SimpleGraph(); { BlankNode bNode1 = new BlankNode(); BlankNode bNode2 = new BlankNode(); subGraph.add(new TripleImpl(u1, u2, bNode2)); subGraph.add(new TripleImpl(bNode2, u2, bNode2)); baseGraph.add(new TripleImpl(bNode2, u2, bNode1)); baseGraph.add(new TripleImpl(bNode2, u2, new BlankNode())); } Assertions.assertThrows( GraphUtils.NoSuchSubGraphException.class, () -> GraphUtils.removeSubGraph(baseGraph, subGraph) ); } }
172
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/RdfListTest.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.clerezza.utils; import org.apache.clerezza.BlankNode; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.RDFTerm; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.List; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author rbn */ @RunWith(JUnitPlatform.class) public class RdfListTest { @Test public void listCreationAndAccess() { Graph tc = new SimpleGraph(); List<RDFTerm> list = new RdfList(new IRI("http://example.org/mytest"), tc); assertEquals(0, list.size()); list.add(new PlainLiteralImpl("hello")); list.add(new PlainLiteralImpl("world")); assertEquals(new PlainLiteralImpl("hello"), list.get(0)); assertEquals(new PlainLiteralImpl("world"), list.get(1)); assertEquals(2, list.size()); list.add(new PlainLiteralImpl("welcome")); assertEquals(3, list.size()); assertEquals(new PlainLiteralImpl("welcome"), list.get(2)); list.add(1, new PlainLiteralImpl("interesting")); assertEquals(4, list.size()); assertEquals(new PlainLiteralImpl("interesting"), list.get(1)); assertEquals(new PlainLiteralImpl("world"), list.get(2)); assertEquals(new PlainLiteralImpl("welcome"), list.get(3)); list.add(0, new PlainLiteralImpl("start")); assertEquals(5, list.size()); assertEquals(new PlainLiteralImpl("hello"), list.get(1)); assertEquals(new PlainLiteralImpl("interesting"), list.get(2)); List<RDFTerm> list2 = new RdfList(new IRI("http://example.org/mytest"), tc); assertEquals(5, list2.size()); assertEquals(new PlainLiteralImpl("hello"), list2.get(1)); assertEquals(new PlainLiteralImpl("interesting"), list2.get(2)); list2.remove(2); assertEquals(4, list2.size()); assertEquals(new PlainLiteralImpl("hello"), list2.get(1)); assertEquals(new PlainLiteralImpl("world"), list2.get(2)); while (list2.size() > 0) { list2.remove(0); } assertEquals(1, tc.size()); //list = rdf:nil statement list2.add(0, new PlainLiteralImpl("restart")); list2.add(1, new PlainLiteralImpl("over")); assertEquals(2, list2.size()); list2.add(new PlainLiteralImpl("2")); list2.add(new PlainLiteralImpl("3")); assertEquals(4, list2.size()); list2.add(new PlainLiteralImpl("4")); list2.add(new PlainLiteralImpl("5")); assertEquals(new PlainLiteralImpl("3"), list2.get(3)); } @Test public void listCreationAndAccess2() { Graph tc = new SimpleGraph(); List<RDFTerm> list = new RdfList(new IRI("http://example.org/mytest"), tc); assertEquals(0, list.size()); list.add(0, new PlainLiteralImpl("world")); list = new RdfList(new IRI("http://example.org/mytest"), tc); list.add(0, new PlainLiteralImpl("beautifuly")); list = new RdfList(new IRI("http://example.org/mytest"), tc); list.add(0, new PlainLiteralImpl("hello")); assertEquals(new PlainLiteralImpl("hello"), list.get(0)); assertEquals(new PlainLiteralImpl("beautifuly"), list.get(1)); assertEquals(new PlainLiteralImpl("world"), list.get(2)); } @Test public void listCreationAndAccess3() { Graph tc = new SimpleGraph(); List<RDFTerm> list = new RdfList(new IRI("http://example.org/mytest"), tc); assertEquals(0, list.size()); BlankNode node0 = new BlankNode() { }; BlankNode node1 = new BlankNode() { }; BlankNode node2 = new BlankNode() { }; list.add(0, node2); list.add(0, node1); list.add(0, node0); assertEquals(node0, list.get(0)); assertEquals(node1, list.get(1)); assertEquals(node2, list.get(2)); } @Test public void secondButLastElementAccessTest() { Graph tc = new SimpleGraph(); List<RDFTerm> list = new RdfList(new IRI("http://example.org/mytest2"), tc); list.add(new PlainLiteralImpl("hello")); list.add(new PlainLiteralImpl("world")); list.remove(1); assertEquals(1, list.size()); } @Test public void cleanGraphAfterRemoval() { Graph tc = new SimpleGraph(); List<RDFTerm> list = new RdfList(new IRI("http://example.org/mytest"), tc); list.add(new PlainLiteralImpl("hello")); list.add(new PlainLiteralImpl("world")); list.remove(1); assertEquals(2, tc.size()); } @Test public void findContainingListNodesAndfindContainingListsTest() { Graph tc = new SimpleGraph(); GraphNode listA = new GraphNode(new IRI("http:///listA"), tc); GraphNode listB = new GraphNode(new IRI("http:///listB"), tc); BlankNode element1 = new BlankNode(); BlankNode element2 = new BlankNode(); BlankNode element3 = new BlankNode(); BlankNode element4 = new BlankNode(); BlankNode element5 = new BlankNode(); RdfList rdfListA = new RdfList(listA); rdfListA.add(element1); rdfListA.add(element2); rdfListA.add(element3); rdfListA.add(element4); RdfList rdfListB = new RdfList(listB); rdfListB.add(element2); rdfListB.add(element4); rdfListB.add(element5); Set<GraphNode> containingListNodes = RdfList.findContainingListNodes( new GraphNode(element3, tc)); assertEquals(1, containingListNodes.size()); assertTrue(containingListNodes.contains(listA)); Set<RdfList> containingLists = RdfList.findContainingLists( new GraphNode(element3, tc)); assertEquals(1, containingLists.size()); assertTrue(containingLists.contains(rdfListA)); containingListNodes = RdfList.findContainingListNodes( new GraphNode(element4, tc)); assertEquals(2, containingListNodes.size()); assertTrue(containingListNodes.contains(listA)); assertTrue(containingListNodes.contains(listB)); containingLists = RdfList.findContainingLists( new GraphNode(element4, tc)); assertEquals(2, containingLists.size()); assertTrue(containingLists.contains(rdfListA)); assertTrue(containingLists.contains(rdfListB)); } }
173
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/IfpSmushTest.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.clerezza.utils; import org.apache.clerezza.BlankNode; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.ontologies.FOAF; import org.apache.clerezza.ontologies.OWL; import org.apache.clerezza.ontologies.RDF; import org.apache.clerezza.ontologies.RDFS; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; /** * @author reto */ @RunWith(JUnitPlatform.class) public class IfpSmushTest { private Graph ontology = new SimpleGraph(); { ontology.add(new TripleImpl(FOAF.mbox, RDF.type, OWL.InverseFunctionalProperty)); } @Test public void simpleBlankNode() { Graph mGraph = new SimpleGraph(); IRI mbox1 = new IRI("mailto:foo@example.org"); final BlankNode bNode1 = new BlankNode(); mGraph.add(new TripleImpl(bNode1, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(bNode1, RDFS.comment, new PlainLiteralImpl("a comment"))); final BlankNode bNode2 = new BlankNode(); mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(bNode2, RDFS.comment, new PlainLiteralImpl("another comment"))); Smusher.smush(mGraph, ontology); Assertions.assertEquals(3, mGraph.size()); } @Test public void overlappingEquivalenceClasses() { Graph mGraph = new SimpleGraph(); IRI mbox1 = new IRI("mailto:foo@example.org"); final BlankNode bNode1 = new BlankNode(); mGraph.add(new TripleImpl(bNode1, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(bNode1, RDFS.comment, new PlainLiteralImpl("a comment"))); final BlankNode bNode2 = new BlankNode(); IRI mbox2 = new IRI("mailto:bar@example.org"); mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox2)); mGraph.add(new TripleImpl(bNode2, RDFS.comment, new PlainLiteralImpl("another comment"))); final BlankNode bNode3 = new BlankNode(); mGraph.add(new TripleImpl(bNode3, FOAF.mbox, mbox2)); mGraph.add(new TripleImpl(bNode3, RDFS.comment, new PlainLiteralImpl("yet another comment"))); Smusher.smush(mGraph, ontology); Assertions.assertEquals(5, mGraph.size()); } @Test public void oneIRI() { Graph mGraph = new SimpleGraph(); IRI mbox1 = new IRI("mailto:foo@example.org"); final IRI resource = new IRI("http://example.org/"); mGraph.add(new TripleImpl(resource, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(resource, RDFS.comment, new PlainLiteralImpl("a comment"))); final BlankNode bNode2 = new BlankNode(); mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(bNode2, RDFS.comment, new PlainLiteralImpl("another comment"))); Smusher.smush(mGraph, ontology); Assertions.assertEquals(3, mGraph.size()); } @Test public void twoIRIs() { Graph mGraph = new SimpleGraph(); IRI mbox1 = new IRI("mailto:foo@example.org"); final IRI resource1 = new IRI("http://example.org/"); mGraph.add(new TripleImpl(resource1, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(resource1, RDFS.comment, new PlainLiteralImpl("a comment"))); final IRI resource2 = new IRI("http://2.example.org/"); mGraph.add(new TripleImpl(resource2, FOAF.mbox, mbox1)); mGraph.add(new TripleImpl(resource2, RDFS.comment, new PlainLiteralImpl("another comment"))); Smusher.smush(mGraph, ontology); Assertions.assertEquals(4, mGraph.size()); } }
174
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/SameAsSmushTest.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.clerezza.utils; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.Literal; import org.apache.clerezza.Triple; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.ontologies.FOAF; import org.apache.clerezza.ontologies.OWL; import org.apache.clerezza.ontologies.RDFS; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.Iterator; /** * @author reto */ @RunWith(JUnitPlatform.class) public class SameAsSmushTest { private final IRI uriA = new IRI("http://example.org/A"); private final IRI uriB = new IRI("http://example.org/B"); private final Literal lit = new PlainLiteralImpl("That's me (and you)"); private Graph sameAsStatements = new SimpleGraph(); { sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB)); } private Graph dataGraph = new SimpleGraph(); { dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB)); dataGraph.add(new TripleImpl(uriB, RDFS.label, lit)); dataGraph.add(new TripleImpl(uriA, RDFS.label, lit)); } @Test public void simple() { Assertions.assertEquals(3, dataGraph.size()); Smusher.sameAsSmush(dataGraph, sameAsStatements); Assertions.assertEquals(3, dataGraph.size()); Assertions.assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext()); //exactly one statement with literal Iterator<Triple> litStmts = dataGraph.filter(null, null, lit); Assertions.assertTrue(litStmts.hasNext()); Triple litStmt = litStmts.next(); Assertions.assertFalse(litStmts.hasNext()); Iterator<Triple> knowsStmts = dataGraph.filter(null, FOAF.knows, null); Assertions.assertTrue(knowsStmts.hasNext()); Triple knowStmt = knowsStmts.next(); Assertions.assertEquals(knowStmt.getSubject(), knowStmt.getObject()); Assertions.assertEquals(litStmt.getSubject(), knowStmt.getObject()); Assertions.assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject()); } }
175
0
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils
Create_ds/clerezza/api.utils/src/test/java/org/apache/clerezza/utils/smushing/SameAsSmushTest.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.clerezza.utils.smushing; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.Literal; import org.apache.clerezza.Triple; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.ontologies.FOAF; import org.apache.clerezza.ontologies.OWL; import org.apache.clerezza.ontologies.RDFS; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.Iterator; import java.util.Set; /** * @author reto */ @RunWith(JUnitPlatform.class) public class SameAsSmushTest { private final IRI uriA = new IRI("http://example.org/A"); private final IRI uriB = new IRI("http://example.org/B"); private final IRI uriC = new IRI("http://example.org/C"); private final Literal lit = new PlainLiteralImpl("That's me (and you)"); private Graph sameAsStatements = new SimpleGraph(); { sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB)); } private Graph dataGraph = new SimpleGraph(); { dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB)); dataGraph.add(new TripleImpl(uriB, RDFS.label, lit)); dataGraph.add(new TripleImpl(uriA, RDFS.label, lit)); } @Test public void simple() { SameAsSmusher smusher = new SameAsSmusher() { @Override protected IRI getPreferedIRI(Set<IRI> uriRefs) { if (!uriRefs.contains(uriA)) throw new RuntimeException("not the set we excpect"); if (!uriRefs.contains(uriB)) throw new RuntimeException("not the set we excpect"); return uriC; } }; Assertions.assertEquals(3, dataGraph.size()); smusher.smush(dataGraph, sameAsStatements, true); Assertions.assertEquals(4, dataGraph.size()); Assertions.assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext()); //exactly one statement with literal Iterator<Triple> litStmts = dataGraph.filter(null, null, lit); Assertions.assertTrue(litStmts.hasNext()); Triple litStmt = litStmts.next(); Assertions.assertFalse(litStmts.hasNext()); Iterator<Triple> knowsStmts = dataGraph.filter(null, FOAF.knows, null); Assertions.assertTrue(knowsStmts.hasNext()); Triple knowStmt = knowsStmts.next(); Assertions.assertEquals(knowStmt.getSubject(), knowStmt.getObject()); Assertions.assertEquals(litStmt.getSubject(), knowStmt.getObject()); Assertions.assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject()); Assertions.assertEquals(knowStmt.getSubject(), uriC); } }
176
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/UriMutatingGraph.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.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleImmutableGraph; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.locks.ReadWriteLock; /** * This wrapps a Triplecollection changing a prefix for the IRIs contained * in subject or object position. * <p> * Currently it only supports read opearations. * * @author reto */ public class UriMutatingGraph implements Graph { private final Graph base; private final String sourcePrefix; private final String targetPrefix; private final int sourcePrefixLength; private final int targetPrefixLength; public UriMutatingGraph(Graph base, String sourcePrefix, String targetPrefix) { this.base = base; this.sourcePrefix = sourcePrefix; sourcePrefixLength = sourcePrefix.length(); this.targetPrefix = targetPrefix; targetPrefixLength = targetPrefix.length(); } private <R extends RDFTerm> R toTargetRDFTerm(final R sourceRDFTerm) { if (sourceRDFTerm instanceof IRI) { final IRI sourceIRI = (IRI) sourceRDFTerm; if (sourceIRI.getUnicodeString().startsWith(sourcePrefix)) { final String uriRest = sourceIRI.getUnicodeString() .substring(sourcePrefixLength); return (R) new IRI(targetPrefix + uriRest); } } return sourceRDFTerm; } private Triple toTargetTriple(Triple triple) { if (triple == null) { return null; } return new TripleImpl(toTargetRDFTerm(triple.getSubject()), triple.getPredicate(), toTargetRDFTerm(triple.getObject())); } private <R extends RDFTerm> R toSourceRDFTerm(final R targetRDFTerm) { if (targetRDFTerm instanceof IRI) { final IRI sourceIRI = (IRI) targetRDFTerm; if (sourceIRI.getUnicodeString().startsWith(targetPrefix)) { final String uriRest = sourceIRI.getUnicodeString() .substring(targetPrefixLength); return (R) new IRI(sourcePrefix + uriRest); } } return targetRDFTerm; } private Triple toSourceTriple(Triple triple) { if (triple == null) { return null; } return new TripleImpl(toSourceRDFTerm(triple.getSubject()), triple.getPredicate(), toSourceRDFTerm(triple.getObject())); } @Override public Iterator<Triple> filter(BlankNodeOrIRI subject, IRI predicate, RDFTerm object) { final Iterator<Triple> baseIter = base.filter(toSourceRDFTerm(subject), predicate, toSourceRDFTerm(object)); return new WrappedIteraror(baseIter); } @Override public int size() { return base.size(); } @Override public boolean isEmpty() { return base.isEmpty(); } @Override public boolean contains(Object o) { return base.contains(toSourceTriple((Triple) o)); } @Override public Iterator<Triple> iterator() { return filter(null, null, null); } @Override public Object[] toArray() { Object[] result = base.toArray(); for (int i = 0; i < result.length; i++) { Triple triple = (Triple) result[i]; result[i] = toTargetTriple(triple); } return result; } @Override public <T> T[] toArray(T[] a) { T[] result = base.toArray(a); for (int i = 0; i < result.length; i++) { Triple triple = (Triple) result[i]; result[i] = (T) toTargetTriple(triple); } return result; } @Override public boolean add(Triple e) { throw new UnsupportedOperationException("Not supported."); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Not supported."); } @Override public boolean containsAll(Collection<?> c) { for (Object object : c) { if (!contains(object)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends Triple> c) { throw new UnsupportedOperationException("Not supported."); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported."); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("Not supported."); } @Override public void clear() { throw new UnsupportedOperationException("Not supported."); } @Override public ImmutableGraph getImmutableGraph() { return new SimpleImmutableGraph(this); } @Override public ReadWriteLock getLock() { return base.getLock(); } class WrappedIteraror implements Iterator<Triple> { private final Iterator<Triple> baseIter; private WrappedIteraror(Iterator<Triple> baseIter) { this.baseIter = baseIter; } @Override public boolean hasNext() { return baseIter.hasNext(); } @Override public Triple next() { return toTargetTriple(baseIter.next()); } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } } }
177
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/SeeAlsoExpander.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.clerezza.utils; import org.apache.clerezza.IRI; import org.apache.clerezza.RDFTerm; import org.apache.clerezza.Graph; import org.apache.clerezza.dataset.NoSuchEntityException; import org.apache.clerezza.dataset.TcManager; import org.apache.clerezza.ontologies.RDFS; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.locks.Lock; /** * Expands a GraphNode expanding SeeAlso-References of the node. * * @author reto */ public class SeeAlsoExpander { /** * using TcManger instead of TcProvider as this ensures LockableGraphs */ private final TcManager tcManager; public SeeAlsoExpander(TcManager tcManager) { this.tcManager = tcManager; } /** * expands a node dereferencing its rdfs:seeAlso references using the * tcManager associated to this instance. If the added TripleCollections * also associate rdfs:seeAlso properties to node this are expanded till * the maximum recursion depth specified. * * @param node the node to be expanded * @param recursion the maximum recursion depth * @return a new GraphNode over the union of the original and all expansion graphs */ public GraphNode expand(GraphNode node, int recursion) { Set<IRI> alreadyVisited = new HashSet(); Set<Graph> resultTripleCollections = new HashSet<Graph>(); resultTripleCollections.add(node.getGraph()); for (IRI uriRef : expand(node, alreadyVisited, recursion)) { try { resultTripleCollections.add(tcManager.getGraph(uriRef)); } catch (NoSuchEntityException e) { //ignore } } return new GraphNode(node.getNode(), new UnionGraph(resultTripleCollections.toArray( new Graph[resultTripleCollections.size()]))); } private Set<IRI> getSeeAlsoObjectUris(GraphNode node) { Set<IRI> result = new HashSet<IRI>(); Lock l = node.readLock(); l.lock(); try { Iterator<RDFTerm> objects = node.getObjects(RDFS.seeAlso); while (objects.hasNext()) { RDFTerm next = objects.next(); if (next instanceof IRI) { result.add((IRI) next); } } } finally { l.unlock(); } return result; } private Set<IRI> expand(GraphNode node, Set<IRI> alreadyVisited, int recursion) { Set<IRI> rdfSeeAlsoTargets = getSeeAlsoObjectUris(node); Set<IRI> result = new HashSet<IRI>(); result.addAll(rdfSeeAlsoTargets); recursion++; if (recursion > 0) { rdfSeeAlsoTargets.removeAll(alreadyVisited); alreadyVisited.addAll(rdfSeeAlsoTargets); for (IRI target : rdfSeeAlsoTargets) { try { result.addAll(expand(new GraphNode(node.getNode(), tcManager.getGraph(target)), alreadyVisited, recursion)); } catch (NoSuchEntityException e) { //ignore } } } return result; } }
178
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/GraphUtils.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.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Utility methods to manipulate <code>Graph</code>s * * @author reto */ public class GraphUtils { /** * Removes a subGraph from an Graph. The subGraph must match a subgraph of * Graph so that for every node in <code>subGraph</code> * each triple it appears in is also present in <code>mGraph</code>. Two * bnodes are considered equals if their contexts (as returned by * <code>GraphNode.getNodeContext</code> are equals. * * @param mGraph * @param subGraph * @throws org.apache.clerezza.utils.GraphUtils.NoSuchSubGraphException */ public static void removeSubGraph(Graph mGraph, Graph subGraph) throws NoSuchSubGraphException { //point to triples of mGraph that are to be removed (if something is removed) final Set<Triple> removingTriples = new HashSet<Triple>(); //we first check only the grounded triples and put the non-grounded in here: final Graph unGroundedTriples = new SimpleGraph(); for (Triple triple : subGraph) { if (isGrounded(triple)) { if (!mGraph.contains(triple)) { throw new NoSuchSubGraphException(); } removingTriples.add(triple); } else { unGroundedTriples.add(triple); } } //we first remove the context of bnodes we find in object position OBJ_BNODE_LOOP: while (true) { final Triple triple = getTripleWithBlankNodeObject(unGroundedTriples); if (triple == null) { break; } final GraphNode objectGN = new GraphNode(triple.getObject(), unGroundedTriples); BlankNodeOrIRI subject = triple.getSubject(); ImmutableGraph context = objectGN.getNodeContext(); Iterator<Triple> potentialIter = mGraph.filter(subject, triple.getPredicate(), null); while (potentialIter.hasNext()) { try { final Triple potentialTriple = potentialIter.next(); BlankNode potentialMatch = (BlankNode) potentialTriple.getObject(); final ImmutableGraph potentialContext = new GraphNode(potentialMatch, mGraph).getNodeContext(); if (potentialContext.equals(context)) { removingTriples.addAll(potentialContext); unGroundedTriples.removeAll(context); continue OBJ_BNODE_LOOP; } } catch (ClassCastException e) { continue; } } throw new NoSuchSubGraphException(); } SUBJ_BNODE_LOOP: while (true) { final Triple triple = getTripleWithBlankNodeSubject(unGroundedTriples); if (triple == null) { break; } final GraphNode subjectGN = new GraphNode(triple.getSubject(), unGroundedTriples); RDFTerm object = triple.getObject(); if (object instanceof BlankNode) { object = null; } ImmutableGraph context = subjectGN.getNodeContext(); Iterator<Triple> potentialIter = mGraph.filter(null, triple.getPredicate(), object); while (potentialIter.hasNext()) { try { final Triple potentialTriple = potentialIter.next(); BlankNode potentialMatch = (BlankNode) potentialTriple.getSubject(); final ImmutableGraph potentialContext = new GraphNode(potentialMatch, mGraph).getNodeContext(); if (potentialContext.equals(context)) { removingTriples.addAll(potentialContext); unGroundedTriples.removeAll(context); continue SUBJ_BNODE_LOOP; } } catch (ClassCastException e) { continue; } } throw new NoSuchSubGraphException(); } mGraph.removeAll(removingTriples); } private static boolean isGrounded(Triple triple) { if (triple.getSubject() instanceof BlankNode) { return false; } if (triple.getObject() instanceof BlankNode) { return false; } return true; } /** * retrun triples with a bnode only at object position * * @param triples * @return */ private static Triple getTripleWithBlankNodeObject(Graph triples) { for (Triple triple : triples) { if (triple.getSubject() instanceof BlankNode) { continue; } if (triple.getObject() instanceof BlankNode) { return triple; } } return null; } private static Triple getTripleWithBlankNodeSubject(Graph triples) { for (Triple triple : triples) { if (triple.getSubject() instanceof BlankNode) { return triple; } } return null; } public static class NoSuchSubGraphException extends Exception { } }
179
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/IRIUtil.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.clerezza.utils; /** * A utility class for IRI and String manipulations. * * @author tio */ public class IRIUtil { /** * Strips #x00 - #x1F and #x7F-#x9F from a Unicode string * * @param inputChars * @return the stripped string * @see <a href="http://www.w3.org/TR/rdf-concepts/#dfn-URI-reference"> * http://www.w3.org/TR/rdf-concepts/#dfn-URI-reference</a> and * replaces all US-ASCII space character with a "+". */ public static String stripNonIRIChars(CharSequence inputChars) { if (inputChars == null) { return ""; } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < inputChars.length(); i++) { char c = inputChars.charAt(i); if (!isIllegal(c)) { buffer.append(c); } } return buffer.toString().replaceAll("\\s+", "+"); } private static boolean isIllegal(char ch) { if ((ch >= 0x7F) && (ch <= 0x9F)) { return true; } return false; } }
180
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/UnionGraph.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.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.graph.AbstractGraph; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; /** * This class represents the union of multiple triple collections. A UnionGraph * appears like a merge of the different graphs (see. * http://www.w3.org/TR/rdf-mt/#graphdefs). * * @author hasan */ public class UnionGraph extends AbstractGraph { protected Graph[] baseTripleCollections; private Lock readLock; private Lock writeLock; /** * Constructs a UnionGraph over the specified baseTripleCollections. Write * and delete operations are forwarded to the first baseTripleCollections. * * @param baseTripleCollections the baseTripleCollections */ public UnionGraph(Graph... baseTripleCollections) { this.baseTripleCollections = baseTripleCollections; readLock = getPartialReadLock(0); writeLock = createWriteLock(); } @Override public int performSize() { int size = 0; for (Graph graph : baseTripleCollections) { size += graph.size(); } return size; } @Override public Iterator<Triple> performFilter(final BlankNodeOrIRI subject, final IRI predicate, final RDFTerm object) { if (baseTripleCollections.length == 0) { return new HashSet<Triple>(0).iterator(); } return new Iterator<Triple>() { int currentBaseTC = 0; Iterator<Triple> currentBaseIter = baseTripleCollections[0].filter( subject, predicate, object); private Triple lastReturned; @Override public boolean hasNext() { if (currentBaseIter.hasNext()) { return true; } if (currentBaseTC == baseTripleCollections.length - 1) { return false; } currentBaseTC++; currentBaseIter = baseTripleCollections[currentBaseTC].filter( subject, predicate, object); return hasNext(); } @Override public Triple next() { lastReturned = hasNext() ? currentBaseIter.next() : null; return lastReturned; } @Override public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } if (currentBaseTC == 0) { currentBaseIter.remove(); } lastReturned = null; } }; } @Override public boolean add(Triple e) { if (baseTripleCollections.length == 0) { throw new RuntimeException("no base graph for adding triples"); } return baseTripleCollections[0].add(e); } @Override public boolean remove(Object e) { if (baseTripleCollections.length == 0) { throw new RuntimeException("no base graph for removing triples"); } return baseTripleCollections[0].remove(e); } @Override public boolean equals(Object obj) { if (!(obj.getClass().equals(getClass()))) { return false; } UnionGraph other = (UnionGraph) obj; Set<Graph> otherGraphs = new HashSet(Arrays.asList(other.baseTripleCollections)); Set<Graph> thisGraphs = new HashSet(Arrays.asList(baseTripleCollections)); return thisGraphs.equals(otherGraphs) && baseTripleCollections[0].equals(other.baseTripleCollections[0]); } @Override public int hashCode() { int hash = 0; for (Graph graph : baseTripleCollections) { hash += graph.hashCode(); } hash *= baseTripleCollections[0].hashCode(); return hash; } @Override public ReadWriteLock getLock() { return readWriteLock; } private ReadWriteLock readWriteLock = new ReadWriteLock() { @Override public Lock readLock() { return readLock; } @Override public Lock writeLock() { return writeLock; } }; private Lock getPartialReadLock(int startPos) { ArrayList<Lock> resultList = new ArrayList<Lock>(); for (int i = startPos; i < baseTripleCollections.length; i++) { Graph graph = baseTripleCollections[i]; final Lock lock = graph.getLock().readLock(); resultList.add(lock); } return new UnionLock(resultList.toArray(new Lock[resultList.size()])); } private Lock createWriteLock() { Lock partialReadLock = getPartialReadLock(1); Lock baseWriteLock = (baseTripleCollections[0]).getLock().writeLock(); return new UnionLock(baseWriteLock, partialReadLock); } private static class UnionLock implements Lock { Lock[] locks; public UnionLock(Lock... locks) { this.locks = locks; } @Override public void lock() { boolean isLocked = false; while (!isLocked) { try { isLocked = tryLock(10000, TimeUnit.NANOSECONDS); } catch (InterruptedException ex) { } } } @Override public void lockInterruptibly() throws InterruptedException { Set<Lock> aquiredLocks = new HashSet<Lock>(); try { for (Lock lock : locks) { lock.lockInterruptibly(); aquiredLocks.add(lock); } } catch (InterruptedException e) { for (Lock lock : aquiredLocks) { lock.unlock(); } throw e; } } @Override public boolean tryLock() { Set<Lock> aquiredLocks = new HashSet<Lock>(); for (Lock lock : locks) { if (!lock.tryLock()) { for (Lock aquiredLock : aquiredLocks) { aquiredLock.unlock(); } return false; } aquiredLocks.add(lock); } return true; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { Set<Lock> aquiredLocks = new HashSet<Lock>(); long timeInNanos = unit.convert(time, TimeUnit.NANOSECONDS); long startTime = System.nanoTime(); try { for (Lock lock : locks) { if (!lock.tryLock((timeInNanos + startTime) - System.nanoTime(), TimeUnit.NANOSECONDS)) { for (Lock aquiredLock : aquiredLocks) { aquiredLock.unlock(); } return false; } aquiredLocks.add(lock); } } catch (InterruptedException e) { for (Lock lock : aquiredLocks) { lock.unlock(); } throw e; } return true; } @Override public void unlock() { for (Lock lock : locks) { lock.unlock(); } } @Override public Condition newCondition() { throw new UnsupportedOperationException("Conditions not supported."); } } }
181
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/Smusher.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.clerezza.utils; import org.apache.clerezza.Graph; import org.apache.clerezza.utils.smushing.IfpSmusher; import org.apache.clerezza.utils.smushing.SameAsSmusher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility to smush equivalent resources. For greater flexibility use the * classes in the smushing package. * * @author reto */ public class Smusher { static final Logger log = LoggerFactory.getLogger(Smusher.class); /** * smush mGaph given the ontological facts. Currently it does only one step * ifp smushin, i.e. only ifps are taken in account and only nodes that have * the same node as ifp object in the orignal graph are equates. (calling * the method a second time might lead to additional smushings.) * * @param mGraph * @param tBox */ public static void smush(Graph mGraph, Graph tBox) { new IfpSmusher().smush(mGraph, tBox); } /** * Smushes the specified graph adding owl:sameAs statements pointing to the new canonical IRI * * @param mGraph * @param owlSameStatements */ public static void sameAsSmush(Graph mGraph, Graph owlSameStatements) { new SameAsSmusher().smush(mGraph, owlSameStatements, true); } }
182
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/GraphNode.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.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.LiteralFactory; import java.util.*; import java.util.concurrent.locks.Lock; /** * This class represents a node in the context of a graph. It provides * utility methods to explore and modify its neighbourhood. The method * modifying the graph will throw an {@link UnsupportedOperationException} * it the underlying Graph in immutable (i.e. is a {@link ImmutableGraph}. * * @author reto, mir * @since 0.2 */ public class GraphNode { private final RDFTerm resource; private final Graph graph; /** * Create a GraphNode representing resource within graph. * * @param resource the resource this GraphNode represents * @param graph the Graph that describes the resource */ public GraphNode(RDFTerm resource, Graph graph) { if (resource == null) { throw new IllegalArgumentException("resource may not be null"); } if (graph == null) { throw new IllegalArgumentException("graph may not be null"); } this.resource = resource; this.graph = graph; } /** * Gets the graph the node represented by this instance is in * * @return the graph of this GraphNode */ public Graph getGraph() { return graph; } /** * Gets the unwrapped node * * @return the node represented by this GraphNode */ public RDFTerm getNode() { return resource; } /** * Deletes the context of a node * * @see #getNodeContext() */ public void deleteNodeContext() { for (Triple triple : getNodeContext()) { graph.remove(triple); } } /** * The context of a node are the triples containing a node * as subject or object and recursively the context of the b-nodes in any * of these statements. * * The triples in the ImmutableGraph returned by this method contain the same bnode * instances as in the original graph. * * @return the context of the node represented by the instance */ public ImmutableGraph getNodeContext() { Lock l = readLock(); l.lock(); try { final HashSet<RDFTerm> dontExpand = new HashSet<RDFTerm>(); dontExpand.add(resource); if (resource instanceof IRI) { return getContextOf((IRI) resource, dontExpand).getImmutableGraph(); } return getContextOf(resource, dontExpand).getImmutableGraph(); } finally { l.unlock(); } } private Graph getContextOf(IRI node, final Set<RDFTerm> dontExpand) { final String uriPrefix = node.getUnicodeString() + '#'; return getContextOf(node, dontExpand, new Acceptor() { @Override public boolean expand(RDFTerm resource) { if (resource instanceof BlankNode) { return true; } if (resource instanceof IRI) { return ((IRI) resource).getUnicodeString().startsWith(uriPrefix); } return false; } }); } /** * Returns the context of a <code>BlankNodeOrIRI</code> * * @param node * @param dontExpand a list of bnodes at which to stop expansion, if node * is a BlankNode it should be contained (potentially faster) * @return the context of a node */ private Graph getContextOf(RDFTerm node, final Set<RDFTerm> dontExpand) { return getContextOf(node, dontExpand, new Acceptor() { @Override public boolean expand(RDFTerm resource) { if (resource instanceof BlankNode) { return true; } return false; } }); } private interface Acceptor { boolean expand(RDFTerm resource); } private Graph getContextOf(RDFTerm node, final Set<RDFTerm> dontExpand, Acceptor acceptor) { Graph result = new SimpleGraph(); if (node instanceof BlankNodeOrIRI) { Iterator<Triple> forwardProperties = graph.filter((BlankNodeOrIRI) node, null, null); while (forwardProperties.hasNext()) { Triple triple = forwardProperties.next(); result.add(triple); RDFTerm object = triple.getObject(); if (acceptor.expand(object) && !dontExpand.contains(object)) { dontExpand.add(object); result.addAll(getContextOf(object, dontExpand, acceptor)); } } } Iterator<Triple> backwardProperties = graph.filter(null, null, node); while (backwardProperties.hasNext()) { Triple triple = backwardProperties.next(); result.add(triple); BlankNodeOrIRI subject = triple.getSubject(); if (acceptor.expand(subject) && !dontExpand.contains(subject)) { dontExpand.add(subject); result.addAll(getContextOf(subject, dontExpand, acceptor)); } } return result; } private <T> Iterator<T> getTypeSelectedObjects(IRI property, final Class<T> type) { final Iterator<RDFTerm> objects = getObjects(property); return new Iterator<T>() { T next = prepareNext(); @Override public boolean hasNext() { return next != null; } @Override public T next() { T result = next; next = prepareNext(); return result; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } private T prepareNext() { while (objects.hasNext()) { RDFTerm nextObject = objects.next(); if (type.isAssignableFrom(nextObject.getClass())) { return (T) nextObject; } } return null; } }; } public Iterator<Literal> getLiterals(IRI property) { final Iterator<RDFTerm> objects = getObjects(property); return new Iterator<Literal>() { Literal next = prepareNext(); @Override public boolean hasNext() { return next != null; } @Override public Literal next() { Literal result = next; next = prepareNext(); return result; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } private Literal prepareNext() { while (objects.hasNext()) { RDFTerm nextObject = objects.next(); if (nextObject instanceof Literal) { return (Literal) nextObject; } } return null; } }; } /** * Count the number of triples in the underlying triple-collection * with this node as subject and a specified property as predicate. * * @param property the property to be examined * @return the number of triples in the underlying triple-collection * which meet the specified condition */ public int countObjects(IRI property) { return countTriples(graph.filter((BlankNodeOrIRI) resource, property, null)); } private int countTriples(final Iterator<Triple> triples) { int count = 0; while (triples.hasNext()) { triples.next(); count++; } return count; } /** * Get the objects of statements with this node as subject and a specified * property as predicate. * * @param property the property * @return */ public Iterator<RDFTerm> getObjects(IRI property) { if (resource instanceof BlankNodeOrIRI) { final Iterator<Triple> triples = graph.filter((BlankNodeOrIRI) resource, property, null); return new Iterator<RDFTerm>() { @Override public boolean hasNext() { return triples.hasNext(); } @Override public RDFTerm next() { final Triple triple = triples.next(); if (triple != null) { return triple.getObject(); } else { return null; } } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } else { return new Iterator<RDFTerm>() { @Override public boolean hasNext() { return false; } @Override public RDFTerm next() { return null; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } } /** * Checks wether this node has the given property with the given value. * If the given value is null, then it is checked if this node has the * specified property regardless of its value. * * @param property * @param object * @return true if the node represented by this object is the subject of a * statement with the given prediate and object, false otherwise */ public boolean hasProperty(IRI property, RDFTerm object) { Lock l = readLock(); l.lock(); try { Iterator<RDFTerm> objects = getObjects(property); if (object == null) { return objects.hasNext(); } while (objects.hasNext()) { if (objects.next().equals(object)) { return true; } } return false; } finally { l.unlock(); } } /** * Count the number of triples in the underlying triple-collection * with this node as object and a specified property as predicate. * * @param property the property to be examined * @return the number of triples in the underlying triple-collection * which meet the specified condition */ public int countSubjects(IRI property) { Lock l = readLock(); l.lock(); try { return countTriples(graph.filter(null, property, resource)); } finally { l.unlock(); } } /** * Get the subjects of statements with this node as object and a specified * property as predicate. * * @param property the property * @return */ public Iterator<BlankNodeOrIRI> getSubjects(IRI property) { final Iterator<Triple> triples = graph.filter(null, property, resource); return new Iterator<BlankNodeOrIRI>() { @Override public boolean hasNext() { return triples.hasNext(); } @Override public BlankNodeOrIRI next() { return triples.next().getSubject(); } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } public Iterator<IRI> getIRIObjects(IRI property) { return getTypeSelectedObjects(property, IRI.class); } /** * Get all available properties as an {@link Iterator}{@literal <}{@link IRI}{@literal >}. * You can use <code>getObjects(IRI property)</code> to get the values of * each property * * @return an iterator over properties of this node */ public Iterator<IRI> getProperties() { if (resource instanceof BlankNodeOrIRI) { final Iterator<Triple> triples = graph.filter((BlankNodeOrIRI) resource, null, null); return getUniquePredicates(triples); } else { return new Iterator<IRI>() { @Override public boolean hasNext() { return false; } @Override public IRI next() { return null; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } } /** * Get all inverse properties as an {@link Iterator}{@literal <}{@link IRI}{@literal >}. * You can use <code>getSubject(IRI property)</code> to get the values of * each inverse property * * @return an iterator over properties pointing to this node */ public Iterator<IRI> getInverseProperties() { final Iterator<Triple> triples = graph.filter(null, null, resource); return getUniquePredicates(triples); } /** * @param triples * @returnan {@link Iterator}<{@link IRI}> containing the predicates from * an {@link Iterator}<{@link Triple}> */ private Iterator<IRI> getUniquePredicates(final Iterator<Triple> triples) { final Set<IRI> resultSet = new HashSet<IRI>(); while (triples.hasNext()) { resultSet.add(triples.next().getPredicate()); } return resultSet.iterator(); } /** * Adds a property to the node with the specified predicate and object * * @param predicate * @param object */ public void addProperty(IRI predicate, RDFTerm object) { if (resource instanceof BlankNodeOrIRI) { graph.add(new TripleImpl((BlankNodeOrIRI) resource, predicate, object)); } else { throw new RuntimeException("Literals cannot be the subject of a statement"); } } /** * Coverts the value into a typed literals and sets it as object of the * specified property * * @param property the predicate of the triple to be created * @param value the value of the typed literal object */ public void addPropertyValue(IRI property, Object value) { addProperty(property, LiteralFactory.getInstance().createTypedLiteral(value)); } /** * Adds a property to the node with the inverse of the specified predicate and object * In other words <code>subject</code> will be related via the property <code>relation</code> to this node. * * @param predicate * @param subject */ public void addInverseProperty(IRI predicate, RDFTerm subject) { if (subject instanceof BlankNodeOrIRI) { graph.add(new TripleImpl((BlankNodeOrIRI) subject, predicate, resource)); } else { throw new RuntimeException("Literals cannot be the subject of a statement"); } } /** * creates and returns an <code>RdfList</code> for the node and * Graph represented by this object. * * @return a List to easy access the rdf:List represented by this node */ public List<RDFTerm> asList() { if (resource instanceof BlankNodeOrIRI) { return new RdfList((BlankNodeOrIRI) resource, graph); } else { throw new RuntimeException("Literals cannot be the subject of a List"); } } /** * Deletes all statement with the current node as subject and the specified * predicate * * @param predicate */ public void deleteProperties(IRI predicate) { if (resource instanceof BlankNodeOrIRI) { Iterator<Triple> tripleIter = graph.filter((BlankNodeOrIRI) resource, predicate, null); Collection<Triple> toDelete = new ArrayList<Triple>(); while (tripleIter.hasNext()) { Triple triple = tripleIter.next(); toDelete.add(triple); } for (Triple triple : toDelete) { graph.remove(triple); } } } /** * Delete property to the node with the specified predicate and object * * @param predicate * @param object */ public void deleteProperty(IRI predicate, RDFTerm object) { if (resource instanceof BlankNodeOrIRI) { graph.remove(new TripleImpl((BlankNodeOrIRI) resource, predicate, object)); } } @Override public String toString() { return resource.toString(); } /** * Replaces the graph node resouce with the specified <code>BlankNodeOrIRI</code>. * The resource is only replaced where it is either subject or object. * * @param replacement * @return a GraphNode representing the replecement node */ public GraphNode replaceWith(BlankNodeOrIRI replacement) { return replaceWith(replacement, false); } /** * Replaces the graph node resouce with the specified <code>BlankNodeOrIRI</code>. * Over the boolean <code>checkPredicate</code> it can be specified if the * resource should also be replaced where it is used as predicate. * * @param replacement * @param checkPredicates * @return a GraphNode representing the replecement node */ public GraphNode replaceWith(BlankNodeOrIRI replacement, boolean checkPredicates) { Graph newTriples = new SimpleGraph(); if (!(resource instanceof Literal)) { Iterator<Triple> subjectTriples = graph.filter((BlankNodeOrIRI) resource, null, null); while (subjectTriples.hasNext()) { Triple triple = subjectTriples.next(); Triple newTriple = new TripleImpl(replacement, triple.getPredicate(), triple.getObject()); subjectTriples.remove(); newTriples.add(newTriple); } graph.addAll(newTriples); newTriples.clear(); } Iterator<Triple> objectTriples = graph.filter(null, null, resource); while (objectTriples.hasNext()) { Triple triple = objectTriples.next(); Triple newTriple = new TripleImpl(triple.getSubject(), triple.getPredicate(), replacement); objectTriples.remove(); newTriples.add(newTriple); } graph.addAll(newTriples); newTriples.clear(); if (checkPredicates && replacement instanceof IRI && resource instanceof IRI) { Iterator<Triple> predicateTriples = graph.filter(null, (IRI) resource, null); while (predicateTriples.hasNext()) { Triple triple = predicateTriples.next(); Triple newTriple = new TripleImpl(triple.getSubject(), (IRI) replacement, triple.getObject()); predicateTriples.remove(); newTriples.add(newTriple); } graph.addAll(newTriples); } return new GraphNode(replacement, graph); } /** * Returns a iterator containing all objects of the triples where this * graph node is the subject and has the specified property. The objects * are returned as <code>GraphNode</code>s. * * @param property * @return */ public Iterator<GraphNode> getObjectNodes(IRI property) { final Iterator<RDFTerm> objects = this.getObjects(property); return new Iterator<GraphNode>() { @Override public boolean hasNext() { return objects.hasNext(); } @Override public GraphNode next() { RDFTerm object = objects.next(); return new GraphNode(object, graph); } @Override public void remove() { objects.remove(); } }; } /** * Returns a iterator containing all subjects of the triples where this * graph node is the object and has the specified property. The subjects * are returned as <code>GraphNode</code>s. * * @param property * @return */ public Iterator<GraphNode> getSubjectNodes(IRI property) { final Iterator<BlankNodeOrIRI> subjects = this.getSubjects(property); return new Iterator<GraphNode>() { @Override public boolean hasNext() { return subjects.hasNext(); } @Override public GraphNode next() { RDFTerm object = subjects.next(); return new GraphNode(object, graph); } @Override public void remove() { subjects.remove(); } }; } /** * @param obj * @return true if obj is an instance of the same class represening the same * node in the same graph, subclasses may have different identity criteria. */ @Override public boolean equals(Object obj) { if (obj == null || !(obj.getClass().equals(getClass()))) { return false; } GraphNode other = (GraphNode) obj; return getNode().equals(other.getNode()) && getGraph().equals(other.getGraph()); } @Override public int hashCode() { return 13 * getNode().hashCode() + getGraph().hashCode(); } /** * @return a ReadLock if the underlying ImmutableGraph is a LockableGraph it returns its lock, otherwise null */ public Lock readLock() { return getGraph().getLock().readLock(); } /** * @return */ public Lock writeLock() { return (getGraph()).getLock().writeLock(); } }
183
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/UnionWatchableGraph.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.clerezza.utils; import org.apache.clerezza.Graph; import org.apache.clerezza.WatchableGraph; import org.apache.clerezza.event.FilterTriple; import org.apache.clerezza.event.GraphListener; /** * @author developer */ public class UnionWatchableGraph extends UnionGraph implements WatchableGraph { public UnionWatchableGraph(WatchableGraph... baseTripleCollections) { super(baseTripleCollections); } @Override public void addGraphListener(GraphListener listener, FilterTriple filter) { for (Graph graph : baseTripleCollections) { ((WatchableGraph) graph).addGraphListener(listener, filter); } } @Override public void addGraphListener(GraphListener listener, FilterTriple filter, long delay) { for (Graph graph : baseTripleCollections) { ((WatchableGraph) graph).addGraphListener(listener, filter, delay); } } @Override public void removeGraphListener(GraphListener listener) { for (Graph graph : baseTripleCollections) { ((WatchableGraph) graph).removeGraphListener(listener); } } }
184
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/RdfList.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.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.ontologies.OWL; import org.apache.clerezza.ontologies.RDF; import org.apache.clerezza.representation.Serializer; import org.apache.clerezza.representation.SupportedFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileOutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; /** * An implementation of an <code>java.util.List</code> backed by an RDF * collection (rdf:List). The list allows modification that are reflected * to the underlying <code>Graph</code>. It reads the data from the * <code>Graph</code> when it is first needed, so changes to the * Graph affecting the rdf:List may or may not have an effect on the * values returned by instances of this class. For that reason only one * instance of this class should be used for accessing an rdf:List of sublists * thereof when the lists are being modified, having multiple lists exclusively * for read operations (such as for immutable <code>Graph</code>s) is * not problematic. * * @author rbn, mir */ public class RdfList extends AbstractList<RDFTerm> { private static final Logger logger = LoggerFactory.getLogger(RdfList.class); private final static IRI RDF_NIL = new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"); /** * a list of the linked rdf:List elements in order */ private List<BlankNodeOrIRI> listList = new ArrayList<BlankNodeOrIRI>(); private List<RDFTerm> valueList = new ArrayList<RDFTerm>(); private BlankNodeOrIRI firstList; private Graph tc; private boolean totallyExpanded = false; /** * Get a list for the specified resource. * <p> * If the list is modified using the created instance * <code>listRDFTerm</code> will always be the first list. * * @param listRDFTerm * @param tc */ public RdfList(BlankNodeOrIRI listRDFTerm, Graph tc) { firstList = listRDFTerm; this.tc = tc; } /** * Get a list for the specified resource node. * * @param listNode */ public RdfList(GraphNode listNode) { this((BlankNodeOrIRI) listNode.getNode(), listNode.getGraph()); } /** * Creates an empty RdfList by writing a triple * "{@code listRDFTerm} owl:sameAs rdf.nil ." to {@code tc}. * * @param listRDFTerm * @param tc * @return an empty rdf:List. * @throws IllegalArgumentException if the provided {@code listRDFTerm} is a non-empty rdf:List. */ public static RdfList createEmptyList(BlankNodeOrIRI listRDFTerm, Graph tc) throws IllegalArgumentException { if (!tc.filter(listRDFTerm, RDF.first, null).hasNext()) { RdfList list = new RdfList(listRDFTerm, tc); list.tc.add(new TripleImpl(listRDFTerm, OWL.sameAs, RDF_NIL)); return list; } else { throw new IllegalArgumentException(listRDFTerm + "is a non-empty rdf:List."); } } private void expandTill(int pos) { if (totallyExpanded) { return; } BlankNodeOrIRI currentList; if (listList.size() > 0) { currentList = listList.get(listList.size() - 1); } else { currentList = firstList; if (!tc.filter(currentList, RDF.first, null).hasNext()) { return; } listList.add(currentList); valueList.add(getFirstEntry(currentList)); } if (listList.size() >= pos) { return; } while (true) { currentList = getRest(currentList); if (currentList.equals(RDF_NIL)) { totallyExpanded = true; break; } if (listList.size() == pos) { break; } valueList.add(getFirstEntry(currentList)); listList.add(currentList); } } @Override public RDFTerm get(int index) { expandTill(index + 1); return valueList.get(index); } @Override public int size() { expandTill(Integer.MAX_VALUE); return valueList.size(); } @Override public void add(int index, RDFTerm element) { expandTill(index); if (index == 0) { //special casing to make sure the first list remains the same resource if (listList.size() == 0) { tc.remove(new TripleImpl(firstList, OWL.sameAs, RDF_NIL)); tc.add(new TripleImpl(firstList, RDF.rest, RDF_NIL)); tc.add(new TripleImpl(firstList, RDF.first, element)); listList.add(firstList); } else { tc.remove(new TripleImpl(listList.get(0), RDF.first, valueList.get(0))); tc.add(new TripleImpl(listList.get(0), RDF.first, element)); addInRdfList(1, valueList.get(0)); } } else { addInRdfList(index, element); } valueList.add(index, element); } /** * @param index is > 0 * @param element */ private void addInRdfList(int index, RDFTerm element) { expandTill(index + 1); BlankNodeOrIRI newList = new BlankNode() { }; tc.add(new TripleImpl(newList, RDF.first, element)); if (index < listList.size()) { tc.add(new TripleImpl(newList, RDF.rest, listList.get(index))); tc.remove(new TripleImpl(listList.get(index - 1), RDF.rest, listList.get(index))); } else { tc.remove(new TripleImpl(listList.get(index - 1), RDF.rest, RDF_NIL)); tc.add(new TripleImpl(newList, RDF.rest, RDF_NIL)); } tc.add(new TripleImpl(listList.get(index - 1), RDF.rest, newList)); listList.add(index, newList); } @Override public RDFTerm remove(int index) { //keeping the first list resource tc.remove(new TripleImpl(listList.get(index), RDF.first, valueList.get(index))); if (index == (listList.size() - 1)) { tc.remove(new TripleImpl(listList.get(index), RDF.rest, RDF_NIL)); if (index > 0) { tc.remove(new TripleImpl(listList.get(index - 1), RDF.rest, listList.get(index))); tc.add(new TripleImpl(listList.get(index - 1), RDF.rest, RDF_NIL)); } else { tc.add(new TripleImpl(listList.get(index), OWL.sameAs, RDF_NIL)); } listList.remove(index); } else { tc.add(new TripleImpl(listList.get(index), RDF.first, valueList.get(index + 1))); tc.remove(new TripleImpl(listList.get(index), RDF.rest, listList.get(index + 1))); tc.remove(new TripleImpl(listList.get(index + 1), RDF.first, valueList.get(index + 1))); if (index == (listList.size() - 2)) { tc.remove(new TripleImpl(listList.get(index + 1), RDF.rest, RDF_NIL)); tc.add(new TripleImpl(listList.get(index), RDF.rest, RDF_NIL)); } else { tc.remove(new TripleImpl(listList.get(index + 1), RDF.rest, listList.get(index + 2))); tc.add(new TripleImpl(listList.get(index), RDF.rest, listList.get(index + 2))); } listList.remove(index + 1); } return valueList.remove(index); } private BlankNodeOrIRI getRest(BlankNodeOrIRI list) { return (BlankNodeOrIRI) tc.filter(list, RDF.rest, null).next().getObject(); } private RDFTerm getFirstEntry(final BlankNodeOrIRI listRDFTerm) { try { return tc.filter(listRDFTerm, RDF.first, null).next().getObject(); } catch (final NullPointerException e) { RuntimeException runtimeEx = AccessController.doPrivileged(new PrivilegedAction<RuntimeException>() { @Override public RuntimeException run() { try { final FileOutputStream fileOutputStream = new FileOutputStream("/tmp/broken-list.nt"); final GraphNode graphNode = new GraphNode(listRDFTerm, tc); Serializer.getInstance().serialize(fileOutputStream, graphNode.getNodeContext(), SupportedFormat.N_TRIPLE); fileOutputStream.flush(); logger.warn("GraphNode: " + graphNode); final Iterator<IRI> properties = graphNode.getProperties(); while (properties.hasNext()) { logger.warn("available: " + properties.next()); } return new RuntimeException("broken list " + listRDFTerm, e); } catch (Exception ex) { return new RuntimeException(ex); } } }); throw runtimeEx; } } public BlankNodeOrIRI getListRDFTerm() { return firstList; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RdfList other = (RdfList) obj; if (!other.firstList.equals(this.firstList)) { return false; } if (!other.tc.equals(this.tc)) { return false; } return true; } @Override public int hashCode() { return 17 * this.firstList.hashCode() + this.tc.hashCode(); } /** * Returns the rdf lists of which the specified <code>GraphNode</code> is * an element of. Sublists of other lists are not returned. * * @param element * @return */ public static Set<RdfList> findContainingLists(GraphNode element) { Set<GraphNode> listNodes = findContainingListNodes(element); if (listNodes.isEmpty()) { return null; } Set<RdfList> rdfLists = new HashSet<RdfList>(); for (Iterator<GraphNode> it = listNodes.iterator(); it.hasNext(); ) { GraphNode listNode = it.next(); rdfLists.add(new RdfList(listNode)); } return rdfLists; } /** * Returns a set of <code>GraphNode</code>S which are the first list nodes (meaning * they are not the beginning of a sublist) of the list containing the specified * <code>GraphNode</code> as an element. * * @param element * @return */ public static Set<GraphNode> findContainingListNodes(GraphNode element) { Iterator<GraphNode> partOfaListNodesIter = element.getSubjectNodes(RDF.first); if (!partOfaListNodesIter.hasNext()) { return null; } Set<GraphNode> listNodes = new HashSet<GraphNode>(); while (partOfaListNodesIter.hasNext()) { listNodes.addAll(findAllListNodes(partOfaListNodesIter.next())); } return listNodes; } private static Set<GraphNode> findAllListNodes(GraphNode listPart) { Iterator<GraphNode> invRestNodesIter; Set<GraphNode> listNodes = new HashSet<GraphNode>(); do { invRestNodesIter = listPart.getSubjectNodes(RDF.rest); if (invRestNodesIter.hasNext()) { listPart = invRestNodesIter.next(); while (invRestNodesIter.hasNext()) { GraphNode graphNode = invRestNodesIter.next(); listNodes.addAll(findAllListNodes(graphNode)); } } else { listNodes.add(listPart); break; } } while (true); return listNodes; } }
185
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/graphnodeprovider/GraphNodeProvider.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.clerezza.utils.graphnodeprovider; import org.apache.clerezza.IRI; import org.apache.clerezza.utils.GraphNode; /** * A service that returns a GraphNode for a specified named resource, the * returned GraphNode has as BaseGraph the ContentGraph provided by the * ContentGraphProvider and the for remote uris the Graphs they dereference to * and for local URIs with a path-section starting with /user/{username}/ the * local-public-graph of that user. */ public interface GraphNodeProvider { /** * Get a GraphNode for the specified resource, see class comments for * details. */ GraphNode get(IRI uriRef); /** * Get a GraphNode for the specified resource, The resource is assumed to be * local, i.e. the method behaves like get(IRI) for a Uri with an * authority section contained in the Set retuned by * <code>org.apache.clerezza.platform.config.PlatformConfig#getBaseUris()</code> */ GraphNode getLocal(IRI uriRef); /** * return true iff getLocal(uriRef).getNodeContext.size > 0 */ boolean existsLocal(IRI uriRef); }
186
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/smushing/IfpSmusher.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.clerezza.utils.smushing; import org.apache.clerezza.*; import org.apache.clerezza.ontologies.OWL; import org.apache.clerezza.ontologies.RDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * A utility to equate duplicate nodes in an Mgarph, currently only nodes with * a shared ifp are equated. * * @author reto */ public class IfpSmusher extends BaseSmusher { static final Logger log = LoggerFactory.getLogger(IfpSmusher.class); /** * smush mGaph given the ontological facts. Currently it does only * one step ifp smushin, i.e. only ifps are taken in account and only * nodes that have the same node as ifp object in the orignal graph are * equates. (calling the method a second time might lead to additional * smushings.) * * @param mGraph * @param tBox */ public void smush(Graph mGraph, Graph tBox) { final Set<IRI> ifps = getIfps(tBox); final Map<PredicateObject, Set<BlankNodeOrIRI>> ifp2nodesMap = new HashMap<PredicateObject, Set<BlankNodeOrIRI>>(); for (Iterator<Triple> it = mGraph.iterator(); it.hasNext(); ) { final Triple triple = it.next(); final IRI predicate = triple.getPredicate(); if (!ifps.contains(predicate)) { continue; } final PredicateObject po = new PredicateObject(predicate, triple.getObject()); Set<BlankNodeOrIRI> equivalentNodes = ifp2nodesMap.get(po); if (equivalentNodes == null) { equivalentNodes = new HashSet<BlankNodeOrIRI>(); ifp2nodesMap.put(po, equivalentNodes); } equivalentNodes.add(triple.getSubject()); } Set<Set<BlankNodeOrIRI>> unitedEquivalenceSets = uniteSetsWithCommonElement(ifp2nodesMap.values()); smush(mGraph, unitedEquivalenceSets, true); } private Set<IRI> getIfps(Graph tBox) { final Iterator<Triple> ifpDefinitions = tBox.filter(null, RDF.type, OWL.InverseFunctionalProperty); final Set<IRI> ifps = new HashSet<IRI>(); while (ifpDefinitions.hasNext()) { final Triple triple = ifpDefinitions.next(); ifps.add((IRI) triple.getSubject()); } return ifps; } private <T> Set<Set<T>> uniteSetsWithCommonElement( Collection<Set<T>> originalSets) { Set<Set<T>> result = new HashSet<Set<T>>(); Iterator<Set<T>> iter = originalSets.iterator(); while (iter.hasNext()) { Set<T> originalSet = iter.next(); //TODO this could be done more efficiently with a map Set<T> matchingSet = getMatchinSet(originalSet, result); if (matchingSet != null) { matchingSet.addAll(originalSet); } else { result.add(new HashSet<T>(originalSet)); } } if (result.size() < originalSets.size()) { return uniteSetsWithCommonElement(result); } else { return result; } } private <T> Set<T> getMatchinSet(Set<T> set, Set<Set<T>> setOfSet) { for (Set<T> current : setOfSet) { if (shareElements(set, current)) { return current; } } return null; } private <T> boolean shareElements(Set<T> set1, Set<T> set2) { for (T elem : set2) { if (set1.contains(elem)) { return true; } } return false; } class PredicateObject { final IRI predicate; final RDFTerm object; public PredicateObject(IRI predicate, RDFTerm object) { this.predicate = predicate; this.object = object; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PredicateObject other = (PredicateObject) obj; if (this.predicate != other.predicate && !this.predicate.equals(other.predicate)) { return false; } if (this.object != other.object && !this.object.equals(other.object)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 29 * hash + this.predicate.hashCode(); hash = 13 * hash + this.object.hashCode(); return hash; } @Override public String toString() { return "(" + predicate + ", " + object + ")"; } } }
187
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/smushing/BaseSmusher.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.clerezza.utils.smushing; import org.apache.clerezza.*; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.ontologies.OWL; import java.util.*; import java.util.concurrent.locks.Lock; /** * @author Reto */ public class BaseSmusher { /** * Smushes the resources in mGraph that belong to the same set in equivalenceSets, * i.e. it adds all properties to one of the resources in the equivalence set. * <p> * Optionally owl:sameAs statement are added that point from the IRIs that * no longer have properties to the one with properties. If addOwlSameAs * is false the IRIs will just disappear from the graph. * * @param mGraph the graph to smush * @param equivalenceSets sets of equivalent resources * @param addOwlSameAs whether owl:sameAs statements should be added */ public void smush(Graph mGraph, Set<Set<BlankNodeOrIRI>> equivalenceSets, boolean addOwlSameAs) { Map<BlankNodeOrIRI, BlankNodeOrIRI> current2ReplacementMap = new HashMap<BlankNodeOrIRI, BlankNodeOrIRI>(); final Graph owlSameAsGraph = new SimpleGraph(); for (Set<BlankNodeOrIRI> equivalenceSet : equivalenceSets) { final BlankNodeOrIRI replacement = getReplacementFor(equivalenceSet, owlSameAsGraph); for (BlankNodeOrIRI current : equivalenceSet) { if (!current.equals(replacement)) { current2ReplacementMap.put(current, replacement); } } } final Set<Triple> newTriples = new HashSet<Triple>(); Lock l = mGraph.getLock().writeLock(); l.lock(); try { for (Iterator<Triple> it = mGraph.iterator(); it.hasNext(); ) { final Triple triple = it.next(); final BlankNodeOrIRI subject = triple.getSubject(); BlankNodeOrIRI subjectReplacement = current2ReplacementMap.get(subject); final RDFTerm object = triple.getObject(); @SuppressWarnings(value = "element-type-mismatch") RDFTerm objectReplacement = current2ReplacementMap.get(object); if ((subjectReplacement != null) || (objectReplacement != null)) { it.remove(); if (subjectReplacement == null) { subjectReplacement = subject; } if (objectReplacement == null) { objectReplacement = object; } newTriples.add(new TripleImpl(subjectReplacement, triple.getPredicate(), objectReplacement)); } } for (Triple triple : newTriples) { mGraph.add(triple); } mGraph.addAll(owlSameAsGraph); } finally { l.unlock(); } } private BlankNodeOrIRI getReplacementFor(Set<BlankNodeOrIRI> equivalenceSet, Graph owlSameAsGraph) { final Set<IRI> uriRefs = new HashSet<IRI>(); for (BlankNodeOrIRI nonLiteral : equivalenceSet) { if (nonLiteral instanceof IRI) { uriRefs.add((IRI) nonLiteral); } } switch (uriRefs.size()) { case 1: return uriRefs.iterator().next(); case 0: return new BlankNode(); } final IRI preferedIRI = getPreferedIRI(uriRefs); final Iterator<IRI> uriRefIter = uriRefs.iterator(); while (uriRefIter.hasNext()) { IRI uriRef = uriRefIter.next(); if (!uriRef.equals(preferedIRI)) { owlSameAsGraph.add(new TripleImpl(uriRef, OWL.sameAs, preferedIRI)); } } return preferedIRI; } /** * Returns a prefered IRI for the IRIs in a set. Typically and in the * default implementation the IRI will be one of the set. Note however that * subclass implementations may also return another IRI to be used. * * @param uriRefs * @return */ protected IRI getPreferedIRI(Set<IRI> uriRefs) { final Iterator<IRI> uriRefIter = uriRefs.iterator(); //instead of an arbitrary one we might either decide lexicographically //or look at their frequency in mGraph return uriRefIter.next(); } }
188
0
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils
Create_ds/clerezza/api.utils/src/main/java/org/apache/clerezza/utils/smushing/SameAsSmusher.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.clerezza.utils.smushing; import org.apache.clerezza.BlankNodeOrIRI; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.Triple; import org.apache.clerezza.ontologies.OWL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * A utility to equate duplicate nodes in an Mgraph. This unifies owl:sameAs * resources. * * @author reto */ public class SameAsSmusher extends BaseSmusher { static final Logger log = LoggerFactory.getLogger(SameAsSmusher.class); /** * This will ensure that all properties of sameAs resources are associated * to the preferedIRI as returned by {@code getPreferedIRI} * * @param mGraph * @param owlSameStatements * @param addCanonicalSameAsStatements if true owl:sameAsStatements with the preferedIRI as object will be added */ public void smush(Graph mGraph, Graph owlSameStatements, boolean addCanonicalSameAsStatements) { log.info("Starting smushing"); // This hashmap contains a uri (key) and the set of equivalent uris (value) final Map<BlankNodeOrIRI, Set<BlankNodeOrIRI>> node2EquivalenceSet = new HashMap<BlankNodeOrIRI, Set<BlankNodeOrIRI>>(); log.info("Creating the sets of equivalent uris of each subject or object in the owl:sameAs statements"); // Determines for each subject and object in all the owl:sameAs statements the set of ewquivalent uris for (Iterator<Triple> it = owlSameStatements.iterator(); it.hasNext(); ) { final Triple triple = it.next(); final IRI predicate = triple.getPredicate(); if (!predicate.equals(OWL.sameAs)) { throw new RuntimeException("Statements must use only <http://www.w3.org/2002/07/owl#sameAs> predicate."); } final BlankNodeOrIRI subject = triple.getSubject(); //literals not yet supported final BlankNodeOrIRI object = (BlankNodeOrIRI) triple.getObject(); Set<BlankNodeOrIRI> equivalentNodes = node2EquivalenceSet.get(subject); // if there is not a set of equivalent uris then create a new set if (equivalentNodes == null) { equivalentNodes = node2EquivalenceSet.get(object); if (equivalentNodes == null) { equivalentNodes = new HashSet<BlankNodeOrIRI>(); } } else { Set<BlankNodeOrIRI> objectSet = node2EquivalenceSet.get(object); if ((objectSet != null) && (objectSet != equivalentNodes)) { //merge two sets for (BlankNodeOrIRI res : objectSet) { node2EquivalenceSet.remove(res); } for (BlankNodeOrIRI res : objectSet) { node2EquivalenceSet.put(res, equivalentNodes); } equivalentNodes.addAll(objectSet); } } // add both subject and object of the owl:sameAs statement to the set of equivalent uris equivalentNodes.add(subject); equivalentNodes.add(object); // use both uris in the owl:sameAs statement as keys for the set of equivalent uris node2EquivalenceSet.put(subject, equivalentNodes); node2EquivalenceSet.put(object, equivalentNodes); log.info("Sets of equivalent uris created."); } // This set contains the sets of equivalent uris Set<Set<BlankNodeOrIRI>> unitedEquivalenceSets = new HashSet<Set<BlankNodeOrIRI>>(node2EquivalenceSet.values()); smush(mGraph, unitedEquivalenceSets, addCanonicalSameAsStatements); } }
189
0
Create_ds/clerezza/tutorial/src/main/java/org/apache/clerezza
Create_ds/clerezza/tutorial/src/main/java/org/apache/clerezza/tutorial/Example03.java
package org.apache.clerezza.tutorial; import org.apache.clerezza.Graph; import org.apache.clerezza.representation.Parser; import org.apache.clerezza.representation.Serializer; import org.apache.clerezza.representation.SupportedFormat; import org.apache.clerezza.representation.UnsupportedFormatException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; public class Example03 { private static final Logger logger = LoggerFactory.getLogger( Example03.class ); public static void main( String[] args ) { InputStream inputStream = Example03.class.getResourceAsStream( "example03.ttl" ); Parser parser = Parser.getInstance(); Graph graph; try { graph = parser.parse( inputStream, SupportedFormat.TURTLE ); } catch ( UnsupportedFormatException ex ) { logger.warn( String.format( "%s is not supported by the used parser", SupportedFormat.TURTLE ) ); return; } Serializer serializer = Serializer.getInstance(); try { FileOutputStream outputStream = new FileOutputStream( "/tmp/example03.rdf" ); serializer.serialize( outputStream, graph, SupportedFormat.RDF_XML ); } catch ( FileNotFoundException ex ) { logger.warn( ex.getMessage() ); } catch ( UnsupportedFormatException ex ) { logger.warn( String.format( "%s is not supported by the used serializer", SupportedFormat.RDF_XML ) ); } } }
190
0
Create_ds/clerezza/tutorial/src/main/java/org/apache/clerezza
Create_ds/clerezza/tutorial/src/main/java/org/apache/clerezza/tutorial/Example02.java
package org.apache.clerezza.tutorial; import org.apache.clerezza.Graph; import org.apache.clerezza.Triple; import org.apache.clerezza.representation.Parser; import org.apache.clerezza.representation.SupportedFormat; import org.apache.clerezza.representation.UnsupportedFormatException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Iterator; public class Example02 { private static final Logger logger = LoggerFactory.getLogger( Example02.class ); public static void main( String[] args ) { InputStream inputStream = Example02.class.getResourceAsStream( "example02.ttl" ); Parser parser = Parser.getInstance(); try { Graph graph = parser.parse( inputStream, SupportedFormat.TURTLE ); Iterator<Triple> iterator = graph.filter( null, null, null ); Triple triple; while ( iterator.hasNext() ) { triple = iterator.next(); logger.info( String.format( "%s %s %s", triple.getSubject().toString(), triple.getPredicate().toString(), triple.getObject().toString() ) ); } } catch ( UnsupportedFormatException ex ) { logger.warn( String.format( "%s is not supported by the used parser", SupportedFormat.TURTLE ) ); } } }
191
0
Create_ds/clerezza/tutorial/src/main/java/org/apache/clerezza
Create_ds/clerezza/tutorial/src/main/java/org/apache/clerezza/tutorial/Example01.java
package org.apache.clerezza.tutorial; import org.apache.clerezza.BlankNode; import org.apache.clerezza.Graph; import org.apache.clerezza.IRI; import org.apache.clerezza.Triple; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import java.util.Iterator; public class Example01 { public static void main( String[] args ) { BlankNode subject = new BlankNode(); IRI isA = new IRI( "http://clerezza.apache.org/2017/01/example#isA" ); IRI clerezzaUser = new IRI( "http://clerezza.apache.org/2017/01/example#ClerezzaUser" ); IRI hasFirstName = new IRI( "http://clerezza.apache.org/2017/01/example#hasFirstName" ); PlainLiteralImpl firstName = new PlainLiteralImpl( "Hasan" ); TripleImpl subjectType = new TripleImpl( subject, isA, clerezzaUser ); TripleImpl subjectFirstName = new TripleImpl( subject, hasFirstName, firstName ); Graph myGraph = new SimpleGraph(); myGraph.add( subjectType ); myGraph.add( subjectFirstName ); Iterator<Triple> iterator = myGraph.filter( null, null, null ); Triple triple; while ( iterator.hasNext() ) { triple = iterator.next(); System.out.println( triple.getSubject().toString() ); System.out.println( triple.getPredicate().toString() ); System.out.println( triple.getObject().toString() ); } } }
192
0
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserSerializerCombinationTest.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.clerezza.sparql; import org.apache.clerezza.sparql.query.Query; import org.junit.jupiter.api.*; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; /** * * @author hasan */ @RunWith(JUnitPlatform.class) public class QueryParserSerializerCombinationTest { public QueryParserSerializerCombinationTest() { } @BeforeAll public static void setUpClass() { } @AfterAll public static void tearDownClass() { } @BeforeEach public void setUp() { } @AfterEach public void tearDown() { } @Test public void testPatternOrderPreservation() throws Exception { String queryString = "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description \n" + "WHERE\n" + "{ ?property <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#ObjectProperty> .\n" + "{ { ?property <http://www.w3.org/2000/01/rdf-schema#domain> ?superclass .\n" + "<http://example.org/ontologies/market_ontology.owl#Company> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?superclass .\n" + "} UNION { ?property <http://www.w3.org/2000/01/rdf-schema#domain> ?dunion .\n" + "?dunion <http://www.w3.org/2002/07/owl#unionOf> ?dlist .\n" + "?dlist <http://jena.hpl.hp.com/ARQ/list#member> ?superclass .\n" + "<http://example.org/ontologies/market_ontology.owl#Company> <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?superclass .\n" + "} } { { ?property <http://www.w3.org/2000/01/rdf-schema#range> ?superrange .\n" + "?range <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?superrange .\n" + "FILTER (! (isBLANK(?range)))\n" + "} UNION { ?property <http://www.w3.org/2000/01/rdf-schema#range> ?range .\n" + "FILTER (! (isBLANK(?range)))\n" + "} } OPTIONAL { ?somesub <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?range .\n" + "FILTER (((?somesub) != (<http://www.w3.org/2002/07/owl#Nothing>)) && ((?somesub) != (?range)))\n" + "} OPTIONAL { ?subproperty <http://www.w3.org/2000/01/rdf-schema#subPropertyOf> ?property .\n" + " OPTIONAL { ?subproperty <http://purl.org/dc/elements/1.1/description> ?subproperty_description .\n" + "} FILTER (((?subproperty) != (<http://www.w3.org/2002/07/owl#bottomObjectProperty>)) && ((?subproperty) != (?property)))\n" + "} OPTIONAL { ?property <http://purl.org/dc/elements/1.1/description> ?property_description .\n" + "} FILTER ((?property) != (<http://www.w3.org/2002/07/owl#bottomObjectProperty>))\n" + "FILTER ((?range) != (<http://www.w3.org/2002/07/owl#Nothing>))\n" + "FILTER (! (BOUND(?somesub)))\n" + "} \n"; Query query = QueryParser.getInstance().parse(queryString); Assertions.assertEquals(queryString.replaceAll("\\s", "").trim(), query.toString().replaceAll("\\s", "").trim()); } @Test public void testParsingAndSerializationStability() throws Exception { String queryString = "PREFIX mo: <http://example.org/ontologies/market_ontology.owl#>\n" + "PREFIX list: <http://jena.hpl.hp.com/ARQ/list#>\n" + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description\n" + "WHERE {\n" + " ?property a owl:ObjectProperty .\n" + " FILTER (?property != owl:bottomObjectProperty) .\n" + " {\n" + " {\n" + " ?property rdfs:domain ?superclass .\n" + " mo:Company rdfs:subClassOf ?superclass .\n" + " }\n" + " UNION\n" + " {\n" + " ?property rdfs:domain ?dunion .\n" + " ?dunion owl:unionOf ?dlist .\n" + " ?dlist list:member ?superclass .\n" + " mo:Company rdfs:subClassOf ?superclass .\n" + " }\n" + " }\n" + " {\n" + " {\n" + " ?property rdfs:range ?superrange .\n" + " ?range rdfs:subClassOf ?superrange .\n" + " FILTER (!isBlank(?range)) .\n" + " }\n" + " UNION\n" + " {\n" + " ?property rdfs:range ?range .\n" + " FILTER (!isBlank(?range)) .\n" + " }\n" + " } .\n" + " FILTER (?range != owl:Nothing) .\n" + " OPTIONAL { ?somesub rdfs:subClassOf ?range . FILTER(?somesub != owl:Nothing && ?somesub != ?range)}\n" + " FILTER (!bound(?somesub)) .\n" + " OPTIONAL {\n" + " ?subproperty rdfs:subPropertyOf ?property .\n" + " FILTER(?subproperty != owl:bottomObjectProperty && ?subproperty != ?property)\n" + " OPTIONAL { ?subproperty dc:description ?subproperty_description . }\n" + " }\n" + " OPTIONAL { ?property dc:description ?property_description . }\n" + "} "; Query query1 = QueryParser.getInstance().parse(queryString); Thread.sleep(5000l); Query query2 = QueryParser.getInstance().parse(queryString); Assertions.assertEquals(query1.toString(), query2.toString()); } }
193
0
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza/sparql/SparqlPreParserTest.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.clerezza.sparql; import org.apache.clerezza.IRI; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * * @author hasan */ @RunWith(JUnitPlatform.class) public class SparqlPreParserTest { private final static IRI STORED_NAME_GRAPH = new IRI("http://example.org/named.graph"); private class TestGraphStore implements GraphStore { private IRI namedGraph; public TestGraphStore(IRI namedGraph) { this.namedGraph = namedGraph; } @Override public Set<IRI> listGraphs() { return this.listNamedGraphs(); } @Override public Set<IRI> listNamedGraphs() { return Collections.singleton(this.namedGraph); } } private TestGraphStore graphStore = new TestGraphStore(STORED_NAME_GRAPH); private final static IRI DEFAULT_GRAPH = new IRI("http://example.org/default.graph"); private final static IRI TEST_GRAPH = new IRI("http://example.org/test.graph"); @Test public void testDefaultGraphInSelectQuery() throws ParseException { StringBuilder queryStrBuilder = new StringBuilder(); queryStrBuilder.append( "PREFIX : <http://example.org/>\n" + "SELECT ?x \n" + "{\n" + ":order :item/:price ?x\n" + "}\n"); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testAllGraphReferenceInSelectQuery() throws ParseException { StringBuilder queryStrBuilder = new StringBuilder(); queryStrBuilder.append("SELECT DISTINCT ?g { GRAPH ?g { ?s ?p ?o } }\n"); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs == null); } @Test public void testSelectQuery() throws ParseException { StringBuilder queryStrBuilder = new StringBuilder(); queryStrBuilder.append( "PREFIX : <http://example.org/>\n" + "SELECT ?x (foo(2*3, ?x < ?y) AS ?f) (GROUP_CONCAT(?x ; separator=\"|\") AS ?gc) (sum(distinct *) AS ?total)\n" + "FROM " + TEST_GRAPH.toString() + "\n" + "{\n" + ":order :item/:price ?x\n" + "}\n"); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); } @Test public void testSimpleDescribe() throws ParseException { String queryStr = "DESCRIBE <http://example.org/>"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testLoadingToDefaultGraph() throws ParseException { String queryStr = "LOAD SILENT <http://example.org/mydata>"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(new IRI("http://example.org/mydata")); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testLoadingToGraph() throws ParseException { String queryStr = "LOAD SILENT <http://example.org/mydata> INTO GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(TEST_GRAPH); expected.add(new IRI("http://example.org/mydata")); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testClearingDefaultGraph() throws ParseException { String queryStr = "CLEAR SILENT DEFAULT"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testClearingNamedGraph() throws ParseException { String queryStr = "CLEAR SILENT NAMED"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.contains(STORED_NAME_GRAPH)); } @Test public void testClearingGraph() throws ParseException { String queryStr = "CLEAR SILENT GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); } @Test public void testDroppingDefaultGraph() throws ParseException { String queryStr = "DROP SILENT DEFAULT"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testDroppingNamedGraph() throws ParseException { String queryStr = "DROP SILENT NAMED"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.contains(STORED_NAME_GRAPH)); } @Test public void testDroppingGraph() throws ParseException { String queryStr = "DROP SILENT GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); } @Test public void testCreatingGraph() throws ParseException { String queryStr = "CREATE SILENT GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); } @Test public void testAddingTriplesFromDefaultGraphToNamedGraph() throws ParseException { String queryStr = "ADD SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testAddingTriplesFromNamedGraphToDefaultGraph() throws ParseException { String queryStr = "ADD SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testMovingTriplesFromDefaultGraphToNamedGraph() throws ParseException { String queryStr = "MOVE SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testMovingTriplesFromNamedGraphToDefaultGraph() throws ParseException { String queryStr = "MOVE SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testCopyingTriplesFromDefaultGraphToNamedGraph() throws ParseException { String queryStr = "COPY SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testCopyingTriplesFromNamedGraphToDefaultGraph() throws ParseException { String queryStr = "COPY SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testInsertDataToDefaultGraph() throws ParseException { String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/> INSERT DATA { \n" + "<http://example/book1> dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testInsertDataToNamedGraph() throws ParseException { String queryStr = "PREFIX ns: <http://example.org/ns#>\n" + "INSERT DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1> ns:price 42 } }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); } @Test public void testDeleteDataInDefaultGraph() throws ParseException { String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/> DELETE DATA { \n" + "<http://example/book1> dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testDeleteDataInNamedGraph() throws ParseException { String queryStr = "PREFIX ns: <http://example.org/ns#>\n" + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1> ns:price 42 } }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); } @Test public void testInsertAndDeleteData() throws ParseException { String queryStr = "PREFIX ns: <http://example.org/ns#> " + "INSERT DATA { <http://example/book1> ns:price 42 }; " + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { <http://example/book1> ns:price 42 } }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(DEFAULT_GRAPH); expected.add(TEST_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testDeleteWhereInDefaultGraph() throws ParseException { String queryStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "DELETE WHERE { ?person foaf:givenName 'Fred'; ?property ?value }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testDeleteWhereInNamedGraphs() throws ParseException { String queryStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> DELETE WHERE " + "{ GRAPH <http://example.com/names> { ?person foaf:givenName 'Fred' ; ?property1 ?value1 } " + " GRAPH <http://example.com/addresses> { ?person ?property2 ?value2 } }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(new IRI("http://example.com/names")); expected.add(new IRI("http://example.com/addresses")); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testModifyOperationWithFallbackGraph() throws ParseException { String queryStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> WITH " + TEST_GRAPH.toString() + " DELETE { ?person foaf:givenName 'Bill' } INSERT { ?person foaf:givenName 'William' }" + " WHERE { ?person foaf:givenName 'Bill' }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(TEST_GRAPH); expected.add(DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testDeleteOperationInDefaultGraph() throws ParseException { String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "DELETE { ?book ?p ?v } WHERE { ?book dc:date ?date . " + "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testInsertOperationToNamedGraph() throws ParseException { String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "INSERT { GRAPH <http://example/bookStore2> { ?book ?p ?v } } " + "WHERE { GRAPH <http://example/bookStore> { ?book dc:date ?date . " + "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v } }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(new IRI("http://example/bookStore2")); expected.add(new IRI("http://example/bookStore")); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testInsertAndDeleteWithCommonPrefix() throws ParseException { String queryStr = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX dcmitype: <http://purl.org/dc/dcmitype/>\n" + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n\n" + "INSERT\n" + " { GRAPH <http://example/bookStore2> { ?book ?p ?v } }\n" + "WHERE\n" + " { GRAPH <http://example/bookStore>\n" + " { ?book dc:date ?date . \n" + " FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime )\n" + " ?book ?p ?v\n" + " }\n" + " } ;\n\n" + "WITH <http://example/bookStore>\n" + "DELETE\n" + " { ?book ?p ?v }\n" + "WHERE\n" + " { ?book dc:date ?date ;\n" + " dc:type dcmitype:PhysicalObject .\n" + " FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime ) \n" + " ?book ?p ?v\n" + " }"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Set<IRI> expected = new HashSet<>(); expected.add(new IRI("http://example/bookStore2")); expected.add(new IRI("http://example/bookStore")); Assertions.assertTrue(referredGraphs.containsAll(expected)); } @Test public void testExistsFunction() throws ParseException { String queryStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n\n" + "SELECT ?person\n" + "WHERE \n" + "{\n" + " ?person rdf:type foaf:Person .\n" + " FILTER EXISTS { ?person foaf:name ?name }\n" + "}"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } @Test public void testNotExistsFunction() throws ParseException { String queryStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n\n" + "SELECT ?person\n" + "WHERE \n" + "{\n" + " ?person rdf:type foaf:Person .\n" + " FILTER NOT EXISTS { ?person foaf:name ?name }\n" + "}"; SparqlPreParser parser; parser = new SparqlPreParser(this.graphStore); Set<IRI> referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); Assertions.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); } }
194
0
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza/sparql/QuerySerializerTest.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.clerezza.sparql; import org.apache.clerezza.IRI; import org.apache.clerezza.implementation.literal.LiteralFactory; import org.apache.clerezza.sparql.query.*; import org.apache.clerezza.sparql.query.impl.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author hasan */ @RunWith(JUnitPlatform.class) public class QuerySerializerTest { @Test public void testSelectQuery() { final String queryString = "SELECT ?title FROM <http://example.org/library>" + " WHERE { <http://example.org/book/book1>" + " <http://purl.org/dc/elements/1.1/title> ?title . }"; SimpleSelectQuery selectQuery = new SimpleSelectQuery(); Variable variable = new Variable("title"); selectQuery.addSelection(variable); IRI defaultGraph = new IRI("http://example.org/library"); selectQuery.addDefaultGraph(defaultGraph); ResourceOrVariable subject = new ResourceOrVariable( new IRI("http://example.org/book/book1")); UriRefOrVariable predicate = new UriRefOrVariable( new IRI("http://purl.org/dc/elements/1.1/title")); ResourceOrVariable object = new ResourceOrVariable(variable); TriplePattern triplePattern = new SimpleTriplePattern(subject, predicate, object); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(triplePattern); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); selectQuery.setQueryPattern(queryPattern); Assertions.assertTrue(selectQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testConstructQuery() { final String queryString = "CONSTRUCT { <http://example.org/person#Alice> " + "<http://www.w3.org/2001/vcard-rdf/3.0#FN> ?name . } " + "WHERE { ?x <http://xmlns.com/foaf/0.1/name> ?name . }"; ResourceOrVariable s = new ResourceOrVariable( new IRI("http://example.org/person#Alice")); UriRefOrVariable p = new UriRefOrVariable( new IRI("http://www.w3.org/2001/vcard-rdf/3.0#FN")); ResourceOrVariable o = new ResourceOrVariable(new Variable("name")); Set<TriplePattern> constructTriplePatterns = new HashSet<TriplePattern>(); constructTriplePatterns.add(new SimpleTriplePattern(s, p, o)); SimpleConstructQuery constructQuery = new SimpleConstructQuery(constructTriplePatterns); s = new ResourceOrVariable(new Variable("x")); p = new UriRefOrVariable(new IRI("http://xmlns.com/foaf/0.1/name")); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern(s, p, o)); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); constructQuery.setQueryPattern(queryPattern); Assertions.assertTrue(constructQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testDescribeQuery() { final String queryString = "DESCRIBE <http://example.org/book/book1>"; SimpleDescribeQuery describeQuery = new SimpleDescribeQuery(); describeQuery.addResourceToDescribe(new ResourceOrVariable( new IRI("http://example.org/book/book1"))); Assertions.assertTrue(describeQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testAskQuery() { final String queryString = "ASK WHERE { ?x <http://xmlns.com/foaf/0.1/name> " + "\"Alice\"^^<http://www.w3.org/2001/XMLSchema#string> . }"; ResourceOrVariable s = new ResourceOrVariable(new Variable("x")); UriRefOrVariable p = new UriRefOrVariable( new IRI("http://xmlns.com/foaf/0.1/name")); ResourceOrVariable o = new ResourceOrVariable( LiteralFactory.getInstance().createTypedLiteral("Alice")); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern(s, p, o)); SimpleAskQuery askQuery = new SimpleAskQuery(); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); askQuery.setQueryPattern(queryPattern); Assertions.assertTrue(askQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } /** * Ignoring: given that triplePatterns is a Set I don't see what is supposed * to guarantee the expected ordering. */ @Disabled @Test public void testFilter() { final String queryString = "SELECT ?title ?price WHERE { " + "?x <http://purl.org/dc/elements/1.1/title> ?title . " + "?x <http://example.org/ns#price> ?price . " + "FILTER ((?price) < (\"30.5\"^^<http://www.w3.org/2001/XMLSchema#double>)) " + "}"; Variable price = new Variable("price"); Variable title = new Variable("title"); SimpleSelectQuery selectQuery = new SimpleSelectQuery(); selectQuery.addSelection(title); selectQuery.addSelection(price); Variable x = new Variable("x"); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern(x, new IRI("http://example.org/ns#price"), price)); triplePatterns.add(new SimpleTriplePattern(x, new IRI("http://purl.org/dc/elements/1.1/title"), title)); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); BinaryOperation constraint = new BinaryOperation("<", price, new LiteralExpression(LiteralFactory.getInstance().createTypedLiteral(30.5))); queryPattern.addConstraint(constraint); selectQuery.setQueryPattern(queryPattern); Assertions.assertTrue(selectQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testUriRefExpression() { final String queryString = "SELECT ?resource WHERE { " + "?resource <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?myType . " + "FILTER ((?resource) = (<http://example.org/ontology#special>)) " + "}"; Variable resource = new Variable("resource"); SimpleSelectQuery selectQuery = new SimpleSelectQuery(); selectQuery.addSelection(resource); Variable myType = new Variable("myType"); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern(resource, new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), myType)); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); BinaryOperation constraint = new BinaryOperation("=", resource, new UriRefExpression(new IRI("http://example.org/ontology#special"))); queryPattern.addConstraint(constraint); selectQuery.setQueryPattern(queryPattern); Assertions.assertTrue(selectQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testOrderBy() { final String queryString = "SELECT * WHERE { ?a ?b ?c . } ORDER BY DESC(?c)"; Variable a = new Variable("a"); Variable b = new Variable("b"); Variable c = new Variable("c"); SimpleSelectQuery selectQuery = new SimpleSelectQuery(); selectQuery.setSelectAll(); selectQuery.addSelection(a); selectQuery.addSelection(b); selectQuery.addSelection(c); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern(a, b, c)); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); selectQuery.setQueryPattern(queryPattern); selectQuery.addOrderCondition(new SimpleOrderCondition(c, false)); Assertions.assertTrue(selectQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testOptional() { final String queryString = "SELECT ?title ?price WHERE { " + "?x <http://purl.org/dc/elements/1.1/title> ?title . " + "OPTIONAL { ?x <http://example.org/ns#price> ?price . } " + "}"; Variable title = new Variable("title"); Variable price = new Variable("price"); SimpleSelectQuery selectQuery = new SimpleSelectQuery(); selectQuery.addSelection(title); selectQuery.addSelection(price); Variable x = new Variable("x"); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern(x, new IRI("http://purl.org/dc/elements/1.1/title"), title)); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); Set<TriplePattern> triplePatternsOpt = new HashSet<TriplePattern>(); triplePatternsOpt.add(new SimpleTriplePattern(x, new IRI("http://example.org/ns#price"), price)); SimpleBasicGraphPattern bgpOpt = new SimpleBasicGraphPattern(triplePatternsOpt); SimpleGroupGraphPattern ggpOpt = new SimpleGroupGraphPattern(); ggpOpt.addGraphPattern(bgpOpt); SimpleOptionalGraphPattern ogp = new SimpleOptionalGraphPattern(bgp, ggpOpt); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(ogp); selectQuery.setQueryPattern(queryPattern); Assertions.assertTrue(selectQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } @Test public void testRegex() { final String queryString = "SELECT ?p WHERE { " + "<http://localhost/testitem> ?p ?x . " + "FILTER REGEX(?x,\".*uni.*\"^^<http://www.w3.org/2001/XMLSchema#string>) }"; Variable p = new Variable("p"); SimpleSelectQuery selectQuery = new SimpleSelectQuery(); selectQuery.addSelection(p); Variable x = new Variable("x"); Set<TriplePattern> triplePatterns = new HashSet<TriplePattern>(); triplePatterns.add(new SimpleTriplePattern( new IRI("http://localhost/testitem"), p, x)); SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); queryPattern.addGraphPattern(bgp); List<Expression> arguments = new ArrayList<Expression>(); arguments.add(x); arguments.add(new LiteralExpression(LiteralFactory.getInstance(). createTypedLiteral(".*uni.*"))); BuiltInCall constraint = new BuiltInCall("REGEX", arguments); queryPattern.addConstraint(constraint); selectQuery.setQueryPattern(queryPattern); Assertions.assertTrue(selectQuery.toString() .replaceAll("( |\n)+", " ").trim().equals(queryString)); } }
195
0
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/test/java/org/apache/clerezza/sparql/QueryParserTest.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.clerezza.sparql; import org.apache.clerezza.IRI; import org.apache.clerezza.Language; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.sparql.query.*; import org.apache.clerezza.sparql.query.impl.SimpleTriplePattern; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author hasan */ @RunWith(JUnitPlatform.class) public class QueryParserTest { @Test public void testSelectQuery() throws ParseException { // SELECT ?title FROM <http://example.org/library> // WHERE { <http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> ?title . } final String variable = "title"; final String defaultGraph = "http://example.org/library"; final String subject = "http://example.org/book/book1"; final String predicate = "http://purl.org/dc/elements/1.1/title"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("SELECT ?").append(variable) .append(" FROM <").append(defaultGraph) .append("> WHERE { <").append(subject).append("> <") .append(predicate).append("> ?").append(variable).append(" . }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); SelectQuery selectQuery = (SelectQuery) q; Assertions.assertTrue(selectQuery.getSelection().get(0) .equals(new Variable(variable))); Assertions.assertTrue(selectQuery.getDataSet().getDefaultGraphs().toArray()[0] .equals(new IRI(defaultGraph))); GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); ResourceOrVariable s = new ResourceOrVariable(new IRI(subject)); UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate)); ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); } @Test public void testInvalidQuery() throws ParseException { Assertions.assertThrows(ParseException.class, () -> { Query q = QueryParser.getInstance().parse("Hello"); }); } @Test public void testSelectQuerySelection() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT ?a ?b WHERE {?a ?x ?b}"); Set<Variable> selectionSet = new HashSet<Variable>( q.getSelection()); Set<Variable> expected = new HashSet<Variable>(); expected.add(new Variable("a")); expected.add(new Variable("b")); Assertions.assertEquals(expected, selectionSet); Assertions.assertFalse(q.isSelectAll()); } @Test public void testSelectAll() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT * WHERE {?a ?x ?b}"); Set<Variable> selectionSet = new HashSet<Variable>( q.getSelection()); Set<Variable> expected = new HashSet<Variable>(); expected.add(new Variable("a")); expected.add(new Variable("b")); expected.add(new Variable("x")); Assertions.assertEquals(expected, selectionSet); Assertions.assertTrue(q.isSelectAll()); } @Test public void testPlainLiteral() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT * WHERE {?a ?x 'tiger' . ?a ?x 'lion'@en . }"); GraphPattern gp = (GraphPattern) q.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==2); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern( new Variable("a"), new Variable("x"), new PlainLiteralImpl("tiger")))); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern( new Variable("a"), new Variable("x"), new PlainLiteralImpl("lion", new Language("en"))))); } @Test public void testOrderBy() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT * WHERE {?a ?x ?b} ORDER BY DESC(?b)"); List<OrderCondition> oc = ((QueryWithSolutionModifier) q).getOrderConditions(); Assertions.assertTrue(oc.size()==1); Assertions.assertFalse(oc.get(0).isAscending()); Variable b = new Variable("b"); Assertions.assertEquals(b, oc.get(0).getExpression()); } @Test public void testConstructQuery() throws ParseException { // CONSTRUCT { <http://example.org/person#Alice> <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?name} // WHERE { ?x <http://xmlns.com/foaf/0.1/name> ?name} final String variable1 = "name"; final String variable2 = "x"; final String subject1 = "http://example.org/person#Alice"; final String predicate1 = "http://www.w3.org/2001/vcard-rdf/3.0#FN"; final String predicate2 = "http://xmlns.com/foaf/0.1/name"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("CONSTRUCT { <").append(subject1).append("> <") .append(predicate1).append("> ?").append(variable1) .append("} WHERE { ?").append(variable2).append(" <") .append(predicate2).append("> ?").append(variable1).append("}"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(ConstructQuery.class.isAssignableFrom(q.getClass())); ConstructQuery constructQuery = (ConstructQuery) q; Set<TriplePattern> triplePatterns = constructQuery .getConstructTemplate(); Assertions.assertTrue(triplePatterns.size()==1); ResourceOrVariable s = new ResourceOrVariable(new IRI(subject1)); UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate1)); ResourceOrVariable o = new ResourceOrVariable(new Variable(variable1)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); GraphPattern gp = (GraphPattern) constructQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); s = new ResourceOrVariable(new Variable(variable2)); p = new UriRefOrVariable(new IRI(predicate2)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); } @Test public void testDescribeQuery() throws ParseException { // DESCRIBE <http://example.org/book/book1> final String resource = "http://example.org/book/book1"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("DESCRIBE <").append(resource).append(">"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(DescribeQuery.class.isAssignableFrom(q.getClass())); DescribeQuery describeQuery = (DescribeQuery) q; Assertions.assertTrue(describeQuery.getResourcesToDescribe().get(0) .getResource().equals(new IRI(resource))); } @Test public void testAskQuery() throws ParseException { // ASK { ?x <http://xmlns.com/foaf/0.1/name> "Alice" } final String variable = "x"; final String predicate = "http://xmlns.com/foaf/0.1/name"; final String object = "Alice"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("ASK { ?").append(variable).append(" <") .append(predicate).append("> \"").append(object).append("\" }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(AskQuery.class.isAssignableFrom(q.getClass())); AskQuery askQuery = (AskQuery) q; GraphPattern gp = (GraphPattern) askQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern(new Variable(variable), new IRI(predicate), new PlainLiteralImpl(object)))); } @Test public void testBaseAndPrefix() throws ParseException { // BASE <http://example.org/book/> // PREFIX dc: <http://purl.org/dc/elements/1.1/> // // SELECT $title // WHERE { <book1> dc:title ?title } final String base = "http://example.org/book/"; final String prefix = "dc"; final String prefixUri = "http://purl.org/dc/elements/1.1/"; final String variable = "title"; final String subject = "book1"; final String predicate = "title"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("BASE <").append(base).append(">") .append(" PREFIX ").append(prefix).append(": <") .append(prefixUri).append("> SELECT $").append(variable) .append(" WHERE { <").append(subject).append("> ") .append(prefix).append(":").append(predicate).append(" ?") .append(variable).append(" }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); SelectQuery selectQuery = (SelectQuery) q; Assertions.assertTrue(selectQuery.getSelection().get(0) .equals(new Variable(variable))); GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); ResourceOrVariable s = new ResourceOrVariable(new IRI(base+subject)); UriRefOrVariable p = new UriRefOrVariable(new IRI(prefixUri+predicate)); ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); } @Test public void testOptionalAndFilter() throws ParseException { // PREFIX dc: <http://purl.org/dc/elements/1.1/> // PREFIX books: <http://example.org/book/> // // SELECT ?book ?title // WHERE // { ?book dc:title ?title . // OPTIONAL // { ?book books:author ?author .} // FILTER ( ! bound(?author) ) // } final String prefix1 = "dc"; final String prefix1Uri = "http://purl.org/dc/elements/1.1/"; final String prefix2 = "books"; final String prefix2Uri = "http://example.org/book/"; final String variable1 = "book"; final String variable2 = "title"; final String variable3 = "author"; final String predicate1 = "title"; final String predicate2 = "author"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("PREFIX ").append(prefix1).append(": <").append(prefix1Uri) .append("> PREFIX ").append(prefix2).append(": <").append(prefix2Uri) .append("> SELECT ?").append(variable1).append(" ?").append(variable2) .append(" WHERE { ?").append(variable1).append(" ") .append(prefix1).append(":").append(predicate1) .append(" ?").append(variable2).append(" . OPTIONAL { ?") .append(variable1).append(" ").append(prefix2).append(":") .append(predicate2).append(" ?").append(variable3) .append(" .} FILTER ( ! bound(?").append(variable3).append(") ) }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); SelectQuery selectQuery = (SelectQuery) q; Assertions.assertTrue(selectQuery.getSelection().size() == 2); Set<Variable> vars = new HashSet<Variable>(2); Variable var1 = new Variable(variable1); Variable var2 = new Variable(variable2); vars.add(var1); vars.add(var2); Assertions.assertTrue(selectQuery.getSelection().containsAll(vars)); GroupGraphPattern ggp = selectQuery.getQueryPattern(); List<Expression> constraints = ggp.getFilter(); Assertions.assertTrue(UnaryOperation.class.isAssignableFrom(constraints .get(0).getClass())); UnaryOperation uop = (UnaryOperation) constraints.get(0); Assertions.assertTrue(uop.getOperatorString().equals("!")); Assertions.assertTrue(BuiltInCall.class.isAssignableFrom(uop.getOperand() .getClass())); BuiltInCall bic = (BuiltInCall) uop.getOperand(); Assertions.assertTrue(bic.getName().equals("BOUND")); Variable var3 = new Variable(variable3); Assertions.assertTrue(bic.getArguements().get(0).equals(var3)); GraphPattern gp = (GraphPattern) ggp.getGraphPatterns().toArray()[0]; Assertions.assertTrue(OptionalGraphPattern.class.isAssignableFrom(gp.getClass())); OptionalGraphPattern ogp = (OptionalGraphPattern) gp; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom( ogp.getMainGraphPattern().getClass())); BasicGraphPattern bgp = (BasicGraphPattern) ogp.getMainGraphPattern(); Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size() == 1); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix1Uri + predicate1), var2))); GraphPattern gp2 = (GraphPattern) ogp.getOptionalGraphPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp2.getClass())); bgp = (BasicGraphPattern) gp2; triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size() == 1); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix2Uri + predicate2), var3))); } }
196
0
Create_ds/clerezza/sparql/src/main/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/main/java/org/apache/clerezza/sparql/StringQuerySerializer.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.clerezza.sparql; import org.apache.clerezza.sparql.query.*; /** * This abstract class provides a method to generate a {@link String} * representation of a {@link Query}. * * @author hasan */ public abstract class StringQuerySerializer { /** * Serializes a {@link Query} object to a {@link String}. * * @param query * the Query object to be serialized * @return * a String representation of the specified Query object. */ public String serialize(Query query) { if (query instanceof SelectQuery) { return serialize((SelectQuery) query); } else if (query instanceof ConstructQuery) { return serialize((ConstructQuery) query); } else if (query instanceof DescribeQuery) { return serialize((DescribeQuery) query); } else { return serialize((AskQuery) query); } } /** * Serializes a {@link SelectQuery} object to a {@link String}. * * @param selectQuery * the SelectQuery object to be serialized * @return * a String representation of the specified SelectQuery object. */ public abstract String serialize(SelectQuery selectQuery); /** * Serializes a {@link ConstructQuery} object to a {@link String}. * * @param constructQuery * the ConstructQuery object to be serialized * @return * a String representation of the specified ConstructQuery object. */ public abstract String serialize(ConstructQuery constructQuery); /** * Serializes a {@link DescribeQuery} object to a {@link String}. * * @param describeQuery * the DescribeQuery object to be serialized * @return * a String representation of the specified DescribeQuery object. */ public abstract String serialize(DescribeQuery describeQuery); /** * Serializes an {@link AskQuery} object to a {@link String}. * * @param askQuery * the AskQuery object to be serialized * @return * a String representation of the specified AskQuery object. */ public abstract String serialize(AskQuery askQuery); }
197
0
Create_ds/clerezza/sparql/src/main/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/main/java/org/apache/clerezza/sparql/QueryEngine.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.clerezza.sparql; import org.apache.clerezza.Graph; /** * A QueryEngine can process SPARQL queries against an arbitrary set of graphs. * * @author rbn */ public interface QueryEngine { /** * Executes any sparql query. The type of the result object will vary * depending on the type of the query. * * @param graphStore * where the query originates. * @param defaultGraph * the default ImmutableGraph against which to execute the query if no * FROM clause is present * @param query * string to be executed. * @return the resulting ResultSet, ImmutableGraph or Boolean value */ public Object execute(GraphStore graphStore, Graph defaultGraph, String query); }
198
0
Create_ds/clerezza/sparql/src/main/java/org/apache/clerezza
Create_ds/clerezza/sparql/src/main/java/org/apache/clerezza/sparql/SolutionMapping.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.clerezza.sparql; import org.apache.clerezza.RDFTerm; import org.apache.clerezza.sparql.query.Variable; import java.util.Map; /** * A set of mapping from variable names to solutions. * * a variable name has the form: ( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9] * | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )* * where PN_CHARS_U = [A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] * | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] * | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] * | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] | '_' * * * @author rbn */ public interface SolutionMapping extends Map<Variable, RDFTerm> { /** * Should be the equivalent to this: * public Resource get(String name) { * return get(new Variable(name)); * } * * @param name * @return */ public RDFTerm get(String name); }
199