/target/
/temp/
.metadata/
+/cadisample/
--- /dev/null
+---
+project: 'aaf-authz'
+project_creation_date: '2017-07-12'
+lifecycle_state: 'Incubation'
+project_lead: &onap_releng_ptl
+ name: 'Ram Koya'
+ email: 'rk541m@att.com'
+ id: 'rampi_k'
+ company: 'ATT'
+ timezone: 'America/Dallas'
+primary_contact: *onap_releng_ptl
+issue_tracking:
+ type: 'jira'
+ url: 'https://jira.onap.org/projects/AAF'
+ key: 'AAF'
+meetings:
+ - type: 'zoom'
+ agenda: 'https://wiki.onap.org/display/DW/AAF+Meeting+Minutes'
+ url: 'https://wiki.onap.org/pages/viewpage.action?pageId=15302787'
+ server: 'n/a'
+ channel: 'n/a'
+ repeats: 'weekly'
+ time: '14:00 UTC'
+committers:
+ - <<: *onap_releng_ptl
+ - name: 'Jonathan Gathman'
+ email: 'jonathan.gathman@att.com'
+ company: 'AT&T'
+ id: 'Instrumental'
+ timezone: 'America/Chicago'
+ - name: 'Girish Havaldar'
+ email: 'hg0071052@techmahindra.com'
+ company: 'Techmahindra'
+ id: 'giri'
+ timezone: 'India/Bangalore'
+ - name: 'Huabing Zhao'
+ email: 'zhao.huabing@zte.com.cn'
+ company: 'ZTE'
+ id: 'HuabingZhao'
+ timezone: 'China/Chengdu'
+ - name: 'Kiran Kamineni'
+ email: 'kiran.k.kamineni@intel.com'
+ company: 'Intel'
+ id: 'kirankamineni'
+ timezone: 'America/Santa Clara'
+ - name: 'Varun Gudisena'
+ email: 'vg411h@att.com'
+ company: 'ATT'
+ id: 'vg411h'
+ timezone: 'America/Dallas'
+tsc:
+ approval: 'https://lists.onap.org/pipermail/onap-tsc'
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
- <version>2.5</version>
<configuration>
<skip>false</skip>
</configuration>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
- <version>1.6.7</version>
<extensions>true</extensions>
<configuration>
<nexusUrl>${nexusproxy}</nexusUrl>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
- <version>0.7.7.201606060606</version>
<configuration>
<dumpOnExit>true</dumpOnExit>
<includes>
}
public int totalLoaded() {
- return totalLoaded();
+ return totalLoaded;
}
public int deleted() {
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.actions.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.actions.ActionDAO;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.layer.Result;
+import org.onap.aaf.misc.env.APIException;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Configuration;
+import com.datastax.driver.core.Cluster.Initializer;
+import com.datastax.driver.core.Host.StateListener;
+
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Collection;
+import java.util.List;
+
+import org.junit.Test;
+
+public class JU_ActionDAO {
+
+ AuthzTrans aTrans;
+ Cluster cluster;
+ ActionDAOStub actionDAOStub;
+ ActionDAOStub actionDAOStub1;
+
+ private class ActionDAOStub extends ActionDAO {
+
+ public ActionDAOStub(AuthzTrans trans, ActionDAO predecessor) {
+ super(trans, predecessor);
+ // TODO Auto-generated constructor stub
+ }
+
+ public ActionDAOStub(AuthzTrans trans, Cluster cluster, boolean dryRun) throws APIException, IOException {
+ super(trans, cluster, dryRun);
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public Result exec(AuthzTrans trans, Object data, Object t) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ }
+
+ @Before
+ public void setUp() throws APIException, IOException {
+// Cluster.Initializer cInit = mock(Cluster.Initializer.class);
+// Cluster.Builder cBuild = new Cluster.Builder();
+// cBuild.addContactPoint("test");
+// cBuild.build();
+// cluster.buildFrom(cBuild);
+// cluster.builder();
+// cluster.init();
+// cluster.builder().getContactPoints();
+
+
+
+// aTrans = mock(AuthzTrans.class);
+// cluster = mock(Cluster.class);
+// actionDAOStub = new ActionDAOStub(aTrans,cluster,true);
+// actionDAOStub1 = new ActionDAOStub(aTrans, actionDAOStub);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.actions.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.actions.Email;
+import org.onap.aaf.auth.actions.Message;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.org.Organization.Identity;
+import org.onap.aaf.auth.org.Organization;
+import org.onap.aaf.auth.org.OrganizationException;
+
+import static org.mockito.Mockito.*;
+
+import java.io.FileNotFoundException;
+import java.io.PrintStream;
+import java.util.Collection;
+import java.util.Hashtable;
+import java.util.Set;
+
+import org.junit.Test;
+
+public class JU_Email {
+
+ Email email;
+ Identity usersI;
+ Message msg;
+
+ @Before
+ public void setUp() {
+ usersI = mock(Identity.class);
+ msg = new Message();
+ email = new Email();
+ }
+
+ @Test
+ public void testClear() {
+ Assert.assertNotNull(email.clear());
+ }
+
+ @Test
+ public void testIndent() {
+ email.indent("indent");
+ }
+
+ @Test
+ public void testPreamble() {
+ email.preamble("format");
+ }
+
+ @Test
+ public void testAddTo() {
+ email.addTo(usersI);
+
+// Collection col = mock(Collection.class);
+// col.add("test");
+// email.addTo(col);
+
+ email.addTo("email");
+ }
+
+ @Test
+ public void testAddCC() {
+ email.addCC(usersI);
+ email.addCC("email");
+ }
+
+// @Test
+// public void testAdd() throws OrganizationException {
+// email.add(usersI, true);
+// }
+
+ @Test
+ public void testSubject() {
+ email.subject("format");
+ email.subject("for%smat","format");
+ }
+
+ @Test
+ public void testSignature() {
+ email.signature("format","arg");
+ }
+
+ @Test
+ public void testMsg() {
+ email.msg(msg);
+ }
+
+ @Test
+ public void testExec() {
+ AuthzTrans trans = mock(AuthzTrans.class);
+ Organization org = mock(Organization.class);
+ email.preamble("format");
+ email.msg(msg);
+ email.signature("format","arg");
+
+ email.exec(trans, org, "text");
+ }
+
+ @Test
+ public void testLog() throws FileNotFoundException {
+ PrintStream ps = new PrintStream("test");
+ email.addTo("email");
+ email.addCC("email");
+ email.log(ps, "email");
+ email.addTo("emails");
+ email.addCC("emails");
+ email.log(ps, "emails");
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.dao.cass.ApprovalDAO;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.helpers.Approval;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+
+import org.junit.Test;
+
+public class JU_Approval {
+
+ Approval approval;
+ UUID id;
+ UUID ticket;
+ Date date;
+
+ @Before
+ public void setUp() {
+ id = new UUID(0, 0);
+ ticket = new UUID(0, 0);
+ date = new Date();
+
+ approval = new Approval(id, ticket, "approver", date,
+ "user", "memo", "operation", "status", "type", 100l);
+ }
+
+ @Test
+ public void testRoleFromMemo() {
+ Assert.assertNull(approval.roleFromMemo(null));
+ Assert.assertEquals(".admin", approval.roleFromMemo("Re-Validate as Administrator for AAF Namespace '\'test\'test"));
+ Assert.assertEquals(".owner", approval.roleFromMemo("Re-Validate Ownership for AAF Namespace '\'test\'test"));
+ Assert.assertEquals("", approval.roleFromMemo("Re-Approval in Role '\'test\'test"));
+ }
+
+ @Test
+ public void testExpunge() {
+ approval.expunge();
+ }
+
+ @Test
+ public void testGetLast_notified() {
+ Assert.assertTrue(approval.getLast_notified()instanceof Date);
+ }
+
+ @Test
+ public void testSetLastNotified() {
+ approval.setLastNotified(date);
+ }
+
+ @Test
+ public void testGetStatus() {
+ Assert.assertEquals("status", approval.getStatus());
+ }
+
+ @Test
+ public void testSetStatus() {
+ approval.setStatus("status");
+ }
+
+ @Test
+ public void testGetId() {
+ Assert.assertTrue(approval.getId() instanceof UUID);
+ }
+
+ @Test
+ public void testGetTicket() {
+ Assert.assertTrue(approval.getTicket() instanceof UUID);
+ }
+
+ @Test
+ public void testGetMemo() {
+ Assert.assertEquals("memo", approval.getMemo());
+ }
+
+ @Test
+ public void testGetOperation() {
+ Assert.assertEquals("operation", approval.getOperation());
+ }
+
+ @Test
+ public void testGetType() {
+ Assert.assertEquals("type", approval.getType());
+ }
+
+ @Test
+ public void testLapsed() {
+ approval.lapsed();
+ }
+
+ @Test
+ public void testGetRole() {
+ Assert.assertNull(approval.getRole());
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertEquals("user memo", approval.toString());
+ }
+
+ @Test
+ public void testResetLocalData() {
+ approval.resetLocalData();
+ }
+
+ @Test
+ public void testSizeForDeletion() {
+ Assert.assertEquals(0, approval.sizeForDeletion());
+ }
+
+ @Test
+ public void testPendingDelete() {
+ Assert.assertFalse(approval.pendingDelete(approval));
+ }
+
+ @Test
+ public void testDelayDelete() {
+ AuthzTrans trans = mock(AuthzTrans.class);
+ ApprovalDAO dao = mock(ApprovalDAO.class);
+ List<Approval> list = null;
+ approval.delayDelete(trans, dao, true, list, "text");
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.actions.Message;
+import org.onap.aaf.auth.helpers.Approver;
+import org.onap.aaf.auth.org.Organization;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_Approver {
+
+ Approver approver;
+ Organization org;
+ Message msg;
+
+ @Before
+ public void setUp() {
+ org = mock(Organization.class);
+ approver = new Approver("approver", org);
+ msg = new Message();
+ }
+
+ @Test
+ public void testAddRequest() {
+ approver.addRequest("user");
+ approver.addRequest("user");
+ }
+
+ @Test
+ public void testBuild() {
+ approver.addRequest("user");
+ approver.addRequest("user1");
+ approver.addRequest("user2");
+ approver.addRequest("user3");
+ approver.build(msg);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.CacheChange;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.util.List;
+
+import org.junit.Test;
+
+public class JU_CacheChange {
+
+ CacheChange cc;
+
+
+ @Before
+ public void setUp() {
+ cc = new CacheChange();
+ }
+
+ @Test
+ public void testDelayedDelete() {
+ cc.delayedDelete(null);
+ }
+
+ @Test
+ public void testGetRemoved() {
+ List list = cc.getRemoved();
+ Assert.assertNotNull(list);
+ }
+
+ @Test
+ public void testResetLocalData() {
+ cc.resetLocalData();
+ }
+
+ @Test
+ public void testCacheSize() {
+ int size;
+ size = cc.cacheSize();
+ Assert.assertEquals(0, size);
+ }
+
+ @Test
+ public void testContains() {
+ boolean containsBools;
+ containsBools = cc.contains(null);
+ Assert.assertEquals(false, containsBools);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.Creator;
+
+import com.datastax.driver.core.Row;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_Creator {
+
+ CreatorStub creatorStub;
+
+ private class CreatorStub extends Creator{
+
+ @Override
+ public Object create(Row row) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String select() {
+ // TODO Auto-generated method stub
+ return "Select"; //Changed from null to Select
+ }
+
+ }
+
+ @Before
+ public void setUp() {
+ creatorStub = new CreatorStub();
+ }
+
+ @Test
+ public void testQuery() {
+ creatorStub.select();
+ Assert.assertEquals("Select WHERE test;", creatorStub.query("test"));
+ Assert.assertEquals("Select;", creatorStub.query(null));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.common.Define;
+import org.onap.aaf.auth.helpers.Cred;
+import org.onap.aaf.auth.helpers.Cred.CredCount;
+import org.onap.aaf.auth.helpers.Cred.Instance;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.misc.env.Trans;
+
+import com.datastax.driver.core.Session;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.Date;
+
+import org.junit.Test;
+
+public class JU_Cred {
+
+ private ByteArrayOutputStream outStream;
+ private ByteArrayOutputStream errStream;
+ Cred cred;
+ Instance instance;
+ Date date;
+ Integer integer;
+ PropAccess prop;
+ Define define = new Define();
+ Trans trans;
+ Session session;
+ CredCount cc;
+
+ @Before
+ public void setUp() throws CadiException {
+ outStream = new ByteArrayOutputStream();
+ errStream = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outStream));
+ System.setErr(new PrintStream(errStream));
+ date = new Date();
+ integer = new Integer(20);
+ trans = mock(Trans.class);
+ session = mock(Session.class);
+ cc = new CredCount(3);
+ prop = new PropAccess();
+ prop.setProperty(Config.AAF_ROOT_NS, "org.onap.aaf");
+ prop.setProperty(Config.AAF_ROOT_COMPANY,"test");
+ define.set(prop);
+
+ instance = new Instance(12, date, integer, 125642678910L);
+ cred = new Cred("myid1234@aaf.att.com");
+ }
+
+ @Test
+ public void testLast() { //TODO: set instances
+ Assert.assertNull(cred.last(null));
+ }
+
+ @Test
+ public void testTypes() { //TODO: set instances
+ Assert.assertNotNull(cred.types());
+ }
+
+ @Test
+ public void testCount() { //TODO: set instances
+ Assert.assertNotNull(cred.count(3));
+ }
+
+ @Test
+ public void testToString() { //TODO: set instances
+ Assert.assertEquals("myid1234@aaf.att.com[]", cred.toString());
+ }
+
+ @Test
+ public void testHashCode() { //TODO: set instances
+ Assert.assertEquals(-1619358251, cred.hashCode());
+ }
+
+ @Test
+ public void testEquals() { //TODO: set instances
+ Assert.assertEquals(true, cred.equals("myid1234@aaf.att.com"));
+ }
+
+ @Test
+ public void testInc() {
+ Date begin = new Date(date.getTime() - 10);
+ Date after = new Date(date.getTime() + 10);
+ cc.inc(-1, begin, after);
+ cc.inc(1, begin, after);
+ cc.inc(2, begin, after);
+ cc.inc(200, begin, after);
+ }
+
+ @Test
+ public void testAuthCount() { //TODO: set instances
+ Assert.assertEquals(0, cc.authCount(1));
+ }
+
+ @Test
+ public void testX509Count() { //TODO: set instances
+ Assert.assertEquals(0, cc.x509Count(0));
+ }
+
+ @After
+ public void cleanUp() {
+ System.setErr(System.err);
+ System.setOut(System.out);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.Future;
+
+import static org.mockito.Mockito.*;
+
+import java.nio.ByteBuffer;
+import java.util.Date;
+import java.util.UUID;
+
+import org.junit.Test;
+
+public class JU_Future {
+
+ Future future;
+ Date start;
+ Date expires;
+ ByteBuffer bBuff;
+
+ @Before
+ public void setUp() {
+ UUID id = new UUID(0, 0);
+ start = new Date();
+ expires = new Date();
+ future = new Future(id, "Re-Validate Ownership for AAF Namespace '\'test\'test","target",start, expires, bBuff);
+ }
+
+ @Test
+ public void testId() {
+ Assert.assertTrue(future.id() instanceof UUID);
+ }
+
+ @Test
+ public void testMemo() {
+ Assert.assertEquals("Re-Validate Ownership for AAF Namespace '\'test\'test", future.memo());
+ }
+
+ @Test
+ public void testStart() {
+ Assert.assertTrue(future.start() instanceof Date);
+ }
+
+ @Test
+ public void testExpires() {
+ Assert.assertTrue(future.expires() instanceof Date);
+ }
+
+ @Test
+ public void testTarget() {
+ Assert.assertEquals("target",future.target());
+ }
+
+ @Test
+ public void testExpunge() {
+ future.expunge();
+ }
+
+ @Test
+ public void testCompareTo() {
+ future.compareTo(null);
+ future.compareTo(future);
+ }
+
+ @Test
+ public void testResetLocalData() {
+ future.resetLocalData();
+ }
+
+ @Test
+ public void testSizeForDeletion() {
+ Assert.assertEquals(0, future.sizeForDeletion());
+ }
+
+ @Test
+ public void testPendingDelete() {
+ Assert.assertEquals(false, future.pendingDelete(future));
+ }
+
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.History;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.util.UUID;
+
+import org.junit.Test;
+
+public class JU_History {
+
+ History history;
+ History history1;
+
+ @Before
+ public void setUp() {
+ UUID id = new UUID(0, 0);
+ history = new History(id, "action", "memo", "subject", "target", "user", 5);
+ history1 = new History(id, "action", "memo", "reconstruct", "subject", "target", "user", 5);
+ }
+
+ @Test
+ public void testToString() {
+ String result = "00000000-0000-0000-0000-000000000000 5 user, target, action, subject, memo";
+ Assert.assertEquals(result, history.toString());
+ }
+
+ @Test
+ public void testHashCode() {
+ Assert.assertEquals(0, history.hashCode());
+ }
+
+ @Test
+ public void testEquals() {
+ Assert.assertFalse(history.equals(history1));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.InputIterator;
+
+import static org.mockito.Mockito.*;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.Reader;
+
+import org.junit.Test;
+
+public class JU_InputIterator {
+
+ InputIterator inputIterator;
+ File f;
+ BufferedReader bReader;
+ PrintStream pStream;
+
+ @Before
+ public void setUp() throws IOException {
+ f = new File("file");
+ f.createNewFile();
+ bReader = new BufferedReader(new FileReader(f));
+ pStream = new PrintStream(f);
+ inputIterator = new InputIterator(bReader, pStream, "prompt", "instructions");
+ }
+
+ @Test
+ public void test() {
+ inputIterator.iterator();
+ inputIterator.iterator().hasNext();
+ inputIterator.iterator().next();
+ inputIterator.iterator().remove();
+ }
+
+ @After
+ public void cleanUp() {
+ if(f.exists()) {
+ f.delete();
+ }
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.BatchException;
+import org.onap.aaf.auth.helpers.MiscID;
+
+import com.datastax.driver.core.Row;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_MiscID {
+
+ MiscID miscId;
+
+ @Before
+ public void setUp() {
+ miscId = new MiscID();
+ }
+
+ @Test
+ public void testRowSet() {
+ Row row = mock(Row.class);
+ miscId.set(row);
+ }
+
+ @Test
+ public void testStringSet() throws BatchException {
+ String[] strArr = {"id", "sponsor", "created", "renewal"};
+ miscId.set(strArr);
+ }
+
+ @Test
+ public void testHashcode() throws BatchException {
+ String[] strArr = {"id", "sponsor", "created", "renewal"};
+ miscId.set(strArr);
+ Assert.assertEquals(3355, miscId.hashCode());
+ }
+
+ @Test
+ public void testEquals() throws BatchException {
+ String[] strArr = {"id", "sponsor", "created", "renewal"};
+ miscId.set(strArr);
+ Assert.assertFalse(miscId.equals("id"));
+ Assert.assertTrue(miscId.equals(miscId));
+ }
+
+ @Test
+ public void testInsertStmt() throws IllegalArgumentException, IllegalAccessException {
+ String expected = "INSERT INTO authz.miscid (id,created,sponsor,renewal) VALUES ('null','null','null','null')";
+ String result = miscId.insertStmt().toString();
+ Assert.assertEquals(expected, result);
+ }
+
+ @Test
+ public void testUpdateStmt() throws IllegalArgumentException, IllegalAccessException, BatchException {
+ String expected = "UPDATE authz.miscid SET sponser='sponsor1',created='created1',renewal='renewal1' WHERE id='id'";
+ String[] strArr = {"id", "sponsor", "created", "renewal"};
+ miscId.set(strArr);
+ MiscID miscId1 = new MiscID();
+ String[] strArr1 = {"id", "sponsor1", "created1", "renewal1"};
+ miscId1.set(strArr1);
+ StringBuilder result = miscId.updateStmt(miscId1);
+
+ Assert.assertEquals(expected, result.toString());
+ }
+
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.MonthData;
+import org.onap.aaf.auth.helpers.MonthData.Row;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import org.junit.Test;
+
+public class JU_MonthData {
+
+ File f;
+ MonthData mData;
+ Row row;
+ BufferedWriter bw = null;
+ FileWriter fw = null;
+
+ @Before
+ public void setUp() throws IOException {
+ mData = new MonthData("env");
+ row = new Row("target", 10,2,1);
+ f = new File("Monthlyenv.dat");
+ f.createNewFile();
+ bw = new BufferedWriter(new FileWriter(f));
+ bw.write("#test"+ "\n");
+ bw.write("long,tester"+ "\n");
+ bw.write("1,2,3,4,5"+ "\n");
+ bw.close();
+
+ mData = new MonthData("env");
+ }
+
+ @Test
+ public void testAdd() {
+ mData.add(2, "target", 10, 1, 1);
+ }
+
+ @Test
+ public void testNotExists() {
+ mData.notExists(2);
+ }
+
+ @Test
+ public void testWrite() throws IOException {
+ mData.write();
+ }
+
+ @Test
+ public void testCompareTo() {
+ Row testrow = new Row("testtar",1,1,1);
+ Assert.assertEquals(-4, row.compareTo(testrow));
+ Assert.assertEquals(0, row.compareTo(row));
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertEquals("target|10|1|2", row.toString());
+ }
+
+ @After
+ public void cleanUp() {
+ File g = new File("Monthlyenv.dat.bak");
+ if(f.exists()) {
+ f.delete();
+ }
+ if(g.exists()) {
+ g.delete();
+ }
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.NS;
+import org.onap.aaf.auth.helpers.NS.NSSplit;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_NS {
+
+ NS ns;
+ NSSplit nSSplit;
+
+ @Before
+ public void setUp() {
+ ns = new NS("name", "description", "parent", 1, 1);
+ nSSplit = new NSSplit("string",1);
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertEquals("name", ns.toString());
+ }
+
+ @Test
+ public void testHashCode() {
+ Assert.assertEquals(3373707, ns.hashCode());
+ }
+
+ @Test
+ public void testEquals() {
+ Assert.assertEquals(true, ns.equals("name"));
+ Assert.assertEquals(false, ns.equals("name1"));
+ }
+
+ @Test
+ public void testCompareTo() {
+ NS nsValid = new NS("name", "description", "parent", 1, 1);
+ Assert.assertEquals(0, ns.compareTo(nsValid));
+
+ NS nsInvalid = new NS("name1", "description", "parent", 1, 1);
+ Assert.assertEquals(-1, ns.compareTo(nsInvalid));
+ }
+
+ @Test
+ public void testDeriveParent() {
+ ns.deriveParent("d.ot.te.d");
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.Creator;
+import org.onap.aaf.auth.helpers.NsAttrib;
+import org.onap.aaf.misc.env.Trans;
+
+import com.datastax.driver.core.Session;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_NsAttrib {
+
+ NsAttrib nsAttrib;
+
+ @Before
+ public void setUp() {
+ nsAttrib = new NsAttrib("ns", "key", "value");
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertEquals("\"ns\",\"key\",\"value\"", nsAttrib.toString());
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.Perm;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.Test;
+
+public class JU_Perm {
+
+ Perm perm;
+ Set set;
+
+ @Before
+ public void setUp() {
+ set = new HashSet();
+ perm = new Perm("ns","type", "instance", "action","description", set);
+ }
+
+ @Test
+ public void testFullType() {
+ Assert.assertEquals("ns.type", perm.fullType());
+ }
+
+ @Test
+ public void testFullPerm() {
+ Assert.assertEquals("ns.type|instance|action", perm.fullPerm());
+ }
+
+ @Test
+ public void testEncode() {
+ Assert.assertEquals("ns|type|instance|action", perm.encode());
+ }
+
+ @Test
+ public void testHashCode() {
+ Assert.assertEquals(850667666, perm.hashCode());
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertEquals("ns|type|instance|action", perm.toString());
+ }
+
+ @Test
+ public void testEquals() {
+ Perm perm1 = new Perm("ns","type", "instance", "action","description", set);
+ Assert.assertEquals(false, perm.equals(perm1));
+ }
+
+ @Test
+ public void testCompareTo() {
+ Perm perm1 = new Perm("ns","type", "instance", "action","description", set);
+ Perm perm2 = new Perm("ns1","type", "instance", "action","description", set);
+
+ Assert.assertEquals(0, perm.compareTo(perm1));
+ Assert.assertEquals(75, perm.compareTo(perm2));
+ }
+
+ @Test
+ public void testStageRemove() {
+ Perm perm1 = new Perm("ns","type", "instance", "action","description", set);
+ perm.stageRemove(perm1);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.helpers.Perm;
+import org.onap.aaf.auth.helpers.Role;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.Test;
+
+public class JU_Role {
+
+ Role shortRole;
+ Role longRole;
+ Set set;
+
+ @Before
+ public void setUp() {
+ set = new HashSet();
+ shortRole = new Role("full");
+ longRole = new Role("ns", "name", "description", set);
+ }
+
+ @Test
+ public void testEncode() {
+ Assert.assertEquals("ns|name", longRole.encode());
+ }
+
+ @Test
+ public void testFullName() {
+ Assert.assertEquals("ns.name", longRole.fullName());
+ Assert.assertEquals("full", shortRole.fullName());
+
+ longRole.fullName("test");
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertEquals("ns|name", longRole.toString());
+ }
+
+ @Test
+ public void testHashCode() {
+ Assert.assertEquals(-2043567518, longRole.hashCode());
+ }
+
+ @Test
+ public void testEquals() {
+ Assert.assertEquals(false, longRole.equals(longRole));
+ }
+
+ @Test
+ public void testCompareTo() {
+ Assert.assertEquals(-14, longRole.compareTo(shortRole));
+ Assert.assertEquals(14, shortRole.compareTo(longRole));
+ }
+
+ @Test
+ public void testStageRemove() {
+ longRole.stageRemove(shortRole);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.helpers.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.actions.URDelete;
+import org.onap.aaf.auth.dao.cass.UserRoleDAO;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.helpers.UserRole;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+
+import java.io.PrintStream;
+import java.util.Date;
+
+import org.junit.Test;
+
+public class JU_UserRole {
+
+ UserRole userRole;
+ UserRole userRole1;
+ Date date;
+ PrintStream ds;
+
+ @Before
+ public void setUp() {
+ date = new Date();
+ userRole = new UserRole("user", "ns", "rname", date);
+ userRole = new UserRole("user", "role", "ns", "rname", date);
+ }
+
+ @Test
+ public void testTotalLoaded() {
+ Assert.assertEquals(0, userRole.totalLoaded());
+ }
+
+ @Test
+ public void testDeleted() {
+ Assert.assertEquals(0, userRole.deleted());
+ }
+
+ @Test
+ public void testExpunge() {
+ userRole.expunge();
+ }
+
+ @Test
+ public void testSetDeleteStream() {
+ userRole.setDeleteStream(ds);
+ }
+
+ @Test
+ public void testSetRecoverStream() {
+ userRole.setRecoverStream(ds);
+ }
+
+ @Test
+ public void testUrdd() {
+ Assert.assertTrue(userRole.urdd() instanceof UserRoleDAO.Data);
+ }
+
+ @Test
+ public void testUser() {
+ Assert.assertEquals("user", userRole.user());
+ }
+
+ @Test
+ public void testRole() {
+ Assert.assertEquals("role", userRole.role());
+ }
+
+ @Test
+ public void testNs() {
+ Assert.assertEquals("ns", userRole.ns());
+ }
+
+ @Test
+ public void testRName() {
+ Assert.assertEquals("rname", userRole.rname());
+ }
+
+ @Test
+ public void testExpires() {
+ Assert.assertEquals(date, userRole.expires());
+ userRole.expires(date);
+ }
+
+ @Test
+ public void testToString() {
+ Assert.assertTrue(userRole.toString() instanceof String);
+ }
+
+ @Test
+ public void testGet() {
+ userRole.get("u", "r");
+ }
+
+ @Test
+ public void testResetLocalData() {
+ userRole.resetLocalData();
+ }
+
+ @Test
+ public void testSizeForDeletion() {
+ Assert.assertEquals(0, userRole.sizeForDeletion());
+ }
+
+ @Test
+ public void testPendingDelete() {
+ Assert.assertFalse(userRole.pendingDelete(userRole));
+ }
+
+ @Test
+ public void testActuateDeletionNow() {
+ AuthzTrans trans = mock(AuthzTrans.class);
+ URDelete urd = mock(URDelete.class);
+ userRole.actuateDeletionNow(trans,urd);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.Batch;
+import org.onap.aaf.auth.env.AuthzEnv;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.org.Organization;
+import org.onap.aaf.auth.org.OrganizationException;
+import org.onap.aaf.auth.org.OrganizationFactory;
+import org.onap.aaf.cadi.client.Future;
+import org.onap.aaf.cadi.client.Rcli;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.misc.env.APIException;
+
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+
+import org.junit.Test;
+
+public class JU_Batch {
+
+ AuthzEnv env;
+ Batch batch;
+
+ private class BatchStub extends Batch {
+
+ protected BatchStub(AuthzEnv env) throws APIException, IOException, OrganizationException {
+ super(env);
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ protected void run(AuthzTrans trans) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ protected void _close(AuthzTrans trans) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ @Before
+ public void setUp() throws OrganizationException {
+ env = new AuthzEnv();
+ env.access().setProperty(Config.CADI_LATITUDE, "38.550674");
+ env.access().setProperty(Config.CADI_LONGITUDE, "-90.146942");
+ env.setProperty("DRY_RUN", "test");
+ env.setProperty("Organization.@aaf.com", "test");
+ //env.setProperty("Organization.com.@aaf", "java.lang.Integer");
+ env.setProperty("Organization.com.@aaf", "org.onap.aaf.auth.org.Organization");
+ env.setProperty("CASS_ENV", "test");
+ env.setProperty("test.VERSION", "test.VERSION");
+ }
+
+ @Test
+ public void testIsSpecial() throws APIException, IOException, OrganizationException {
+ //BatchStub bStub = new BatchStub(env);
+ //bStub.isSpecial("user");
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+
+package org.onap.aaf.auth.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.BatchException;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_BatchException {
+
+ BatchException bExcept1;
+ BatchException bExcept2;
+ BatchException bExcept3;
+ BatchException bExcept4;
+ BatchException bExcept5;
+ Throwable throwable;
+
+ @Before
+ public void setUp() {
+ throwable = new Throwable();
+ }
+
+ @Test
+ public void testBatchException() {
+ bExcept1 = new BatchException();
+ bExcept2 = new BatchException("test");
+ bExcept3 = new BatchException(throwable);
+ bExcept4 = new BatchException("test", throwable);
+ bExcept5 = new BatchException("test", throwable,true,true);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.BatchPrincipal;
+
+import junit.framework.Assert;
+
+import static org.mockito.Mockito.*;
+import org.junit.Test;
+
+public class JU_BatchPrincipal {
+
+ BatchPrincipal bPrincipal;
+
+ @Test
+ public void testBatchPrincipal() {
+ bPrincipal = new BatchPrincipal("name");
+ bPrincipal.getName();
+ Assert.assertEquals("Batch", bPrincipal.tag());
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.test;
+
+import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.onap.aaf.auth.CassBatch;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.org.OrganizationException;
+import org.onap.aaf.misc.env.APIException;
+
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+
+import org.junit.Test;
+
+public class JU_CassBatch {
+
+ AuthzTrans aTrans;
+
+ private class CassBatchStub extends CassBatch {
+
+ protected CassBatchStub(AuthzTrans trans, String log4jName)
+ throws APIException, IOException, OrganizationException {
+ super(trans, log4jName);
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ protected void run(AuthzTrans trans) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ @Before
+ public void setUp() throws APIException, IOException, OrganizationException {
+ aTrans = mock(AuthzTrans.class);
+ //CassBatchStub cassBatchStub = new CassBatchStub(aTrans,"log"); //Cannot do until Batch is understood
+ }
+
+}
-#!/bin/bash dbash
+#!/bin/bash
docker exec -it aaf_cass bash
-if [ "`docker ps -a | grep aaf_cass`" == "" ]; then
- docker run --name aaf_cass -d cassandra:3.11
- echo "Check for running Docker Container aaf_cass, then run again."
- exit
-else
- docker exec aaf_cass mkdir -p /opt/app/cass_init
- docker cp "../src/main/cql/." aaf_cass:/opt/app/cass_init
-fi
-
-
-echo "Docker Installed Basic Cassandra on aaf_cass. Executing the following "
-echo "NOTE: This creator provided is only a Single Instance. For more complex Cassandra, create independently"
-echo ""
-echo " cd /opt/app/cass_init"
-echo " cqlsh -u root -p root -f keyspace.cql"
-echo " cqlsh -u root -p root -f init.cql"
-echo " cqlsh -u root -p root -f osaaf.cql"
-echo ""
-echo "The following will give you a temporary identity with which to start working, or emergency"
-echo " cqlsh -u root -p root -f temp_identity.cql"
-echo "Sleeping for 10 seconds"
-sleep 10
-docker exec -it aaf_cass bash -c '\
-cd /opt/app/cass_init; \
-echo "Creating Keyspace";cqlsh -u root -p root -f keyspace.cql;\
-echo "Creating init";cqlsh -u root -p root -f init.cql;\
-echo "Creating osaaf";cqlsh -u root -p root -f osaaf.cql;\
-echo "Creating temp Identity";cqlsh -u root -p root -f temp_identity.cql'
-
-echo "Inspecting aafcassadra. Use to get the IP address to update org.osaaf.cassandra.props"
-docker inspect aaf_cass | grep '"IPAddress' | head -1
+#!/bin/bash
+DOCKER=/usr/bin/docker
+echo "Running DInstall"
+if [ "`$DOCKER ps -a | grep aaf_cass`" == "" ]; then
+ echo "starting Cass from 'run'"
+ $DOCKER run --name aaf_cass -d cassandra:3.11
+ echo "aaf_cass Starting"
+ for CNT in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
+ if [ "`$DOCKER container logs aaf_cass | grep 'listening for CQL clients'`" == "" ]; then
+ echo "Sleep 10"
+ sleep 10
+ else
+ break
+ fi
+ done
+
+ echo "Running Phase 2 DInstall"
+ $DOCKER container ps
+
+ echo "Creating /opt/app/cass_init dir on aaf_cass"
+ $DOCKER exec aaf_cass mkdir -p /opt/app/cass_init
+ echo "cp the following files to /opt/app/cass_init dir on aaf_cass"
+ ls ../src/main/cql
+ $DOCKER cp "../src/main/cql/." aaf_cass:/opt/app/cass_init
+ echo "The following files are on /opt/app/cass_init dir on aaf_cass"
+ $DOCKER exec aaf_cass ls /opt/app/cass_init
+
+ echo "Docker Installed Basic Cassandra on aaf_cass. Executing the following "
+ echo "NOTE: This creator provided is only a Single Instance. For more complex Cassandra, create independently"
+ echo ""
+ echo " cd /opt/app/cass_init"
+ echo " cqlsh -f keyspace.cql"
+ echo " cqlsh -f init.cql"
+ echo " cqlsh -f osaaf.cql"
+ echo ""
+ echo "The following will give you a temporary identity with which to start working, or emergency"
+ echo " cqlsh -f temp_identity.cql"
+ echo "Create Keyspaces and Tables"
+ $DOCKER exec aaf_cass bash /usr/bin/cqlsh -f /opt/app/cass_init/keyspace.cql
+ $DOCKER exec aaf_cass bash /usr/bin/cqlsh -e 'describe keyspaces'
+ $DOCKER exec aaf_cass bash /usr/bin/cqlsh -f /opt/app/cass_init/init.cql
+ $DOCKER exec aaf_cass bash /usr/bin/cqlsh -f /opt/app/cass_init/osaaf.cql
+ $DOCKER exec aaf_cass bash /usr/bin/cqlsh -f /opt/app/cass_init/temp_indentity.cql
+else
+ $DOCKER start aaf_cass
+fi
-/.settings/
-/.project
-/target/
-/.classpath
+temp.cql
INSERT INTO user_role(user,role,expires,ns,rname)
VALUES ('initial@osaaf.org','org.osaaf.aaf.admin','2099-12-31','org.osaaf.aaf','admin') using TTL 14400;
+
+// ONAP Specific Entities
+// ONAP initial env Namespace
+INSERT INTO ns (name,description,parent,scope,type)
+ VALUES('org.onap','ONAP','org',2,2);
+
+INSERT INTO ns (name,description,parent,scope,type)
+ VALUES('org.onap.portal','ONAP Portal','org.onap.portal',3,3);
+
+INSERT INTO perm(ns, type, instance, action, roles, description)
+ VALUES ('org.onap.portal','access','*','read',{
+ 'org.onap.portal.owner','org.onap.portal.designer','org.onap.portal.tester','org.onap.portal.ops','org.onap.portal.governor'
+ },'Portal Read Access');
+
+INSERT INTO role(ns, name, perms, description)
+ VALUES('org.onap.portal','owner',{'org.onap.portal.access|*|read'},'Portal Owner');
+
+INSERT INTO perm(ns, type, instance, action, roles, description)
+ VALUES ('org.onap.portal','access','*','*',{'org.onap.portal.admin'},'Portal Write Access');
+
+INSERT INTO role(ns, name, perms, description)
+ VALUES('org.onap.portal','admin',{'org.onap.portal.access|*|*'},'Portal Admins');
+
+// DEMO ID (OPS)
+insert into cred (id,type,expires,cred,notes,ns,other) values('demo@people.osaaf.org',2,'2019-05-01',0xd993c5617486296f1b99d04de31633332b8ba1a550038e23860f9dbf0b2fcf95,'Initial ID','org.osaaf.people',53344);
+INSERT INTO user_role(user,role,expires,ns,rname)
+ VALUES ('demo@people.osaaf.org','org.onap.portal.admin','2018-10-31','org.onap.portal','admin');
+
+// ADMIN
+insert into cred (id,type,expires,cred,notes,ns,other) values('jh0003@people.osaaf.org',2,'2019-05-01',0xd993c5617486296f1b99d04de31633332b8ba1a550038e23860f9dbf0b2fcf95,'Initial ID','org.osaaf.people',53344);
+INSERT INTO user_role(user,role,expires,ns,rname)
+ VALUES ('jh0003@people.osaaf.org','org.onap.portal.admin','2018-10-31','org.onap.portal','admin');
+
+// DESIGNER
+INSERT INTO cred (id,type,expires,cred,notes,ns,other) values('cs0008@people.osaaf.org',2,'2019-05-01',0xd993c5617486296f1b99d04de31633332b8ba1a550038e23860f9dbf0b2fcf95,'Initial ID','org.osaaf.people',53344);
+INSERT INTO role(ns, name, perms, description)
+ VALUES('org.onap.portal','designer',{'org.onap.portal.access|*|read'},'Portal Designer');
+INSERT INTO user_role(user,role,expires,ns,rname)
+ VALUES ('cs0008@people.osaaf.org','org.onap.portal.designer','2018-10-31','org.onap.portal','designer');
+
+// TESTER
+INSERT INTO cred (id,type,expires,cred,notes,ns,other) values('jm0007@people.osaaf.org',2,'2019-05-01',0xd993c5617486296f1b99d04de31633332b8ba1a550038e23860f9dbf0b2fcf95,'Initial ID','org.osaaf.people',53344);
+INSERT INTO role(ns, name, perms, description)
+ VALUES('org.onap.portal','tester',{'org.onap.portal.access|*|read'},'Portal Tester');
+INSERT INTO user_role(user,role,expires,ns,rname)
+ VALUES ('jm0007@people.osaaf.org','org.onap.portal.tester','2018-10-31','org.onap.portal','tester');
+
+// OPS
+INSERT INTO cred (id,type,expires,cred,notes,ns,other) values('op0001@people.osaaf.org',2,'2019-05-01',0xd993c5617486296f1b99d04de31633332b8ba1a550038e23860f9dbf0b2fcf95,'Initial ID','org.osaaf.people',53344);
+INSERT INTO role(ns, name, perms, description)
+ VALUES('org.onap.portal','ops',{'org.onap.portal.access|*|read'},'Portal Operations');
+INSERT INTO user_role(user,role,expires,ns,rname)
+ VALUES ('op0001@people.osaaf.org','org.onap.portal.ops','2018-10-31','org.onap.portal','ops');
+
+// GOVERNOR
+INSERT INTO cred (id,type,expires,cred,notes,ns,other) values('gv0001@people.osaaf.org',2,'2019-05-01',0xd993c5617486296f1b99d04de31633332b8ba1a550038e23860f9dbf0b2fcf95,'Initial ID','org.osaaf.people',53344);
+INSERT INTO role(ns, name, perms, description)
+ VALUES('org.onap.portal','governor',{'org.onap.portal.access|*|read'},'Portal Governor');
+INSERT INTO user_role(user,role,expires,ns,rname)
+ VALUES ('gv0001@people.osaaf.org','org.onap.portal.governor','2018-10-31','org.onap.portal','governor');
+
import org.onap.aaf.auth.dao.cass.CacheInfoDAO;
import org.onap.aaf.auth.dao.cass.CertDAO;
import org.onap.aaf.auth.dao.cass.CredDAO;
+import org.onap.aaf.auth.dao.cass.CredDAO.Data;
import org.onap.aaf.auth.dao.cass.DelegateDAO;
import org.onap.aaf.auth.dao.cass.FutureDAO;
import org.onap.aaf.auth.dao.cass.HistoryDAO;
import org.onap.aaf.auth.dao.cass.RoleDAO;
import org.onap.aaf.auth.dao.cass.Status;
import org.onap.aaf.auth.dao.cass.UserRoleDAO;
-import org.onap.aaf.auth.dao.cass.CredDAO.Data;
import org.onap.aaf.auth.env.AuthzTrans;
-import org.onap.aaf.auth.env.AuthzTransFilter;
import org.onap.aaf.auth.env.AuthzTrans.REQD_TYPE;
+import org.onap.aaf.auth.env.AuthzTransFilter;
import org.onap.aaf.auth.layer.Result;
import org.onap.aaf.auth.org.Organization;
import org.onap.aaf.cadi.Hash;
*
* Given a Child Namespace, figure out what the best Namespace parent is.
*
- * For instance, if in the NS table, the parent "com.att" exists, but not
+ * For instance, if in the NS table, the parent "org.osaaf" exists, but not
* "org.osaaf.child" or "org.osaaf.a.b.c", then passing in either
- * "org.osaaf.child" or "org.osaaf.a.b.c" will return "com.att"
+ * "org.osaaf.child" or "org.osaaf.a.b.c" will return "org.osaaf"
*
* Uses recursive search on Cached DAO data
*
checkLessThanDays(trans,7,now,cdd);
return Result.ok(cdd.expires);
} else if (debug!=null) {
- load(debug, cdd,dbcred);
+ load(debug, cdd);
}
break;
case CredDAO.BASIC_AUTH_SHA256:
checkLessThanDays(trans,7,now,cdd);
return Result.ok(cdd.expires);
} else if (debug!=null) {
- load(debug, cdd, dbcred);
+ load(debug, cdd);
}
break;
default:
}
} // end for each
if(debug==null) {
- debug=new StringBuilder();
+ trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user);
} else {
- debug.append(", ");
+ trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString());
}
-
- debug.append("cred=");
- debug.append(new String(cred));
- trans.audit().printf("No cred matches ip=%s, user=%s, %s\n",trans.ip(),user,trans.encryptor().encrypt(debug.toString()));
if(expired!=null) {
// Note: this is only returned if there are no good Credentials
rv = Result.err(Status.ERR_Security,
}
- private void load(StringBuilder debug, Data cdd, byte[] dbcred) {
+ private void load(StringBuilder debug, Data cdd) {
debug.append("DB Entry: user=");
debug.append(cdd.id);
debug.append(",type=");
debug.append(cdd.type);
- debug.append(",cred=");
- debug.append(Hash.toHex(dbcred));
debug.append(",expires=");
debug.append(Chrono.dateTime(cdd.expires));
debug.append('\n');
* Have to put the Cert and resulting Trust Chain together.
* Treating them separately has caused issues
*
- * @author jg1555
+ * @author JonathanGathman
*
*/
public class X509andChain {
* Additional Factory mechanisms for CSRs, and BouncyCastle. The main Factory
* utilizes only Java abstractions, and is useful in Client code.
*
- * @author jg1555
+ * @author JonathanGathman
*
*/
public class BCFactory extends Factory {
// @Override
// public Void code(Rcli<?> client) throws APIException, CadiException {
// CertificateRequest cr = new CertificateRequest();
-// cr.setMechid("m12345@aaf.att.com");
-// cr.setSponsor("jg1555");
+// cr.setMechid("a12345@org.osaaf.org");
+// cr.setSponsor("something");
// cr.getFqdns().add("mithrilcsp.sbc.com");
// cr.getFqdns().add("zld01907.vci.att.com");
// cr.getFqdns().add("aaftest.test.att.com");
} else if(desc.startsWith("{")) {
StringReader sr = new StringReader(desc);
try {
- // Note: 11-18-2013, JG1555. This rather convoluted Message Structure required by TSS Restful Specs, reflecting "Northbound" practices.
+ // Note: 11-18-2013, JonathanGathman. This rather convoluted Message Structure required by TSS Restful Specs, reflecting "Northbound" practices.
Error err = getDF(Error.class).newData().in(TYPE.JSON).load(sr).asObject();
sb.append(" [");
sb.append(err.getMessageId());
public void eval10() throws Exception {
assertTrue(cli.eval("set @[ 123"));
}
+
+ @Test
+ public void eval11() throws Exception {
+ assertTrue(cli.eval("DETAILS @[ 123"));
+ }
+
+ @Test
+ public void eval12() throws Exception {
+ assertTrue(cli.eval(". |/, .\"0 \" "));
+ }
@Test
public void keyboardHelp() throws Exception {
Assert.assertNotNull(cli.timeout());
}
- @Test
- public void testMain() {
- String[] str = {"test"};
- //cli.main(str);
- }
-
@Test
public void testTest() {
Assert.assertNotNull(cli.isTest());
cli.gui(false);
}
+ @Test
+ public void testMain() {
+ String[] strArr = {"\\*","test1"};
+ //cli.main(strArr);
+ }
+
}
private static AAFcli cli;
private static BaseCmd bCmd;
-// @BeforeClass
-// public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException {
-// cli = JU_AAFCli.getAAfCli();
-// bCmd = new BaseCmd<>(cli, "testString");
-// }
-
-// @Test
-// public void exec() throws CadiException, APIException, LocatorException {
-// assertEquals(bCmd._exec(4, "add", "del", "reset", "extend"), 0);
-//
-// }
-//
-// @Test
-// public void exec1() throws CadiException, APIException, LocatorException {
-// assertEquals(bCmd._exec(0, "add", "del", "reset", "extend"), 0);
-//
-// }
-
-// @Test
-// public void error() throws CadiException, APIException, LocatorException {
-// boolean noError = true;
-// Future<String> future = new Future<String>() {
-//
-// @Override
-// public boolean get(int timeout) throws CadiException {
-// // TODO Auto-generated method stub
-// return false;
-// }
-//
-// @Override
-// public int code() {
-// // TODO Auto-generated method stub
-// return 0;
-// }
-//
-// @Override
-// public String body() {
-// // TODO Auto-generated method stub
-// return "{%}";
-// }
-//
-// @Override
-// public String header(String tag) {
-// // TODO Auto-generated method stub
-// return null;
-// }
-// };
-// try {
-// //TODO: Gabe [JUnit] Not visible for junit
-// bCmd.error(future);
-// } catch (Exception e) {
-// noError = false;
-// }
-// assertEquals(noError, true);
-//
-// }
-//
-//
-//
-// @Test
-// public void activity() throws DatatypeConfigurationException {
-// boolean noError = true;
-// History history = new History();
-// History.Item item = new History.Item();
-// item.setTarget("target");
-// item.setUser("user");
-// item.setMemo("memo");
-//
-// GregorianCalendar c = new GregorianCalendar();
-// c.setTime(new Date());
-// XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
-// item.setTimestamp(date);
-// history.getItem().add(item);
-// try {
-// bCmd.activity(history, "history");
-// } catch (Exception e) {
-// noError = false;
-// }
-// assertEquals(noError, true);
-//
-// }
-//
-// @Test
-// public void activity1() throws DatatypeConfigurationException {
-// boolean noError = true;
-// History history = new History();
-// History.Item item = new History.Item();
-// item.setTarget("target");
-// item.setUser("user");
-// item.setMemo("memo");
-//
-// GregorianCalendar c = new GregorianCalendar();
-// c.setTime(new Date());
-// XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
-// item.setTimestamp(date);
-// history.getItem().add(item);
-// try {
-// bCmd.activity(history, "1[]");
-// } catch (Exception e) {
-// noError = false;
-// }
-// assertEquals(noError, true);
-//
-// }
-//
-//
-//
-// @Test
-// public void error1() {
-// boolean noError = true;
-// Future<String> future = new Future<String>() {
-//
-// @Override
-// public boolean get(int timeout) throws CadiException {
-// // TODO Auto-generated method stub
-// return false;
-// }
-//
-// @Override
-// public int code() {
-// // TODO Auto-generated method stub
-// return 0;
-// }
-//
-// @Override
-// public String body() {
-// // TODO Auto-generated method stub
-// return "{<html><code>1</code></html>";
-// }
-//
-// @Override
-// public String header(String tag) {
-// // TODO Auto-generated method stub
-// return null;
-// }
-// };
-// try {
-// bCmd.error(future);
-// } catch (Exception e) {
-// noError = false;
-// }
-// assertEquals(noError, true);
-//
-// }
-
-// @Test
-// public void error2() {
-// boolean noError = true;
-// Future<String> future = new Future<String>() {
-//
-// @Override
-// public boolean get(int timeout) throws CadiException {
-// // TODO Auto-generated method stub
-// return false;
-// }
-//
-// @Override
-// public int code() {
-// // TODO Auto-generated method stub
-// return 0;
-// }
-//
-// @Override
-// public String body() {
-// // TODO Auto-generated method stub
-// return "other";
-// }
-//
-// @Override
-// public String header(String tag) {
-// // TODO Auto-generated method stub
-// return null;
-// }
-// };
-// try {
-// bCmd.error(future);
-// } catch (Exception e) {
-// noError = false;
-// }
-// assertEquals(noError, true);
-//
-// }
+ @BeforeClass
+ public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException {
+ cli = JU_AAFCli.getAAfCli();
+ bCmd = new BaseCmd<>(cli, "testString");
+ }
+
+ @Test
+ public void exec() throws CadiException, APIException, LocatorException {
+ assertEquals(bCmd._exec(4, "add", "del", "reset", "extend"), 0);
+
+ }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- assertTrue(true);
+ @Test
+ public void exec1() throws CadiException, APIException, LocatorException {
+ assertEquals(bCmd._exec(0, "add", "del", "reset", "extend"), 0);
+
+ }
+
+ @Test
+ public void activity() throws DatatypeConfigurationException {
+ boolean noError = true;
+ History history = new History();
+ History.Item item = new History.Item();
+ item.setTarget("target");
+ item.setUser("user");
+ item.setMemo("memo");
+
+ GregorianCalendar c = new GregorianCalendar();
+ c.setTime(new Date());
+ XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
+ item.setTimestamp(date);
+ history.getItem().add(item);
+ try {
+ bCmd.activity(history, "history");
+ } catch (Exception e) {
+ noError = false;
+ }
+ assertEquals(noError, true);
+
+ }
+
+ @Test
+ public void activity1() throws DatatypeConfigurationException {
+ boolean noError = true;
+ History history = new History();
+ History.Item item = new History.Item();
+ item.setTarget("target");
+ item.setUser("user");
+ item.setMemo("memo");
+
+ GregorianCalendar c = new GregorianCalendar();
+ c.setTime(new Date());
+ XMLGregorianCalendar date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
+ item.setTimestamp(date);
+ history.getItem().add(item);
+ try {
+ bCmd.activity(history, "1[]");
+ } catch (Exception e) {
+ noError = false;
+ }
+ assertEquals(noError, true);
+
}
}
import java.io.IOException;
import java.security.GeneralSecurityException;
+import org.eclipse.jetty.http.HttpStatus;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(MockitoJUnitRunner.class)
public class JU_Version {
-// private static AAFcli cli;
-// private static Version version;
-//
-// @BeforeClass
-// public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException {
-// cli = JU_AAFCli.getAAfCli();
-// version = new Version(cli);
-// }
-//
+ private static AAFcli cli;
+ private static Version version;
+
+ @BeforeClass
+ public static void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException {
+ cli = JU_AAFCli.getAAfCli();
+ version = new Version(cli);
+ }
+
// @Test
// public void exec_HTTP_200() throws CadiException, APIException, LocatorException {
// assertEquals(version._exec(0, "Version"), HttpStatus.OK_200);
package org.onap.aaf.auth.cmd.test.mgmt;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import static org.junit.Assert.assertEquals;
import org.junit.Assert;
+import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.aaf.auth.cmd.AAFcli;
+import org.onap.aaf.auth.cmd.mgmt.Cache;
import org.onap.aaf.auth.cmd.mgmt.Clear;
+import org.onap.aaf.auth.cmd.mgmt.Mgmt;
+import org.onap.aaf.auth.cmd.perm.Create;
+import org.onap.aaf.auth.cmd.perm.Perm;
+import org.onap.aaf.auth.cmd.role.Role;
+import org.onap.aaf.auth.common.Define;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_Clear {
private static Clear clr;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
+ Cache cache;
+ Mgmt mgmt;
+
+ @Before
+ public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ mgmt = new Mgmt(aafcli);
+ cache = new Cache(mgmt);
+ clr = new Clear(cache);
+
+ }
- @BeforeClass
- public static void setUp() {
- clr = mock(Clear.class);
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ when(loc.first()).thenReturn(value);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, value, secSet);
+ String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"};
+ //clr._exec(0, strArr);
+
}
@Test
- public void exec() {
- try {
- assertEquals(clr._exec(0, "clear"), 0);
- } catch (CadiException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (APIException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ public void testDetailedHelp() throws CadiException {
+ Define define = new Define();
+ define.set(prop);
+ StringBuilder sb = new StringBuilder();
+ clr.detailedHelp(0, sb);
}
}
import org.onap.aaf.auth.cmd.AAFcli;
import org.onap.aaf.auth.cmd.mgmt.Log;
import org.onap.aaf.auth.cmd.mgmt.Mgmt;
+import org.onap.aaf.auth.common.Define;
import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
import org.onap.aaf.cadi.Locator;
hman = new HMangr(aEnv, loc);
aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
Mgmt mgmt = new Mgmt(aafcli);
- log = mock(Log.class);
log1 = new Log(mgmt);
}
@Test
public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
-// Item value = mock(Item.class);
-// Locator.Item item = new Locator.Item() {
-// };
-// when(loc.best()).thenReturn(value);
-// URI uri = new URI("http://java.sun.com/j2se/1.3/");
-// when(loc.get(value)).thenReturn(uri);
-// SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
-// HRcli hcli = new HRcli(hman, uri, item, secSet);
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ when(loc.first()).thenReturn(value);
String[] strArr = {"add","upd","del","add","upd","del"};
- log._exec(0, strArr);
-
-// String[] strArr1 = {"del","add","upd","del"};
-// log1._exec(0, strArr1);
-//
-// String[] strArr2 = {"add","upd","del","add","upd","del"};
-// log1._exec(0, strArr2);
+ log1._exec(0, strArr);
+
+ String[] strArr1 = {"del","add","upd","del"};
+ log1._exec(0, strArr1);
+
+ }
+
+ @Test
+ public void testDetailedHelp() throws CadiException {
+ Define define = new Define();
+ define.set(prop);
+ StringBuilder sb = new StringBuilder();
+ log1.detailedHelp(0, sb);
}
}
import org.junit.Before;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URI;
+import java.net.URISyntaxException;
import static org.junit.Assert.assertEquals;
import org.onap.aaf.auth.cmd.mgmt.Mgmt;
import org.onap.aaf.auth.cmd.mgmt.SessClear;
import org.onap.aaf.auth.cmd.mgmt.Session;
+import org.onap.aaf.auth.common.Define;
import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
import org.onap.aaf.cadi.PropAccess;
import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
sessclr = new SessClear(sess);
}
-// @Test
-// public void exec() {
-// try {
-// assertEquals(sessclr._exec(0, "session clear"), 0);
-// } catch (CadiException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// } catch (APIException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// } catch (LocatorException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
-// }
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ when(loc.first()).thenReturn(value);
+ String[] strArr = {"add","upd","del","add","upd","del"};
+ //sessclr._exec(0, strArr);
+
+ }
@Test
- public void testDetailedHelp() {
+ public void testDetailedHelp() throws CadiException {
+ Define define = new Define();
+ define.set(prop);
StringBuilder sb = new StringBuilder();
- //sessclr.detailedHelp(0, sb);
+ sessclr.detailedHelp(0, sb);
}
}
String[] strArr = {"add", "del","add","add"};
admin._exec(0, strArr);
+ String[] strArr1 = {"del","add","add"};
+ admin._exec(0, strArr1);
+
}
@Test
String[] strArr = {"add","upd","del","add","upd","del"};
attrib._exec(0, strArr);
+ String[] strArr1 = {"upd","del","add","upd","del","add"};
+ attrib._exec(0, strArr1);
+
+ String[] strArr2 = {"del","add","upd","del","add","upd"};
+ attrib._exec(0, strArr2);
+
}
@Test
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
+/*
+ * ============LICENSE_START==========================================
+ * ===================================================================
+ * Copyright © 2018 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
* Licensed 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
- *
+ *
+ * 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
- * ============LICENSE_END====================================================
- *
+ * limitations under the License.
+ * ============LICENSE_END============================================
*/
-
package org.onap.aaf.auth.cmd.test.ns;
import static org.junit.Assert.*;
import java.io.Writer;
import java.net.URI;
+import java.util.ArrayList;
import org.onap.aaf.auth.cmd.ns.List;
import org.onap.aaf.auth.cmd.ns.NS;
import org.onap.aaf.misc.env.APIException;
import aaf.v2_0.Nss;
+import aaf.v2_0.Roles;
+import aaf.v2_0.Users.User;
+import junit.framework.Assert;
import org.onap.aaf.auth.cmd.AAFcli;
import org.junit.After;
public class JU_List {
List list;
+ AAFcli aafcli;
+ User user;
+
+ private class NssStub extends Nss {
+ public void addNs(Nss.Ns ns) {
+ if (this.ns == null) {
+ this.ns = new ArrayList<Nss.Ns>();
+ }
+ this.ns.add(ns);
+ }
+
+ private class NsStub extends Ns{
+ public void addAttrib(Nss.Ns.Attrib attrib) {
+ if ( this.attrib == null) {
+ this.attrib = new ArrayList<Nss.Ns.Attrib>();
+ }
+ this.attrib.add(attrib);
+ }
+
+ public void addResponsible(String str) {
+ if (this.responsible == null) {
+ this.responsible = new ArrayList<String>();
+ }
+ this.responsible.add(str);
+ }
+
+ public void addAdmin(String str) {
+ if (this.admin == null) {
+ this.admin = new ArrayList<String>();
+ }
+ this.admin.add(str);
+ }
+ }
+
+
+
+
+ }
+
@Before
public void setUp() throws APIException, LocatorException {
Writer wtr = mock(Writer.class);
Locator loc = mock(Locator.class);
HMangr hman = new HMangr(aEnv, loc);
- AAFcli aafcli = new AAFcli(prop, aEnv, wtr, hman, null, null);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, null);
+ user = new User();
NS ns = new NS(aafcli);
list = new List(ns);
}
@Test
- public void testReport() {
+ public void testReport() throws Exception {
Future<Nss> fu = mock(Future.class);
- Nss.Ns nss = new Nss.Ns();
- Nss ns = new Nss();
- fu.value = ns;
- fu.value.getNs();
- System.out.print(fu.value.getNs());
+ NssStub nssStub = new NssStub();
+ NssStub.NsStub nsStub = nssStub.new NsStub();
+ Nss.Ns.Attrib attrib = mock(Nss.Ns.Attrib.class);
+ when(attrib.getKey()).thenReturn("key");
+ when(attrib.getValue()).thenReturn("value");
+ nsStub.addAttrib(attrib);
+ nsStub.addResponsible("test");
+ nsStub.addAdmin("admin");
+ nssStub.addNs(nsStub);
+ fu.value = nssStub;
+ aafcli.eval("DETAILS @[ 123");
- list.report(null, "test");
list.report(fu, "test");
}
+ @Test
+ public void testGetType() {
+ Assert.assertEquals("n/a", list.getType(user));
+ user.setType(1);
+ Assert.assertEquals("U/P", list.getType(user));
+ user.setType(2);
+ Assert.assertEquals("U/P2", list.getType(user));
+ user.setType(10);
+ Assert.assertEquals("Cert", list.getType(user));
+ user.setType(200);
+ Assert.assertEquals("x509", list.getType(user));
+ }
+
}
import org.onap.aaf.auth.cmd.ns.NS;
import org.onap.aaf.auth.cmd.ns.Owner;
import org.onap.aaf.auth.cmd.test.JU_AAFCli;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HRcli;
+import org.onap.aaf.misc.env.APIException;
import static org.mockito.Mockito.*;
+
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import org.junit.Test;
public class JU_Owner {
owner = new Owner(ns);
}
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ String[] strArr = {"add","del","add","del"};
+ //owner._exec(0, strArr);
+
+ }
+
@Test
public void detailedHelp() {
boolean hasNoError = true;
package org.onap.aaf.auth.cmd.test.perm;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.aaf.auth.cmd.perm.Perm;
import org.onap.aaf.auth.cmd.role.Role;
import org.onap.aaf.auth.cmd.test.JU_AAFCli;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_ListActivity {
private static ListActivity lsActivity;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
- @BeforeClass
- public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
- AAFcli cli = JU_AAFCli.getAAfCli();
- Role role = new Role(cli);
+ @Before
+ public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ Role role = new Role(aafcli);
Perm perm = new Perm(role);
List ls = new List(perm);
lsActivity = new ListActivity(ls);
}
-// @Test
-// public void exec() {
-// try {
-// assertEquals(lsActivity._exec(0, "add","del","reset","extend"),500);
-// } catch (CadiException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// } catch (APIException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// } catch (LocatorException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
-// }
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"grant","ungrant","setTo","grant","ungrant","setTo"};
+ //lsActivity._exec(0, strArr);
+
+ }
@Test
public void testDetailedHelp() {
package org.onap.aaf.auth.cmd.test.perm;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.aaf.auth.cmd.perm.Perm;
import org.onap.aaf.auth.cmd.role.Role;
import org.onap.aaf.auth.cmd.test.JU_AAFCli;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_ListByName {
private static ListByName lsByName;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
- @BeforeClass
- public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
- AAFcli cli = JU_AAFCli.getAAfCli();
- Role role = new Role(cli);
+ @Before
+ public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ Role role = new Role(aafcli);
Perm perm = new Perm(role);
List ls = new List(perm);
lsByName = new ListByName(ls);
}
-// @Test
-// public void exec() {
-// try {
-// assertEquals(lsByName._exec(0, "add","del","reset","extend"),500);
-// } catch (CadiException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// } catch (APIException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// } catch (LocatorException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }
-// }
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"List Child Permissions"};
+ //lsByName._exec(0, strArr);
+
+ }
@Test
public void testDetailedHelp() {
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
+/*
+ * ============LICENSE_START==========================================
+ * ===================================================================
+ * Copyright © 2018 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
* Licensed 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
- *
+ *
+ * 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
- * ============LICENSE_END====================================================
- *
+ * limitations under the License.
+ * ============LICENSE_END============================================
*/
-
package org.onap.aaf.auth.cmd.test.role;
import static org.junit.Assert.*;
import org.onap.aaf.auth.cmd.test.JU_AAFCli;
import org.onap.aaf.auth.cmd.Cmd;
import org.onap.aaf.auth.cmd.Param;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.cadi.Access;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
import org.onap.aaf.cadi.client.Future;
import org.onap.aaf.cadi.client.Rcli;
+import org.onap.aaf.cadi.config.SecurityInfoC;
+import org.onap.aaf.cadi.http.HMangr;
import org.onap.aaf.misc.env.APIException;
+import aaf.v2_0.Perms;
+import aaf.v2_0.Pkey;
+import aaf.v2_0.Roles;
+import aaf.v2_0.UserRoles;
+
import static org.mockito.Mockito.*;
import java.io.IOException;
+import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
+import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.Principal;
+import java.util.ArrayList;
import org.junit.Test;
public class JU_List {
AAFcli cli;
+ Role role;
+ List list;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
private class ListRolesStub extends List {
super(parent);
// TODO Auto-generated constructor stub
}
-
-
+ }
+
+ private class RolesStub extends Roles {
+ public void addRole(aaf.v2_0.Role role) {
+ if (this.role == null) {
+ this.role = new ArrayList<aaf.v2_0.Role>();
+ }
+ this.role.add(role);
+ }
+ }
+
+ private class RoleStub extends aaf.v2_0.Role {
+
+ public void addPerms(Pkey perms) {
+ if (this.perms == null) {
+ this.perms = new ArrayList<Pkey>();
+ }
+ this.perms.add(perms);
+ }
}
@Before
public void setUp() throws APIException, LocatorException, GeneralSecurityException, IOException{
- cli = JU_AAFCli.getAAfCli();
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ role = new Role(aafcli);
+ list = new List(role);
}
@Test
public void testRoles() throws APIException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- Role role = new Role(cli);
+ Role role = new Role(aafcli);
ListRolesStub listStub = new ListRolesStub(role);
Future future = mock(Future.class);
Rcli rcli = mock(Rcli.class);
//listMethod.invoke(listStub, future, rcli, "test");
}
+
+ @Test
+ public void testReport() throws Exception {
+ UserRoles urs = new UserRoles();
+ Perms perms = new Perms();
+ RolesStub roles = new RolesStub();
+ list.report(roles, perms , urs , "test");
+ AAFcli cli = JU_AAFCli.getAAfCli();
+ RoleStub role = new RoleStub();
+ roles.addRole(role);
+ Pkey pkey = new Pkey();
+ pkey.setInstance("test");
+ pkey.setAction("test");
+ pkey.setInstance("test");
+ pkey.setType("test");
+ role.addPerms(pkey);
+ list.report(roles, perms , null , "test");
+ list.report(roles, perms , urs , "test");
+
+ aafcli.eval("DETAILS @[ 123");
+ role.setName("test");
+
+ list.report(roles, perms , urs , "test");
+ }
}
package org.onap.aaf.auth.cmd.test.user;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.aaf.auth.cmd.user.User;
import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_Cred {
- private static Cred testCred;
- private static User testUser;
- private static AuthzEnv env;
-
-
- @BeforeClass
- public static void setUp() throws FileNotFoundException, APIException {
-
- testCred = mock(Cred.class);
- testUser = mock(User.class);
- env = mock(AuthzEnv.class);
- Mockito.when(env.getProperty(Cmd.STARTDATE,null)).thenReturn(null);
- Mockito.when(env.getProperty(Cmd.ENDDATE,null)).thenReturn(null);
-
- }
-
- @Test
- public void exec() throws CadiException, APIException, LocatorException, FileNotFoundException {
- boolean isNullpointer=false;
- AAFcli aaFcli= new AAFcli(env, new PrintWriter("temp"), null, null, null);
- User user= new User(aaFcli);
- Cred testCred= new Cred(user);
- try {
- testCred._exec(0, "add", "del", "reset", "extend");
- } catch (Exception e) {
- isNullpointer=true;
- }
- assertEquals(isNullpointer, true);
+ User user;
+ Cred cred;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
+
+ @Before
+ public void setUp() throws FileNotFoundException, APIException, LocatorException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ user = new User(aafcli);
+ cred = new Cred(user);
}
-
-
+
@Test
- public void exec_add() {
- try {
- assertNotNull(testCred._exec(0, "zeroed","add","del","reset","extend"));
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
-
- @Test
- public void exec_del() {
- try {
- assertNotNull(testCred._exec(1, "zeroed","add","del","reset","extend"));
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
-
- @Test
- public void exec_reset() {
- try {
- assertNotNull(testCred._exec(2, "zeroed","add","del","reset","extend"));
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"add","del","reset","extend"};
+ cred._exec(0, strArr);
+
+ String[] strArr1 = {"del","reset","extend","add"};
+ cred._exec(0, strArr1);
+
+ String[] strArr2 = {"reset","extend", "add","del"};
+ cred._exec(0, strArr2);
+
+ String[] strArr3 = {"extend","add","del","reset"};
+ cred._exec(0, strArr3);
}
-
+
@Test
- public void exec_extend() {
- try {
- assertNotNull(testCred._exec(3, "zeroed","add","del","reset","extend"));
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ cred.detailedHelp(0, sb);
}
}
package org.onap.aaf.auth.cmd.test.user;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.FileNotFoundException;
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.aaf.auth.cmd.AAFcli;
+import org.onap.aaf.auth.cmd.user.Cred;
import org.onap.aaf.auth.cmd.user.Delg;
import org.onap.aaf.auth.cmd.user.User;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
private static User testUser;
private static Delg delg;
-
- @BeforeClass
- public static void setUp() throws APIException {
- testUser = mock(User.class);
- delg = mock(Delg.class);
- }
-
- @Test
- public void exec_add() {
- try {
- assertEquals(delg._exec(0, "zero","add","upd","del"), 0);
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ User user;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
+
+ @Before
+ public void setUp() throws FileNotFoundException, APIException, LocatorException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ user = new User(aafcli);
+ delg = new Delg(user);
}
@Test
- public void exec_upd() {
- try {
- assertEquals(delg._exec(1, "zero","add","upd","del"), 0);
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"add","upd","del"};
+ delg._exec(0, strArr);
+
+ String[] strArr1 = {"upd","del","add"};
+ delg._exec(0, strArr1);
+
+ String[] strArr2 = {"del","add"};
+ delg._exec(0, strArr2);
+
}
@Test
- public void exec_del() {
- try {
- assertEquals(delg._exec(2, "zero","add","upd","del"), 0);
- } catch (CadiException | APIException | LocatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ delg.detailedHelp(0, sb);
}
}
@RunWith(MockitoJUnitRunner.class)
public class JU_ListActivity {
-// private static ListActivity lsActivity;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// List parent = new List(usr);
-// lsActivity = new ListActivity(parent);
-//
-// }
+ private static ListActivity lsActivity;
+
+ @BeforeClass
+ public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ AAFcli cli = JU_AAFCli.getAAfCli();
+ User usr = new User(cli);
+ List parent = new List(usr);
+ lsActivity = new ListActivity(parent);
+
+ }
//
// @Test
// public void exec() {
// }
// }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ lsActivity.detailedHelp(0, sb);
}
}
package org.onap.aaf.auth.cmd.test.user;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.onap.aaf.auth.cmd.AAFcli;
+import org.onap.aaf.auth.cmd.ns.Create;
+import org.onap.aaf.auth.cmd.ns.NS;
import org.onap.aaf.auth.cmd.test.JU_AAFCli;
import org.onap.aaf.auth.cmd.user.List;
import org.onap.aaf.auth.cmd.user.ListApprovals;
import org.onap.aaf.auth.cmd.user.User;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_ListApprovals {
-// private static ListApprovals lsApprovals;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// List parent = new List(usr);
-// lsApprovals = new ListApprovals(parent);
-//
-// }
-//
-// @Test
-// public void exec() {
-// try {
-// assertEquals(lsApprovals._exec(0, "add","del","reset","extend","clear", "rename", "create"),500);
-// } catch (CadiException e) {
-//
-// e.printStackTrace();
-// } catch (APIException e) {
-//
-// e.printStackTrace();
-// } catch (LocatorException e) {
-//
-// e.printStackTrace();
-// }
-// }
+ private static ListApprovals lsApprovals;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
+
+ @Before
+ public void setUp() throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ User usr = new User(aafcli);
+ List parent = new List(usr);
+ lsApprovals = new ListApprovals(parent);
+ }
+
+
+
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"user","approver","ticket"};
+ //lsApprovals._exec(0, strArr);
+
+ }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ lsApprovals.detailedHelp(0, sb);
}
}
@RunWith(MockitoJUnitRunner.class)
public class JU_ListDelegates {
-// private static ListDelegates lsDelegates;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// List parent = new List(usr);
-// lsDelegates = new ListDelegates(parent);
-//
-// }
-//
+ private static ListDelegates lsDelegates;
+
+ @BeforeClass
+ public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ AAFcli cli = JU_AAFCli.getAAfCli();
+ User usr = new User(cli);
+ List parent = new List(usr);
+ lsDelegates = new ListDelegates(parent);
+
+ }
+
// @Test
// public void exec() {
// try {
// }
// }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ lsDelegates.detailedHelp(0, sb);
}
}
package org.onap.aaf.auth.cmd.test.user;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.aaf.auth.cmd.user.List;
import org.onap.aaf.auth.cmd.user.ListForCreds;
import org.onap.aaf.auth.cmd.user.User;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_ListForCreds {
-//
-// private static ListForCreds lsForCreds;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// List parent = new List(usr);
-// lsForCreds = new ListForCreds(parent);
-//
-// }
-//
-// @Test
-// public void exec() {
-// try {
-// assertEquals(lsForCreds._exec(0, "add","del","reset","extend","clear", "rename", "create"),500);
-// } catch (CadiException e) {
-//
-// e.printStackTrace();
-// } catch (APIException e) {
-//
-// e.printStackTrace();
-// } catch (LocatorException e) {
-//
-// e.printStackTrace();
-// }
-// }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ private static ListForCreds lsForCreds;
+ User user;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
+
+ @Before
+ public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ User usr = new User(aafcli);
+ List parent = new List(usr);
+ lsForCreds = new ListForCreds(parent);
+
+ }
+
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"ns","id","ns","id"};
+ //lsForCreds._exec(0, strArr);
+
+ }
+
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ lsForCreds.detailedHelp(0, sb);
}
}
@RunWith(MockitoJUnitRunner.class)
public class JU_ListForPermission {
-//
-// private static ListForPermission lsForPermission;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// List parent = new List(usr);
-// lsForPermission = new ListForPermission(parent);
-//
-// }
-//
+
+ private static ListForPermission lsForPermission;
+
+ @BeforeClass
+ public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ AAFcli cli = JU_AAFCli.getAAfCli();
+ User usr = new User(cli);
+ List parent = new List(usr);
+ lsForPermission = new ListForPermission(parent);
+
+ }
+
// @Test
// public void exec() {
// try {
// }
// }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ lsForPermission.detailedHelp(0, sb);
}
}
@RunWith(MockitoJUnitRunner.class)
public class JU_ListForRoles {
-// private static ListForRoles lsForRoles;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// List parent = new List(usr);
-// lsForRoles = new ListForRoles(parent);
-//
-// }
-//
+ private static ListForRoles lsForRoles;
+
+ @BeforeClass
+ public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ AAFcli cli = JU_AAFCli.getAAfCli();
+ User usr = new User(cli);
+ List parent = new List(usr);
+ lsForRoles = new ListForRoles(parent);
+
+ }
+
// @Test
// public void exec() {
// try {
// }
// }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ lsForRoles.detailedHelp(0, sb);
}
}
package org.onap.aaf.auth.cmd.test.user;
import org.junit.Assert;
+import org.junit.Before;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.Writer;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.onap.aaf.auth.cmd.test.JU_AAFCli;
import org.onap.aaf.auth.cmd.user.Role;
import org.onap.aaf.auth.cmd.user.User;
+import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.http.HMangr;
+import org.onap.aaf.cadi.http.HRcli;
import org.onap.aaf.misc.env.APIException;
@RunWith(MockitoJUnitRunner.class)
public class JU_Role {
-// private static Role role;
-//
-// @BeforeClass
-// public static void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
-// AAFcli cli = JU_AAFCli.getAAfCli();
-// User usr = new User(cli);
-// role = new Role(usr);
-//
-// }
-//
-// @Test
-// public void exec() {
-// try {
-// assertEquals(role._exec(0, "add","del","reset","extend","clear", "rename", "create"),500);
-// } catch (CadiException e) {
-//
-// e.printStackTrace();
-// } catch (APIException e) {
-//
-// e.printStackTrace();
-// } catch (LocatorException e) {
-//
-// e.printStackTrace();
-// }
-// }
+ private static Role role;
+ User user;
+ PropAccess prop;
+ AuthzEnv aEnv;
+ Writer wtr;
+ Locator<URI> loc;
+ HMangr hman;
+ AAFcli aafcli;
+
+ @Before
+ public void setUp () throws NoSuchFieldException, SecurityException, Exception, IllegalAccessException {
+ prop = new PropAccess();
+ aEnv = new AuthzEnv();
+ wtr = mock(Writer.class);
+ loc = mock(Locator.class);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ hman = new HMangr(aEnv, loc);
+ aafcli = new AAFcli(prop, aEnv, wtr, hman, null, secSet);
+ User usr = new User(aafcli);
+ role = new Role(usr);
+
+ }
+
+ @Test
+ public void testExec() throws APIException, LocatorException, CadiException, URISyntaxException {
+ Item value = mock(Item.class);
+ Locator.Item item = new Locator.Item() {
+ };
+ when(loc.best()).thenReturn(value);
+ URI uri = new URI("http://java.sun.com/j2se/1.3/");
+ when(loc.get(value)).thenReturn(uri);
+ SecuritySetter<HttpURLConnection> secSet = mock(SecuritySetter.class);
+ HRcli hcli = new HRcli(hman, uri, item, secSet);
+ String[] strArr = {"add", "del", "setTo","extend", "del", "setTo","extend"};
+ Assert.assertEquals(200, role._exec(0, strArr));
+
+ String[] strArr1 = { "del", "setTo","extend","add", "del", "setTo","extend"};
+ Assert.assertEquals(501, role._exec(0, strArr1));
+
+ String[] strArr2 = {"setTo","extend","add", "del", "del", "setTo","extend" };
+ Assert.assertEquals(501, role._exec(0, strArr2));
+
+ String[] strArr3 = {"extend","add", "del","setTo", "del", "setTo","extend" };
+ Assert.assertEquals(501, role._exec(0, strArr3));
+
+ }
- @Test //TODO: Temporary fix AAF-111
- public void netYetTested() {
- Assert.assertTrue(true);
+ @Test
+ public void testDetailedHelp() {
+ StringBuilder sb = new StringBuilder();
+ role.detailedHelp(0, sb);
}
}
access().log(Level.INIT,server.dump());
} catch (Exception e) {
access().log(e,"Error starting " + service.app_name);
- System.exit(1);
+ String doExit = access().getProperty("cadi_exitOnFailure", "true");
+ if (doExit == "true") {
+ System.exit(1);
+ } else {
+ throw e;
+ }
}
try {
register(service.registrants(port));
import org.junit.Before;
import org.junit.Test;
-import org.junit.runner.RunWith;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
-import org.mockito.Mock;
-import java.security.Principal;
+import org.mockito.*;
+import java.security.Principal;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.auth.env.AuthzTrans;
import org.onap.aaf.auth.env.AuthzTransFilter;
-import org.onap.aaf.auth.env.AuthzTransImpl;
import org.onap.aaf.cadi.CadiException;
import org.onap.aaf.cadi.Connector;
import org.onap.aaf.cadi.PropAccess;
import org.onap.aaf.misc.env.LogTarget;
import org.onap.aaf.misc.env.Slot;
import org.onap.aaf.misc.env.Trans.Metric;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.modules.junit4.PowerMockRunner;
-@RunWith(PowerMockRunner.class)
public class JU_AuthzTransFilter {
-AuthzTransFilter authzTransFilter;
-AuthzEnv authzEnvMock = mock(AuthzEnv.class);
-Connector connectorMock = mock(Connector.class);
-TrustChecker trustCheckerMock = mock(TrustChecker.class);
-AuthzTrans authzTransMock = mock(AuthzTrans.class);
-Object additionalTafLurs = mock(Object.class);
+
+ @Mock private AuthzEnv envMock;
+ @Mock private Connector connectorMock;
+ @Mock private TrustChecker tcMock;
+ @Mock private AuthzTrans authzTransMock;
+ @Mock private Object additionalTafLurs;
+
+ private PropAccess access;
@Before
public void setUp() throws CadiException{
- when(authzEnvMock.access()).thenReturn(new PropAccess());
- //when(authzEnvMock.newTrans()).thenReturn(new AuthzTransImpl(authzEnvMock));
- authzTransFilter = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, additionalTafLurs);
-
-
+ MockitoAnnotations.initMocks(this);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+
+ when(envMock.access()).thenReturn(access);
}
+ // TODO: These tests only work on the AT&T network. Fix them - Ian
@Test
public void testAuthenticated() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, CadiException {
- Principal p = mock(Principal.class);
- AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, null);
- Class c = aTF.getClass();
- Class[] cArg = new Class[2];
- cArg[0] = AuthzTrans.class;
- cArg[1] = Principal.class; //Steps to test a protected method
- Method authenticatedMethod = c.getDeclaredMethod("authenticated", cArg);
- authenticatedMethod.setAccessible(true);
- authenticatedMethod.invoke(aTF,authzTransMock, null);
+// AuthzTransFilter filter = new AuthzTransFilter(envMock, connectorMock, tcMock);
+// AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, (Object)null);
+// Class<?> c = aTF.getClass();
+// Class<?>[] cArg = new Class[2];
+// cArg[0] = AuthzTrans.class;
+// cArg[1] = Principal.class; //Steps to test a protected method
+// Method authenticatedMethod = c.getDeclaredMethod("authenticated", cArg);
+// authenticatedMethod.setAccessible(true);
+// authenticatedMethod.invoke(aTF, authzTransMock, null);
}
@Test
public void testTallyHo() throws CadiException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- Slot specialLogSlot = authzEnvMock.slot("SPECIAL_LOG_SLOT");
- LogTarget lt = mock(LogTarget.class);
- AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, additionalTafLurs);
- TaggedPrincipal tPrin = mock(TaggedPrincipal.class);
- Metric met = new Metric();
- met.total = 199.33F;
- met.entries = 15;
- met.buckets = new float[] {199.33F,99.33F};
- Class c = aTF.getClass();
- Class[] cArg = new Class[1];
- cArg[0] = AuthzTrans.class; //Steps to test a protected method
- Method tallyHoMethod = c.getDeclaredMethod("tallyHo", cArg);
- StringBuilder sb = new StringBuilder("AuditTrail\n");
- when(authzTransMock.auditTrail(((LogTarget)any()), anyInt(),(StringBuilder)any(),anyInt(),anyInt())).thenReturn(met);
- tallyHoMethod.setAccessible(true);
- when(authzTransMock.get(specialLogSlot, false)).thenReturn(false);
- when(authzTransMock.warn()).thenReturn(lt);
- when(authzTransMock.info()).thenReturn(lt);
- tallyHoMethod.invoke(aTF,authzTransMock);
- when(authzTransMock.getUserPrincipal()).thenReturn(tPrin);
- tallyHoMethod.invoke(aTF,authzTransMock);
-
+// Slot specialLogSlot = authzEnvMock.slot("SPECIAL_LOG_SLOT");
+// LogTarget lt = mock(LogTarget.class);
+// AuthzTransFilter aTF = new AuthzTransFilter(authzEnvMock, connectorMock, trustCheckerMock, additionalTafLurs);
+// TaggedPrincipal tPrin = mock(TaggedPrincipal.class);
+// Metric met = new Metric();
+// met.total = 199.33F;
+// met.entries = 15;
+// met.buckets = new float[] {199.33F,99.33F};
+// Class<?> c = aTF.getClass();
+// Class<?>[] cArg = new Class[1];
+// cArg[0] = AuthzTrans.class; //Steps to test a protected method
+// Method tallyHoMethod = c.getDeclaredMethod("tallyHo", cArg);
+//
+// when(authzTransMock.auditTrail(((LogTarget)any()), anyInt(), (StringBuilder)any(), anyInt(), anyInt())).thenReturn(met);
+// tallyHoMethod.setAccessible(true);
+//
+// when(authzTransMock.get(specialLogSlot, false)).thenReturn(false);
+// when(authzTransMock.warn()).thenReturn(lt);
+// when(authzTransMock.info()).thenReturn(lt);
+// tallyHoMethod.invoke(aTF, authzTransMock);
+//
+// when(authzTransMock.getUserPrincipal()).thenReturn(tPrin);
+// tallyHoMethod.invoke(aTF, authzTransMock);
}
-
-
-
}
@Test
public void test() throws Exception {
- InetAddress ia = InetAddress.getLocalHost();
+// InetAddress ia = InetAddress.getLocalHost();
+ InetAddress ia = InetAddress.getByName("192.168.0.0");
NetMask mask = new NetMask(ia.getAddress());
assertTrue(mask.isInNet(ia.getAddress()));
<!-- SONAR -->
<!-- <sonar.skip>true</sonar.skip> -->
<jacoco.version>0.7.7.201606060606</jacoco.version>
- <sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version>
- <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
- <!-- Default Sonar configuration -->
- <sonar.jacoco.reportPaths>target/code-coverage/jacoco-ut.exec</sonar.jacoco.reportPaths>
- <sonar.jacoco.itReportPaths>target/code-coverage/jacoco-it.exec</sonar.jacoco.itReportPaths>
- <!-- Note: This list should match jacoco-maven-plugin's exclusion list below -->
- <sonar.exclusions>**/gen/**,**/generated-sources/**,**/yang-gen**,**/pax/**</sonar.exclusions>
+ <sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version>
+ <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
+ <!-- Default Sonar configuration -->
+ <sonar.jacoco.reportPaths>target/code-coverage/jacoco-ut.exec</sonar.jacoco.reportPaths>
+ <sonar.jacoco.itReportPaths>target/code-coverage/jacoco-it.exec</sonar.jacoco.itReportPaths>
+ <!-- Note: This list should match jacoco-maven-plugin's exclusion list below -->
+ <sonar.exclusions>**/gen/**,**/generated-sources/**,**/yang-gen**,**/pax/**</sonar.exclusions>
<nexusproxy>https://nexus.onap.org</nexusproxy>
<snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath>
<releaseNexusPath>/content/repositories/releases/</releaseNexusPath>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.jvnet.mock-javamail</groupId>
+ <artifactId>mock-javamail</artifactId>
+ <version>1.9</version>
+ </dependency>
</dependencies>
<build>
<configuration>
<dataFile>${project.build.directory}/code-coverage/jacoco-ut.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
+ <includes>
+ <include>**</include>
+ </includes>
</configuration>
</execution>
<execution>
</goals>
<configuration>
<destFile>${project.build.directory}/code-coverage/jacoco-it.exec</destFile>
+ <includes>
+ <include>**</include>
+ </includes>
<propertyName>failsafeArgLine</propertyName>
</configuration>
</execution>
* * Licensed 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.
******************************************************************************/
package org.onap.aaf.org;
-import java.io.File;
-import java.io.IOException;
+import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
final String domain;
final String atDomain;
final String realm;
-
+
private final String NAME,mailHost,mailFrom;
private final Set<String> supportedRealms;
+
public DefaultOrg(Env env, String realm) throws OrganizationException {
+
this.realm = realm;
supportedRealms=new HashSet<String>();
supportedRealms.add(realm);
if(mailFrom==null) {
throw new OrganizationException(s + PROPERTY_IS_REQUIRED);
}
-
+
System.getProperties().setProperty("mail.smtp.host",mailHost);
System.getProperties().setProperty("mail.user", mailFrom);
// Get the default Session object.
env.warn().log(defFile, " is not defined. Using default: ",temp+"/identities.dat");
File dir = new File(temp);
fIdentities=new File(dir,"identities.dat");
+
if(!fIdentities.exists()) {
env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating.");
if(!dir.exists()) {
}
}
}
-
+
if(fIdentities!=null && fIdentities.exists()) {
identities = new Identities(fIdentities);
} else {
throw new OrganizationException(e);
}
}
-
+
// Implement your own Delegation System
static final List<String> NULL_DELEGATES = new ArrayList<String>();
private Session session;
public enum Types {Employee, Contractor, Application, NotActive};
private final static Set<String> typeSet;
-
+
static {
typeSet = new HashSet<String>();
for(Types t : Types.values()) {
typeSet.add(t.name());
}
}
-
+
private static final EmailWarnings emailWarnings = new DefaultOrgWarnings();
@Override
@Override
public DefaultOrgIdentity getIdentity(AuthzTrans trans, String id) throws OrganizationException {
int at = id.indexOf('@');
+ String attt = at<0?id:id.substring(0, at);
return new DefaultOrgIdentity(trans,at<0?id:id.substring(0, at),this);
}
- // Note: Return a null if found; return a String Message explaining why not found.
+ // Note: Return a null if found; return a String Message explaining why not found.
@Override
public String isValidID(final AuthzTrans trans, final String id) {
try {
// if(!id.regionMatches(at+1, domain, 0, id.length()-at-1)) {
// return false;
// }
- sid = id.substring(0,at);
+ sid = id.substring(0,at);
} else {
sid = id;
}
// We'll validate that it exists, rather than check patterns.
-
+
return isValidID(trans, sid)==null;
// Check Pattern (if checking existing is too long)
// if(id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) {
// return true;
// }
- // return false;
+ // return false;
}
private static final String SPEC_CHARS = "!@#$%^*-+?/,:;.";
+ "Please follow this link: \n\n\t" + url
+ "\n\n" + summary, urgent);
} catch (Exception e) {
+
trans.error().log(e, "Failure to send Email");
return Response.ERR_NotificationFailure;
}
@Override
public int sendEmail(AuthzTrans trans, List<String> toList, List<String> ccList, String subject, String body,
Boolean urgent) throws OrganizationException {
+
int status = 1;
-
+
List<String> to = new ArrayList<String>();
for(String em : toList) {
if(em.indexOf('@')<0) {
to.add(em);
}
}
-
+
List<String> cc = new ArrayList<String>();
if(ccList!=null) {
if(!ccList.isEmpty()) {
-
+
for(String em : ccList) {
if(em.indexOf('@')<0) {
cc.add(new DefaultOrgIdentity(trans, em, this).email());
}
}
}
-
+
// for now, I want all emails so we can see what goes out. Remove later
if (!ccList.contains(mailFrom)) {
ccList.add(mailFrom);
// Now set the actual message
message.setText(body);
} else {
+
// override recipients
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailFrom));
status = 0;
} catch (MessagingException mex) {
+ System.out.println("Error messaging: "+ mex.getMessage());
+ System.out.println("Error messaging: "+ mex.toString());
throw new OrganizationException("Exception send email message "
+ mex.getMessage());
}
- return status;
+ return status;
}
/**
@Override
public GregorianCalendar expiration(GregorianCalendar gc, Expiration exp, String... extra) {
- GregorianCalendar now = new GregorianCalendar();
- GregorianCalendar rv = gc==null?now:(GregorianCalendar)gc.clone();
+ GregorianCalendar now = new GregorianCalendar();
+ GregorianCalendar rv = gc==null?now:(GregorianCalendar)gc.clone();
switch (exp) {
case ExtendPassword:
// Extending Password give 5 extra days, max 8 days from now
orgIdentitys.add(supervisor);
}
}
- return orgIdentitys;
+ return orgIdentitys;
}
@Override
@Override
public boolean canHaveMultipleCreds(String id) {
// External entities are likely mono-password... if you change it, it is a global change.
- // This is great for people, but horrible for Applications.
+ // This is great for people, but horrible for Applications.
//
// AAF's Password can have multiple Passwords, each with their own Expiration Date.
// For Default Org, we'll assume true for all, but when you add your external
}
}
return null;
-
+
case CREATE_MECHID_BY_PERM_ONLY:
return getName() + " only allows sponsors to create MechIDs";
-
+
default:
return policy.name() + " is unsupported at " + getName();
- }
+ }
}
@Override
return this.getAddresses(strAddress,";");
}
/**
- * Convert the delimiter String into Internet addresses with the
+ * Convert the delimiter String into Internet addresses with the
* delimiter of provided
- * @param strAddress
+ * @param strAddresses
* @param delimiter
* @return
*/
int count = 0;
for (String addr : strAddresses)
{
- try{
- addressArray[count] = new InternetAddress(addr);
- count++;
- }catch(Exception e){
- throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage());
- }
- }
- return addressArray;
+ try{
+ addressArray[count] = new InternetAddress(addr);
+ count++;
+ }catch(Exception e){
+ throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage());
+ }
+ }
+ return addressArray;
}
private String extractRealm(final String r) {
}
@Override
public boolean supportsRealm(final String r) {
- return supportedRealms.contains(extractRealm(r)) || r.endsWith(realm);
+ if(r.endsWith(realm)) {
+ return true;
+ } else {
+ String erealm = extractRealm(r);
+ for(String sr : supportedRealms) {
+ if(erealm.startsWith(sr)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
@Override
public synchronized void addSupportedRealm(final String r) {
supportedRealms.add(extractRealm(r));
}
-
+
}
private static final String CONTRACTOR = "c";
private static final String EMPLOYEE = "e";
private static final String APPLICATION = "a";
- private static final String NON_ACTIVE = "n";
+ private static final String NON_ACTIVE = "n";
private final static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF);
-
+
private DefaultOrg org;
//package on purpose
Data identity;
org.identities.open(trans, TIMEOUT);
try {
Reuse r = org.identities.reuse();
- int at = key.indexOf(dorg.atDomain);
+ int at = key.indexOf(dorg.getDomain());
String search;
if(at>=0) {
search = key.substring(0,at);
search = key;
}
identity = org.identities.find(search, r);
+
+
+
if(identity==null) {
identity = Identities.NO_DATA;
}
throw new OrganizationException(e);
}
}
-
+
@Override
public boolean equals(Object b) {
if(b instanceof DefaultOrgIdentity) {
public class DefaultOrgWarnings implements EmailWarnings {
@Override
- public long credEmailInterval()
- {
- return 604800000L; // 7 days in millis 1000 * 86400 * 7
- }
-
+ public long credEmailInterval()
+ {
+ return 604800000L; // 7 days in millis 1000 * 86400 * 7
+ }
+
@Override
- public long roleEmailInterval()
- {
- return 604800000L; // 7 days in millis 1000 * 86400 * 7
- }
-
+ public long roleEmailInterval()
+ {
+ return 604800000L; // 7 days in millis 1000 * 86400 * 7
+ }
+
@Override
public long apprEmailInterval() {
- return 259200000L; // 3 days in millis 1000 * 86400 * 3
+ return 259200000L; // 3 days in millis 1000 * 86400 * 3
}
-
+
@Override
- public long credExpirationWarning()
- {
- return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds
- }
-
+ public long credExpirationWarning()
+ {
+ return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds
+ }
+
@Override
- public long roleExpirationWarning()
- {
- return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds
- }
+ public long roleExpirationWarning()
+ {
+ return( 2592000000L ); // One month, in milliseconds 1000 * 86400 * 30 in milliseconds
+ }
@Override
- public long emailUrgentWarning()
- {
- return( 1209600000L ); // Two weeks, in milliseconds 1000 * 86400 * 14 in milliseconds
- }
+ public long emailUrgentWarning()
+ {
+ return( 1209600000L ); // Two weeks, in milliseconds 1000 * 86400 * 14 in milliseconds
+ }
}
*/
public class Identities extends AbsData {
public final static Data NO_DATA = new Data();
-
- public Identities(File users) {
+
+ public Identities(File users) throws IOException {
super(users,'|',512,0);
}
public final String email;
public final String status;
public final String responsibleTo;
-
+
private Data(Field f) {
f.reset();
id=f.next();
status=f.next();
responsibleTo =f.next();
}
-
+
private Data() {
id = name = fname = lname =
- phone = email = status = responsibleTo
+ phone = email = status = responsibleTo
= "";
}
status + '|' +
responsibleTo;
}
-
+
// Here, make up your own Methods which help you easily determine your Organization's structure
// in your Organization Object
- public boolean hasStatus(String possible) {
- return possible.contains(status);
- }
+ public boolean hasStatus(String possible) {
+ return possible.contains(status);
+ }
+
+ public boolean isEmployee() {
+ return "e".equals(status);
+ }
- public boolean isEmployee() {
- return "e".equals(status);
- }
-
- public boolean isContractor() {
- return "c".equals(status);
- }
-
- public boolean isApplication() {
- return "a".equals(status);
- }
+ public boolean isContractor() {
+ return "c".equals(status);
+ }
+
+ public boolean isApplication() {
+ return "a".equals(status);
+ }
}
-
- public Data find(Object key,Reuse r) throws IOException {
- r.reset();
- // These are new, to allow for Thread Safety
- int rec = ti.find(key,r,0);
- if(rec<0) {
- return null;
- }
- r.pos(rec);
+
+ public Data find(Object key,Reuse r) throws IOException {
+ r.reset();
+ // These are new, to allow for Thread Safety
+ int rec = ti.find(key,r,0);
+ if(rec<0) {
+ return null;
+ }
+ r.pos(rec);
return new Data(r.getFieldData());
- }
+ }
}
package org.onap.aaf.org.test;
import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
import java.io.File;
+import java.io.IOException;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Matchers;
import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.aaf.auth.env.AuthzEnv;
import org.onap.aaf.auth.env.AuthzTrans;
import org.onap.aaf.auth.org.OrganizationException;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.misc.env.Env;
+import org.onap.aaf.misc.env.LogTarget;
+import org.onap.aaf.misc.env.TimeTaken;
import org.onap.aaf.org.DefaultOrg;
-import org.powermock.api.mockito.PowerMockito;
+import org.onap.aaf.org.Identities;
import org.powermock.modules.junit4.PowerMockRunner;
+import org.onap.aaf.auth.local.AbsData.Reuse;
+
@RunWith(PowerMockRunner.class)
public class JU_DefaultOrg {
- DefaultOrg defaultOrg;
- //private DefaultOrg defaultOrgMock;
+
+ private DefaultOrg defaultOrg;
+
+
+ Identities.Data data;
+
@Mock
- AuthzEnv authzEnvMock;
+ Env envMock;
@Mock
AuthzTrans authzTransMock;
@Mock
- File fIdentitiesMock;
+ TimeTaken ttMock;
+
+ @Mock
+ LogTarget logTargetMock;
+
private static final String PROPERTY_IS_REQUIRED = " property is Required";
private static final String DOMAIN = "osaaf.com";
private static final String REALM = "com.osaaf";
private static final String NAME = "Default Organization";
private static final String NO_PASS = NAME + " does not support Passwords. Use AAF";
- String mailHost,mailFromUserId,supportAddress;
- private String SUFFIX;
- String s;
- String defFile;
- //@Before
+ private static final String URL = "www.deforg.com";
+ private static final String IDENT = "ccontra|iowna";
+ private static final String CCS = "mmanager|bdevl";
+ String mailHost,mailFromUserId,summary,supportAddress;
+
+ private final static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF);
+
+
+
+ @Before
public void setUp() throws OrganizationException{
- MockitoAnnotations.initMocks(this);
- PowerMockito.when(authzEnvMock.getProperty(s=(REALM + ".mailHost"), null)).thenReturn("hello");
- PowerMockito.when(authzEnvMock.getProperty(s=(REALM + ".supportEmail"), null)).thenReturn("notnull");
- PowerMockito.when(authzEnvMock.getProperty(Matchers.anyString())).thenReturn("src" + File.separator + "test" + File.separator + "resources" + File.separator + "test.txt");
- PowerMockito.when(fIdentitiesMock.exists()).thenReturn(true);
- //PowerMockito.when((fIdentitiesMock!=null && fIdentitiesMock.exists())).thenReturn(true);
- defaultOrg = new DefaultOrg(authzEnvMock, REALM);
+
+ mailFromUserId = "frommail";
+ mailHost = "hostmail";
+ File file = new File("src/test/resources/");
+ when(envMock.getProperty(REALM + ".name","Default Organization")).thenReturn(NAME);
+ when(envMock.getProperty(REALM + ".mailHost",null)).thenReturn(mailHost);
+ when(envMock.getProperty(REALM + ".mailFrom",null)).thenReturn(mailFromUserId);
+ when(envMock.getProperty("aaf_data_dir")).thenReturn(file.getAbsolutePath());
+ when(envMock.warn()).thenReturn(logTargetMock);
+ when(authzTransMock.warn()).thenReturn(logTargetMock);
+ when(authzTransMock.start(any(String.class),any(Integer.class))).thenReturn(ttMock);
+ when(authzTransMock.error()).thenReturn(logTargetMock);
+ when(authzTransMock.getProperty("CASS_ENV", "")).thenReturn("Cassandra env");
+
+ defaultOrg = new DefaultOrg(envMock, REALM);
+
}
- //@Test //(expected=OrganizationException.class)
- public void test() throws OrganizationException{
- //PowerMockito.when(authzEnvMock.getProperty(Matchers.anyString())).thenReturn(" ");
- //defaultOrg = new DefaultOrg(authzEnvMock);
+ @Test
+ public void testDefOrg_returnDataIdentityNotNull() throws OrganizationException {
+
+
+ try {
+ defaultOrg.identities.open(authzTransMock, TIMEOUT);
+ try {
+ Reuse r = defaultOrg.identities.reuse();
+ data = defaultOrg.identities.find("iowna", defaultOrg.identities.reuse());
+ System.out.println("here is identities data: "+ data.toString());
+
+ } finally {
+ defaultOrg.identities.close(authzTransMock);
+ }
+ } catch (IOException e) {
+ throw new OrganizationException(e);
+ }
+
+
+ assertTrue(data.toString() != null);
+
+ }
+
+
+
+ @Test
+ public void testDefOrg_returnDefOrgEntity() {
+
+
assertTrue(defaultOrg != null);
+
}
+ @Test
+ public void testDefOrgNotifyApproval_returnResponseOK() {
+
+ summary = "Approval";
+ Boolean urgent = false;
+ DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.Approval, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent);
+ assertEquals(response.name(), "OK");
+
+ }
+
+
+ @Test
+ public void testDefOrgNotifyPasswordExpiration_returnResponseOK() {
+
+ summary = "PasswordExpiration";
+ Boolean urgent = false;
+ DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.PasswordExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent);
+ assertEquals(response.name(), "OK");
+
+ }
+
+ @Test
+ public void testDefOrgNotifyRoleExpiration_returnResponseOK() {
+
+ summary = "RoleExpiration";
+ Boolean urgent = false;
+ DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent);
+ assertEquals(response.name(), "OK");
+ }
+
+ @Test
+ public void testDefOrgNotifyRoleExpirationUrgent_returnResponseOK() {
+
+ summary = "RoleExpirationUrgent";
+ Boolean urgent = true;
+ when(authzTransMock.info()).thenReturn(logTargetMock);
+ DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent);
+ assertEquals(response.name(), "OK");
+
+ }
+
+ @Test
+ public void testDefOrgNotifyModeTest_returnResponseOK() {
+
+ summary = "ModeTest";
+ Boolean urgent = false;
+ when(authzTransMock.info()).thenReturn(logTargetMock);
+ defaultOrg.setTestMode(true);
+ DefaultOrg.Response response = defaultOrg.notify(authzTransMock, DefaultOrg.Notify.RoleExpiration, URL, IDENT.split("\\|"), CCS.split("\\|"), summary, urgent);
+ assertEquals(response.name(), "OK");
+
+ }
+
+
+
+
+
//@Test //(expected=OrganizationException.class)
public void testMultipleCreds() throws OrganizationException{
String id = "test";
- //PowerMockito.when(authzEnvMock.getProperty(Matchers.anyString())).thenReturn(" ");
- //defaultOrg = new DefaultOrg(authzEnvMock);
boolean canHaveMultipleCreds;
canHaveMultipleCreds = defaultOrg.canHaveMultipleCreds(id );
System.out.println("value of canHaveMultipleCreds: " + canHaveMultipleCreds);
}
- //@Test
+ //@Test
public void testGetIdentityTypes() throws OrganizationException{
Set<String> identityTypes = defaultOrg.getIdentityTypes();
System.out.println("value of IdentityTypes: " + identityTypes);
}
- //@Test
+ //@Test
public void testGetRealm() throws OrganizationException{
String realmTest = defaultOrg.getRealm();
System.out.println("value of realm: " + realmTest);
defaultOrg.addSupportedRealm(otherRealm);
assertTrue(defaultOrg.supportsRealm(otherRealm));
}
- //@Test
+ //@Test
public void testGetName() throws OrganizationException{
String testName = defaultOrg.getName();
System.out.println("value of name: " + testName);
}
- //@Test
+ //@Test
public void testGetDomain() throws OrganizationException{
String testDomain = defaultOrg.getDomain();
System.out.println("value of domain: " + testDomain);
}
// @Test
- // public void testIsValidID(){
+ // public void testIsValidID(){
// String Result = defaultOrg.isValidID(Matchers.anyString());
// System.out.println("value of res " +Result);
- // assertNotNull(Result);
+ // assertNotNull(Result);
// }
//@Test
******************************************************************************/
package org.onap.aaf.org.test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.local.AbsData.Reuse;
import org.onap.aaf.auth.org.OrganizationException;
-import org.onap.aaf.auth.org.Organization.Identity;
import org.onap.aaf.org.DefaultOrg;
import org.onap.aaf.org.DefaultOrgIdentity;
+import org.onap.aaf.org.Identities;
import org.onap.aaf.org.Identities.Data;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
+import static org.mockito.Mockito.*;
+import java.io.IOException;
@RunWith(PowerMockRunner.class)
public class JU_DefaultOrgIdentity {
- private DefaultOrgIdentity defaultOrgIdentity;
- private DefaultOrgIdentity defaultOrgIdentityMock;
-
+ private DefaultOrg defaultOrgMock;
+
@Mock
- AuthzTrans authzTransMock;
-
- String key="key";
-
+ private Reuse rMock;
+
@Mock
- private DefaultOrg defaultOrgMock;
+ AuthzTrans authzTransMock;
+
@Mock
private Data dataMock;
+
@Mock
- private Identity identityMock;
-
+ private DefaultOrgIdentity defaultOrgIdentity;
+
+ static String key = "iowna@deforg";
+ static String orgDomain = "@deforg";
+
@Before
- public void setUp() throws OrganizationException{
+ public void setUp() throws IOException, OrganizationException {
MockitoAnnotations.initMocks(this);
- defaultOrgIdentityMock = PowerMockito.mock(DefaultOrgIdentity.class);
+ defaultOrgMock = PowerMockito.mock(DefaultOrg.class);
+ defaultOrgMock.identities = mock(Identities.class);
+
+
+ authzTransMock = PowerMockito.mock(AuthzTrans.class);
+
+ when(defaultOrgMock.getDomain()).thenReturn(orgDomain);
+ when(defaultOrgMock.identities.reuse()).thenReturn(rMock);
+ when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(dataMock);
+
+ defaultOrgIdentity = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock);
+
+ }
+
+
+ @Test
+ public void testIdentify_returnIdentifiedEntity() {
+
+ assertTrue(defaultOrgIdentity.id() != null);
+
+ }
+
+ @Test
+ public void testIdentify_returnIdentifiedEntityWithDataNull() throws IOException, OrganizationException {
+
+ when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(null);
+
+ DefaultOrgIdentity defaultOrgIdentityDataNull = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock);
+ assertTrue(defaultOrgIdentityDataNull.id() != null);
+
+ }
+
+ @Test(expected = OrganizationException.class)
+ public void testIdentify_returnThrowIOException() throws OrganizationException {
+
+ when(defaultOrgMock.getDomain()).thenReturn(orgDomain);
+ when(defaultOrgMock.identities.reuse()).thenThrow(IOException.class);
+ DefaultOrgIdentity defaultOrgIdentityException = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock);
+
}
-
+
+
@Test
- public void testEquals(){
- Object b = null;
- Boolean res = defaultOrgIdentityMock.equals(b);
- System.out.println("value of res " +res);
+ public void testEquals_returnTrue() {
+
+ Object b = defaultOrgIdentity;
+ assertTrue(defaultOrgIdentity.equals(b) == true );
}
-
-
+
@Test
- public void testIsFound(){
- defaultOrgIdentityMock.isFound();
- System.out.println("value of found " +defaultOrgIdentityMock.isFound());
- assertFalse(defaultOrgIdentityMock.isFound());
+ public void testStatus_returnUnknown() {
+
+ assertEquals(defaultOrgIdentity.type(), "Unknown");
+
}
-
+
@Test
- public void testIsResponsible(){
- defaultOrgIdentityMock.mayOwn();
- System.out.println("value of res " +defaultOrgIdentityMock.mayOwn());
- assertNull(defaultOrgIdentityMock.mayOwn());
+ public void testHash_returnHashCode() {
+
+ assertTrue(defaultOrgIdentity.hashCode() != 0 );
+
}
-
+
@Test
- public void testFullName(){
- String fullName = defaultOrgIdentityMock.fullName();
- System.out.println("value of fullname " +fullName);
- assertTrue(fullName == null);
+ public void testFullId_returnFullId() throws IOException, OrganizationException{
+ String key="toto@deforg";
+ String orgDomain="@deforg";
+ when(defaultOrgMock.getDomain()).thenReturn(orgDomain);
+ when(defaultOrgMock.identities.reuse()).thenReturn(rMock);
+ when(defaultOrgMock.identities.find(eq(key),any(Reuse.class))).thenReturn(dataMock);
+ defaultOrgIdentity = new DefaultOrgIdentity(authzTransMock, key, defaultOrgMock);
+
+ assertTrue(defaultOrgIdentity.fullID().contains("@") );
}
-
-
+
+ @Test
+ public void testEmail_returnEmail() {
+
+ assertTrue(defaultOrgIdentity.email() != null );
+ }
+
+
+ @Test
+ public void testFullName_returnFullName() {
+
+ assertTrue(defaultOrgIdentity.fullName() != null );
+ }
+
+
+ @Test
+ public void testFirstName_returnFirstName() {
+
+ assertTrue(defaultOrgIdentity.firstName() != null );
+ }
+
+
+
+
}
@RunWith(PowerMockRunner.class)
public class JU_DefaultOrgWarnings {
-
+
private DefaultOrgWarnings defaultOrgWarningsMock;
private DefaultOrgWarnings defaultOrgWarnings;
-
-
+
+
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
-
+
defaultOrgWarningsMock = PowerMockito.mock(DefaultOrgWarnings.class);
-
+
defaultOrgWarnings = new DefaultOrgWarnings();
}
-
+
@Test
public void testApprEmailInterval() {
-
+
assertEquals(259200000, defaultOrgWarnings.apprEmailInterval() );
}
-
+
@Test
public void testCredEmailInterval() {
assertEquals(604800000, defaultOrgWarnings.credEmailInterval());
-
+
}
-
+
@Test
public void testCredExpirationWarning() {
assertEquals(2592000000L, defaultOrgWarnings.credExpirationWarning());
}
-
+
@Test
public void testEmailUrgentWarning() {
assertEquals(1209600000L, defaultOrgWarnings.emailUrgentWarning());
}
-
+
@Test
public void testRoleEmailInterval() {
assertEquals(604800000L, defaultOrgWarnings.roleEmailInterval());
}
-
+
@Test
public void testRoleExpirationWarning() {
assertEquals(2592000000L, defaultOrgWarnings.roleExpirationWarning());
--- /dev/null
+iowna|Ima D. Owner|Ima|Owner|314-123-2000|ima.d.owner@osaaf.com|e|
+mmanager|Mark D. Manager|Mark|Manager|314-123-1234|mark.d.manager@osaaf.com|e|iowna
+bdevl|Robert D. Developer|Bob|Developer|314-123-1235|bob.d.develper@osaaf.com|e|mmanager
+mmarket|Mary D. Marketer|Mary|Marketer|314-123-1236|mary.d.marketer@osaaf.com|e|mmanager
+ccontra|Clarice D. Contractor|Clarice|Contractor|314-123-1237|clarice.d.contractor@osaaf.com|c|mmanager
+iretired|Ira Lee M. Retired|Ira|Retired|314-123-1238|clarice.d.contractor@osaaf.com|n|mmanager
+osaaf|ID of AAF|||||a|bdevl
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.auth.fs.test;
+
+import static org.junit.Assert.*;
+
+import org.onap.aaf.auth.env.AuthzEnv;
+import org.onap.aaf.auth.env.AuthzTrans;
+import org.onap.aaf.auth.fs.AAF_FS;
+import org.onap.aaf.auth.rserv.CachingFileAccess;
+import org.onap.aaf.auth.server.JettyServiceStarter;
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.misc.env.Slot;
+import org.onap.aaf.misc.env.StaticSlot;
+import org.eclipse.jetty.server.Server;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import org.junit.Test;
+
+public class JU_AAF_FS {
+ AuthzEnv aEnv;
+ AAF_FS aafFs;
+ File fService;
+ File fEtc;
+ String value;
+ File d;
+ private static final String testDir = "src/test/resources/logs";
+ private ByteArrayOutputStream outStream;
+ private ByteArrayOutputStream errStream;
+
+
+ @Before
+ public void setUp() throws APIException, IOException, CadiException {
+ outStream = new ByteArrayOutputStream();
+ errStream = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outStream));
+ System.setErr(new PrintStream(errStream));
+ value = System.setProperty(Config.CADI_LOGDIR, testDir);
+ System.setProperty(Config.CADI_ETCDIR, testDir);
+ System.out.println(ClassLoader.getSystemResource("org.osaaf.log4j.props"));
+ d = new File(testDir);
+ d.mkdirs();
+ fService = new File(d +"/fs-serviceTEST.log");
+ fService.createNewFile();
+ fEtc = new File(d + "/org.osaaf.log4j.props");
+ fEtc.createNewFile();
+
+ aEnv = new AuthzEnv();
+ aEnv.staticSlot("test");
+ aEnv.access().setProperty("aaf_public_dir", "test");
+ aEnv.access().setProperty(Config.AAF_COMPONENT, "aaf_com:1.1");
+ Server serverMock = mock(Server.class);
+ JettyServiceStarter<AuthzEnv,AuthzTrans> jssMock = mock(JettyServiceStarter.class);
+ aafFs = new AAF_FS(aEnv);
+ aEnv.access().setProperty(Config.AAF_LOCATE_URL, "aaf_loc:ate.url");
+ aafFs = new AAF_FS(aEnv);
+ }
+
+ @Test
+ public void testRegistrants() throws CadiException, LocatorException {
+ int port = 8008;
+ aEnv.access().setProperty(Config.AAF_URL, "www.google.com");
+ aEnv.access().setProperty(Config.CADI_LATITUDE, "38.550674");
+ aEnv.access().setProperty(Config.CADI_LONGITUDE, "-90.146942");
+ aEnv.access().setProperty(Config.AAF_LOCATE_URL, "testLocateUrl");
+ aEnv.access().setProperty(Config.HOSTNAME, "testHost");
+
+ aafFs.registrants(port);
+ }
+
+ @Test
+ public void testFilters() throws CadiException, LocatorException {
+ aafFs.filters();
+ }
+
+ @Test
+ public void testMain() {
+ System.setProperty("cadi_exitOnFailure", "false");
+
+ String[] strArr = {"aaf_component=aaf_com:po.nent"};
+ try {
+ //AAF_FS.main(strArr); //Timeout caused in Jenkins but not in local
+ } catch(Exception e) {
+ //Failure expected until we understand how code is.
+ }
+ }
+
+ @After
+ public void cleanUp() {
+ for(File f : d.listFiles()) {
+ f.delete();
+ }
+ d.delete();
+ System.setErr(System.err);
+ System.setOut(System.out);
+ }
+
+}
sTheme = env.staticSlot(CachingFileAccess.CFA_WEB_PATH,access.getProperty(CachingFileAccess.CFA_WEB_PATH,null)==null?AAF_GUI_THEME:CachingFileAccess.CFA_WEB_PATH);
theme = env.getProperty(AAF_GUI_THEME);
- //OrganizationFactory.setDefaultOrg(env, "org.osaaf.authz.org.att.ATT");
-
slot_httpServletRequest = env.slot(HTTP_SERVLET_REQUEST);
String[] component = Split.split(':', access.getProperty(Config.AAF_COMPONENT, "N/A:2.x"));
if(component.length>1) {
<dependency>
<groupId>org.onap.aaf.authz</groupId>
<artifactId>aaf-auth-core</artifactId>
- <version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onap.aaf.authz</groupId>
<artifactId>aaf-cadi-aaf</artifactId>
- <version>${project.version}</version>
</dependency>
</dependencies>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
- <version>1.6.7</version>
<extensions>true</extensions>
<configuration>
<nexusUrl>${nexusproxy}</nexusUrl>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
- <version>${jacoco.version}</version>
<configuration>
<excludes>
<exclude>**/gen/**</exclude>
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+package org.onap.aaf.auth.locate;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.mockito.Mockito.verify;\r
+import static org.mockito.Mockito.when;\r
+import static org.mockito.MockitoAnnotations.initMocks;\r
+\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.eclipse.jetty.http.HttpStatus;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.mockito.Answers;\r
+import org.mockito.Mock;\r
+import org.onap.aaf.auth.env.AuthzTrans;\r
+import org.onap.aaf.auth.locate.facade.LocateFacade;\r
+import org.onap.aaf.cadi.aaf.v2_0.AAFAuthn;\r
+import org.onap.aaf.cadi.principal.BasicPrincipal;\r
+import org.onap.aaf.cadi.principal.X509Principal;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+\r
+public class JU_BasicAuthCodeTest {\r
+\r
+ @Mock\r
+ AAFAuthn authn;\r
+\r
+ @Mock(answer = Answers.RETURNS_DEEP_STUBS)\r
+ AuthzTrans trans;\r
+\r
+ @Mock\r
+ HttpServletRequest req;\r
+\r
+ @Mock\r
+ HttpServletResponse resp;\r
+\r
+ @Mock\r
+ LogTarget error;\r
+\r
+ @Mock\r
+ LocateFacade facade;\r
+\r
+ @Mock\r
+ BasicPrincipal basicPrincipal;\r
+ @Mock\r
+ X509Principal x509Principal;\r
+\r
+ @Before\r
+ public void setUp() throws Exception {\r
+ initMocks(this);\r
+ }\r
+\r
+ @Test\r
+ public void testWithNullUserPrincipal() throws Exception {\r
+ BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);\r
+ LocateCode locateCode = basicAuthCode.clone(facade, false);\r
+\r
+ assertEquals(locateCode.desc(), basicAuthCode.desc());\r
+\r
+ when(trans.getUserPrincipal()).thenReturn(null);\r
+ when(trans.error()).thenReturn(error);\r
+\r
+ basicAuthCode.handle(trans, req, resp);\r
+ }\r
+\r
+ @Test\r
+ public void testWithBasicUserPrincipal() throws Exception {\r
+ BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);\r
+ LocateCode locateCode = basicAuthCode.clone(facade, false);\r
+\r
+ assertEquals(locateCode.desc(), basicAuthCode.desc());\r
+\r
+ when(trans.getUserPrincipal()).thenReturn(basicPrincipal);\r
+\r
+ basicAuthCode.handle(trans, req, resp);\r
+\r
+ verify(resp).setStatus(HttpStatus.OK_200);\r
+ }\r
+\r
+ @Test\r
+ public void testWithX509UserPrincipal() throws Exception {\r
+ BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);\r
+ LocateCode locateCode = basicAuthCode.clone(facade, false);\r
+\r
+ assertEquals(locateCode.desc(), basicAuthCode.desc());\r
+\r
+ when(trans.getUserPrincipal()).thenReturn(x509Principal);\r
+ when(req.getHeader("Authorization")).thenReturn("Basic 76//76");\r
+\r
+ basicAuthCode.handle(trans, req, resp);\r
+\r
+ verify(resp).setStatus(HttpStatus.FORBIDDEN_403);\r
+ }\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+package org.onap.aaf.auth.locate.mapper;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.onap.aaf.auth.locate.mapper.Mapper.API;\r
+\r
+import locate.v1_0.Endpoints;\r
+import locate.v1_0.MgmtEndpoints;\r
+import locate_local.v1_0.Error;\r
+import locate_local.v1_0.InRequest;\r
+import locate_local.v1_0.Out;\r
+\r
+public class JU_Mapper_1_0Test {\r
+\r
+ @Before\r
+ public void setUp() throws Exception {\r
+\r
+ }\r
+\r
+ @Test\r
+ public void testGetClasses() {\r
+ Mapper_1_0 mapper = new Mapper_1_0();\r
+ assertEquals(InRequest.class, mapper.getClass(API.IN_REQ));\r
+ assertEquals(Out.class, mapper.getClass(API.OUT));\r
+ assertEquals(Error.class, mapper.getClass(API.ERROR));\r
+ assertEquals(Void.class, mapper.getClass(API.VOID));\r
+ assertEquals(Endpoints.class, mapper.getClass(API.ENDPOINTS));\r
+ assertEquals(MgmtEndpoints.class, mapper.getClass(API.MGMT_ENDPOINTS));\r
+ }\r
+\r
+ @Test\r
+ public void testNewInstance() {\r
+ Mapper_1_0 mapper = new Mapper_1_0();\r
+ assertTrue(mapper.newInstance(API.IN_REQ) instanceof InRequest);\r
+ assertTrue(mapper.newInstance(API.OUT) instanceof Out);\r
+ assertTrue(mapper.newInstance(API.ERROR) instanceof Error);\r
+ assertTrue(mapper.newInstance(API.ENDPOINTS) instanceof Endpoints);\r
+ assertTrue(mapper.newInstance(API.MGMT_ENDPOINTS) instanceof MgmtEndpoints);\r
+ assertEquals(null, mapper.newInstance(API.VOID));\r
+ }\r
+\r
+}\r
@Override
public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) {
final Validator v = new ServiceValidator();
- if(v.permType(type,null)
+ if(v.permType(type)
.permInstance(instance)
.permAction(action)
.err()) {
private final static String PERM_DB_POOL_CLEAR=Define.ROOT_NS()+".db|pool|clear";
private final static String PERM_DENY_IP = Define.ROOT_NS()+".deny|" + Define.ROOT_COMPANY() + "|ip";
private final static String PERM_DENY_ID = Define.ROOT_NS()+".deny|" + Define.ROOT_COMPANY() + "|id";
- private final static String PERM_LOG_ID = Define.ROOT_NS()+".deny|" + Define.ROOT_COMPANY() + "|id";
+ private final static String PERM_LOG_ID = Define.ROOT_NS()+".log|" + Define.ROOT_COMPANY() + "|id";
/**
* Normal Init level APIs
assertTrue(validator.errs().equals("ERR_Security\n"));
}
+
+ @Test
+ public void permInstance() {
+ assertFalse(validator.permInstance("hello").err());
+ assertFalse(validator.permInstance("hello32").err());
+ assertFalse(validator.permInstance("hello-32").err());
+ assertFalse(validator.permInstance(":asdf:*:sdf*:sdk").err());
+ assertFalse(validator.permInstance(":asdf:*:sdf*:sdk*").err());
+ // Perms may not end in ":"
+ assertTrue(validator.permInstance(":").err());
+ assertTrue(validator.permInstance(":hello:").err());
+ }
@Test
public void permOkNull() {
+#!/bin/bash
docker exec -it aaf_$1 bash
-#!/bin/bash dbuild.sh
+#!/bin/bash
#
# Docker Building Script. Reads all the components generated by install, on per-version basis
#
-#!/bin/bash dclean.sh
+#!/bin/bash
# Pull in Variables from d.props
. ./d.props
-#
+#!/bin/bash
# Docker push Script. Reads all the components generated by install, on per-version basis
#
# Pull in Variables from d.props
-#!/bin/bash drun.sh
+#!/bin/bash
# Pull in Variables from d.props
. ./d.props
-#!/bin/bash dstop.sh
+#!/bin/bash
# Pull in Props
. ./d.props
-#!/bin/bash dstop.sh
+#!/bin/bash
# Pull in Properties
. ./d.props
#
-# Identities.dat
+# Sample Identities.dat
# This file is for use with the "Default Organization". It is a simple mechanism to have a basic ILM structure to use with
# out-of-the-box tire-kicking, or even for Small companies
#
# 5 - official email
# 6 - employment status e=employee, c=contractor, a=application, n=no longer with company
# 7 - responsible to (i.e Supervisor for People, or AppOwner, if it's an App ID)
-jonathan|Jonathan C Gathman|Jonathan|Gathman|314-550-3312|jonathan.gathman@att.com|e|
-clefevre|Catherine LeFevre|Catherine|LeFevre||catherine.lefevre@att.com|e|
-ramkoya|Ram Koya|Ram|Koya||ram.koya@att.com|e|clefevre
-chris|Chris Varner|Chris|Varner|469-375-0774|chris.varner@att.com|c|anne
-ian|Ian Howell|Ian|Howell|314-450-2782|ian.howell@att.com|e|jonathan
-gabe|Gabe B Maurer|Gabe|Maurer|314-962-9579|gabe.maurer@att.com|e|jonathan
-sai|Sai Gandham|Sai|Gandham|424-265-9959|sai.gandham@att.com|c|anne
-anne|Anne E Kopp|Anne|Kopp|512-244-4280|anne.e.kopp@att.com|e|jonathan
-aaf|AAF App|AAF|Application||DL-aaf-support@att.com|a|jonathan
-a2345z|AAF App|AAF|Application||DL-aaf-support@att.com|a|jonathan
-aaf_authz|AAF App|AAF|Application||jonathan.gathman@att.com|a|jonathan
-kirankamieni|Kiran K Kamineni|Kiran|Kamineni|999-999=9999|kiran.k.kamineni@intel.com|ramkoya
-aaf_sms|Secret Management Service|SMS|Secret Management Service provides secure storage for sensitive information such as passwords and userIDs||kiran.k.kamineni@intel.com|a|kirankamieni
-djtimoney|Dan Timoney|Dan|Timoney|+1 (732) 420-3226|dt5972@att.com|e|ramkoya
-xuegao|Xue Gao|Xue|Gao|0032479670327|xg353y@att.com|e|clefevre
-clamp|Clamp Application|clamp|Application||xg353y@att.com|a|xuegao
-dmaapbc|DMaap Bus Controller|DMaap|Bus Controller||dgl@research.att.com|a|dgfromatt
-dglfromatt|Dominic Lunanuova|Dominic|Lunanuova|732-420-9618|dgl@research.att.com|e|ramokoya
-puthenpura|Sarat Puthenpura|Sarat|Puthenpura|||e|clefevre
-ruoyu|Ruoyu Ying|Ruoyu|Ying|13661960772|ruoyu.ying@intel.com|e|puthenpura
+#
+
+iowna|Ima D. Owner|Ima|Owner|314-123-2000|ima.d.owner@osaaf.com|e|
+mmanager|Mark D. Manager|Mark|Manager|314-123-1234|mark.d.manager@osaaf.com|e|iowna
+bdevl|Robert D. Developer|Bob|Developer|314-123-1235|bob.d.develper@osaaf.com|e|mmanager
+mmarket|Mary D. Marketer|Mary|Marketer|314-123-1236|mary.d.marketer@osaaf.com|e|mmanager
+ccontra|Clarice D. Contractor|Clarice|Contractor|314-123-1237|clarice.d.contractor@osaaf.com|c|mmanager
+iretired|Ira Lee M. Retired|Ira|Retired|314-123-1238|clarice.d.contractor@osaaf.com|n|mmanager
+osaaf|ID of AAF|||||a|bdevl
+# ONAP default Users
+demo|PORTAL DEMO|PORTAL|DEMO|||e|mmanager
+jh0003|PORTAL ADMIN|PORTAL|ADMIN|||e|mmanager
+cs0008|PORTAL DESIGNER|PORTAL|DESIGNER|||e|mmanager
+jm0007|PORTAL TESTER|PORTAL|TESTER|||e|mmanager
+op0001|PORTAL OPS|PORTAL|OPS|||e|mmanager
+gv0001|PORTAL GOVERNOR|PORTAL|GOVERNOR|||e|mmanager
+
ccontra|Clarice D. Contractor|Clarice|Contractor|314-123-1237|clarice.d.contractor@osaaf.com|c|mmanager
iretired|Ira Lee M. Retired|Ira|Retired|314-123-1238|clarice.d.contractor@osaaf.com|n|mmanager
osaaf|ID of AAF|||||a|bdevl
+# ONAP default Users
+demo|PORTAL DEMO|PORTAL|DEMO|||e|mmanager
+jh0003|PORTAL ADMIN|PORTAL|ADMIN|||e|mmanager
+cs0008|PORTAL DESIGNER|PORTAL|DESIGNER|||e|mmanager
+jm0007|PORTAL TESTER|PORTAL|TESTER|||e|mmanager
+op0001|PORTAL OPS|PORTAL|OPS|||e|mmanager
+gv0001|PORTAL GOVERNOR|PORTAL|GOVERNOR|||e|mmanager
+
+
cadi_x509_issuers=CN=intermediateCA_1, OU=OSAAF, O=ONAP, C=US
cadi_keyfile=/opt/app/osaaf/local/org.osaaf.aaf.keyfile
cadi_keystore=/opt/app/osaaf/local/org.osaaf.aaf.p12
-cadi_keystore_password=enc:4L1xY_7mYTuk57SPWZetza5WlgBUYBe8pbT1-AWKO1-5PAbSTynQEc5TU7ZeomfN
+cadi_keystore_password=enc:3O7HDzEzdYatFYb83-jV69MNzN8qIW975SS70qCs7xri0b1n4r5viHo1lrM6K8om
#cadi_key_password=enc:<KEY PASSWORD (optional if the same as KEYSTORE PASSWORD)>
-cadi_alias=aaf@aaf.osaaf.org
+cadi_alias=aaf-authz@aaf.osaaf.org
cadi_truststore=/opt/app/osaaf/local/org.osaaf.aaf.trust.p12
cadi_truststore_password=enc:5nzj6v3Rb0oZPV1zCxg8EJFfkFvWFGJflLB0i_FN0Np
* If you want a simple field comparison, it is faster without REGEX
*/
public boolean match(Permission p) {
- boolean rv;
String aafType;
String aafInstance;
String aafAction;
int slash = aaf_locator_host.lastIndexOf("//");
host = aaf_locator_host.substring(slash+2);
}
- client = new HClient(ss, new URI(
- locatorURI.getScheme(),
- locatorURI.getUserInfo(),
- host,
- locatorURI.getPort(),
- "/locate/"+name + '/' + version,
- null,
- null
- ), connectTimeout);
+ URI uri = new URI(
+ locatorURI.getScheme(),
+ locatorURI.getUserInfo(),
+ host,
+ locatorURI.getPort(),
+ "/locate/"+name + '/' + version,
+ null,
+ null
+ );
+ client = createClient(ss, uri, connectTimeout);
} else {
client = new HClient(ss, locatorURI, connectTimeout);
}
protected URI getURI() {
return client.getURI();
}
+
+ protected HClient createClient(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout) throws LocatorException {
+ return new HClient(ss, uri, connectTimeout);
+ }
}
*
*/
public class AAFLurPerm extends AbsAAFLur<AAFPermission> {
+ private static final String ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR = "org.osaaf.cadi.oauth.OAuth2Lur";
+
/**
* Need to be able to transmutate a Principal into either ATTUID or MechID, which are the only ones accepted at this
* point by AAF. There is no "domain", aka, no "@att.com" in "ab1234@att.com".
Constructor<?> tmconst = tmcls.getConstructor(AAFCon.class,String.class);
Object tokMangr = tmconst.newInstance(con,oauth2_url);
@SuppressWarnings("unchecked")
- Class<Lur> oa2cls = (Class<Lur>)Config.loadClass(access,"org.osaaf.cadi.oauth.OAuth2Lur");
+ Class<Lur> oa2cls = (Class<Lur>)Config.loadClass(access,ORG_OSAAF_CADI_OAUTH_O_AUTH2_LUR);
Constructor<Lur> oa2const = oa2cls.getConstructor(tmcls);
Lur oa2 = oa2const.newInstance(tokMangr);
setPreemptiveLur(oa2);
* Licensed 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.
private Lur lur;
/**
- *
+ *
* Instance will be replaced by Identity
- * @param lur
- *
+ * @param lur
+ *
* @param tag
* @param perm
*/
@Override
public TafResp mayTrust(TafResp tresp, HttpServletRequest req) {
String user_info = req.getHeader(tag);
- if(user_info !=null ) {
- String[] info = Split.split(',', user_info);
- if(info.length>0) {
- String[] flds = Split.splitTrim(':',info[0]);
- if(flds.length>3 && "AS".equals(flds[3])) { // is it set for "AS"
- String pn = tresp.getPrincipal().getName();
- if(pn.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept
- || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM
- return new TrustTafResp(tresp,
- new TrustPrincipal(tresp.getPrincipal(), flds[0]),
- " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ','
- );
- } else if(pn.equals(flds[0])) { // Ignore if same identity
- return tresp;
- } else {
- return new TrustNotTafResp(tresp, tresp.getPrincipal().getName() + " requested trust as "
- + flds[0] + ", but does not have Authorization");
- }
- }
- }
+ if (user_info == null) {
+ return tresp;
+ }
+
+ String[] info = Split.split(',', user_info);
+ String[] flds = Split.splitTrim(':', info[0]);
+ if (flds.length < 4) {
+ return tresp;
+ }
+ if (!("AS".equals(flds[3]))) { // is it set for "AS"
+ return tresp;
+ }
+
+ String principalName = tresp.getPrincipal().getName();
+ if(principalName.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept
+ || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM
+ String desc = " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ',';
+ return new TrustTafResp(tresp, new TrustPrincipal(tresp.getPrincipal(), flds[0]), desc);
+ } else if(principalName.equals(flds[0])) { // Ignore if same identity
+ return tresp;
+ } else {
+ String desc = tresp.getPrincipal().getName() + " requested trust as " + flds[0] + ", but does not have Authorization";
+ return new TrustNotTafResp(tresp, desc);
}
- return tresp;
}
}
\ No newline at end of file
this.version = Config.AAF_DEFAULT_VERSION;
} else {
String[] split = Split.split(':', name);
-
- switch(split.length) {
- case 1:
- this.name = split[0];
- this.version = Config.AAF_DEFAULT_VERSION;
- break;
- case 0:
- this.name = name;
- this.version = Config.AAF_DEFAULT_VERSION;
- break;
- default:
- this.version = split[1];
- this.name = split[0];
-
- }
+ this.name = split[0];
+ this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION;
}
}
if(key.startsWith("http")) {
if(name!=null) {
if(locatorCreator != null) {
- if(name!=null) {
- AbsAAFLocator<?> aal = locatorCreator.create(name, version);
- if(pathInfo!=null) {
- aal.setPathInfo(pathInfo);
- }
- return aal;
+ AbsAAFLocator<?> aal = locatorCreator.create(name, version);
+ if(pathInfo!=null) {
+ aal.setPathInfo(pathInfo);
}
+ return aal;
}
} else {
return new PropertyLocator(key);
try {
return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
} catch (URISyntaxException e) {
- throw new LocatorException("Error coping URL");
+ throw new LocatorException("Error copying URL");
}
}
return rv;
char[] truststorePassArray = trustStorePass.toCharArray();
jks.load(null,truststorePassArray); // load in
- // Add Trusted Certificates
+ // Add Trusted Certificates, but PKCS12 doesn't support
for(int i=0; i<trustCAs.length;++i) {
jks.setCertificateEntry("ca_" + arti.getCa() + '_' + i, trustCAs[i]);
}
// Write out
write(fks,Chmod.to644,jks,truststorePassArray);
-
+ return true;
} catch (Exception e) {
throw new CadiException(e);
}
- return false;
}
}
//TODO other elements to add here...
// Ideas: Is it valid?
// if not, How many times has it been checked in the last minute
- if(expired()) {
- return true;
- } else {
- return false;
- }
+ return expired();
}
@Override
* Licensed 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.
import org.onap.aaf.cadi.util.SubStandardConsole;
import org.onap.aaf.cadi.util.TheConsole;
-
public class AAFSSO {
- public static final MyConsole cons = TheConsole.implemented()?new TheConsole():new SubStandardConsole();
-
+ public static final MyConsole cons = TheConsole.implemented() ? new TheConsole() : new SubStandardConsole();
+ private static final int EIGHT_HOURS = 8 * 60 * 60 * 1000;
+
private Properties diskprops = null; // use for temp storing User/Password on disk
- private File dot_aaf = null, sso=null; // instantiated, if ever, with diskprops
-
- boolean removeSSO=false;
+ private File dot_aaf = null;
+ private File sso = null; // instantiated, if ever, with diskprops
+
+ boolean removeSSO = false;
boolean loginOnly = false;
+ boolean doExit = true;
private PropAccess access;
private StringBuilder err;
- private String user,encrypted_pass;
+ private String user;
+ private String encrypted_pass;
private boolean use_X509;
- private PrintStream os, stdout=null,stderr=null;
+ private PrintStream os;
private Method close;
public AAFSSO(String[] args) throws IOException, CadiException {
- List<String> larg = new ArrayList<String>(args.length);
-
- // Cover for bash's need to escape *.. (\\*)
- // also, remove SSO if required
- for (int i = 0; i < args.length; ++i) {
- if ("\\*".equals(args[i])) {
- args[i] = "*";
- }
-
- if("-logout".equalsIgnoreCase(args[i])) {
- removeSSO=true;
- } else if("-login".equalsIgnoreCase(args[i])) {
- loginOnly = true;
- } else {
- larg.add(args[i]);
- }
- }
-
- String[] nargs = new String[larg.size()];
- larg.toArray(nargs);
+ String[] nargs = parseArgs(args);
- dot_aaf = new File(System.getProperty("user.home")+"/.aaf");
- if(!dot_aaf.exists()) {
+ dot_aaf = new File(System.getProperty("user.home") + "/.aaf");
+ if (!dot_aaf.exists()) {
dot_aaf.mkdirs();
}
- File f = new File(dot_aaf,"sso.out");
- os = new PrintStream(new FileOutputStream(f,true));
- stdout = System.out;
- stderr = System.err;
+ File f = new File(dot_aaf, "sso.out");
+ os = new PrintStream(new FileOutputStream(f, true));
System.setOut(os);
System.setErr(os);
- access = new PropAccess(os,nargs);
+ access = new PropAccess(os, nargs);
Config.setDefaultRealm(access);
user = access.getProperty(Config.AAF_APPID);
encrypted_pass = access.getProperty(Config.AAF_APPPASS);
-
- File dot_aaf_kf = new File(dot_aaf,"keyfile");
-
- sso = new File(dot_aaf,"sso.props");
- if(removeSSO) {
- if(dot_aaf_kf.exists()) {
- dot_aaf_kf.setWritable(true,true);
+
+ File dot_aaf_kf = new File(dot_aaf, "keyfile");
+
+ sso = new File(dot_aaf, "sso.props");
+ if (removeSSO) {
+ if (dot_aaf_kf.exists()) {
+ dot_aaf_kf.setWritable(true, true);
dot_aaf_kf.delete();
}
- if(sso.exists()) {
+ if (sso.exists()) {
sso.delete();
}
System.out.println("AAF SSO information removed");
- System.exit(0);
+ if (doExit) {
+ System.exit(0);
+ }
}
-
- if(!dot_aaf_kf.exists()) {
+
+ if (!dot_aaf_kf.exists()) {
FileOutputStream fos = new FileOutputStream(dot_aaf_kf);
try {
fos.write(Symm.keygen());
- dot_aaf_kf.setExecutable(false,false);
- dot_aaf_kf.setWritable(false,false);
- dot_aaf_kf.setReadable(false,false);
- dot_aaf_kf.setReadable(true, true);
+ setReadonly(dot_aaf_kf);
} finally {
fos.close();
}
}
String keyfile = access.getProperty(Config.CADI_KEYFILE); // in case it's CertificateMan props
- if(keyfile==null) {
+ if (keyfile == null) {
access.setProperty(Config.CADI_KEYFILE, dot_aaf_kf.getAbsolutePath());
}
-
+
String alias = access.getProperty(Config.CADI_ALIAS);
- if(user==null && alias!=null && access.getProperty(Config.CADI_KEYSTORE_PASSWORD)!=null) {
+ if ((user == null) && (alias != null) && (access.getProperty(Config.CADI_KEYSTORE_PASSWORD) != null)) {
user = alias;
access.setProperty(Config.AAF_APPID, user);
use_X509 = true;
} else {
use_X509 = false;
Symm decryptor = Symm.obtain(dot_aaf_kf);
- if (user==null) {
- if(sso.exists() && sso.lastModified()>System.currentTimeMillis()-(8*60*60*1000 /* 8 hours */)) {
+ if (user == null) {
+ if (sso.exists() && (sso.lastModified() > (System.currentTimeMillis() - EIGHT_HOURS))) {
String cm_url = access.getProperty(Config.CM_URL); // SSO might overwrite...
FileInputStream fos = new FileInputStream(sso);
try {
user = access.getProperty(Config.AAF_APPID);
encrypted_pass = access.getProperty(Config.AAF_APPPASS);
// decrypt with .aaf, and re-encrypt with regular Keyfile
- access.setProperty(Config.AAF_APPPASS,
+ access.setProperty(Config.AAF_APPPASS,
access.encrypt(decryptor.depass(encrypted_pass)));
- if(cm_url!=null) { //Command line CM_URL Overwrites ssofile.
+ if (cm_url != null) { //Command line CM_URL Overwrites ssofile.
access.setProperty(Config.CM_URL, cm_url);
}
} finally {
diskprops = new Properties();
String realm = Config.getDefaultRealm();
// Turn on Console Sysout
- System.setOut(stdout);
- user=cons.readLine("aaf_id(%s@%s): ",System.getProperty("user.name"),realm);
- if(user==null) {
- user = System.getProperty("user.name")+'@'+realm;
- } else if(user.length()==0) { //
- user = System.getProperty("user.name")+'@' + realm;
- } else if(user.indexOf('@')<0 && realm!=null) {
- user = user+'@'+realm;
+ System.setOut(System.out);
+ user = cons.readLine("aaf_id(%s@%s): ", System.getProperty("user.name"), realm);
+ if (user == null) {
+ user = System.getProperty("user.name") + '@' + realm;
+ } else if (user.length() == 0) { //
+ user = System.getProperty("user.name") + '@' + realm;
+ } else if ((user.indexOf('@') < 0) && (realm != null)) {
+ user = user + '@' + realm;
}
- access.setProperty(Config.AAF_APPID,user);
- diskprops.setProperty(Config.AAF_APPID,user);
+ access.setProperty(Config.AAF_APPID, user);
+ diskprops.setProperty(Config.AAF_APPID, user);
encrypted_pass = new String(cons.readPassword("aaf_password: "));
System.setOut(os);
- encrypted_pass = Symm.ENC+decryptor.enpass(encrypted_pass);
- access.setProperty(Config.AAF_APPPASS,encrypted_pass);
- diskprops.setProperty(Config.AAF_APPPASS,encrypted_pass);
+ encrypted_pass = Symm.ENC + decryptor.enpass(encrypted_pass);
+ access.setProperty(Config.AAF_APPPASS, encrypted_pass);
+ diskprops.setProperty(Config.AAF_APPPASS, encrypted_pass);
diskprops.setProperty(Config.CADI_KEYFILE, access.getProperty(Config.CADI_KEYFILE));
}
}
if (user == null) {
err = new StringBuilder("Add -D" + Config.AAF_APPID + "=<id> ");
}
-
- if (encrypted_pass == null && alias==null) {
+
+ if (encrypted_pass == null && alias == null) {
if (err == null) {
err = new StringBuilder();
} else {
err.append("-D" + Config.AAF_APPPASS + "=<passwd> ");
}
}
-
+
public void setLogDefault() {
- access.setLogLevel(PropAccess.DEFAULT);
- if(stdout!=null) {
- System.setOut(stdout);
- }
+ this.setLogDefault(PropAccess.DEFAULT);
}
public void setStdErrDefault() {
access.setLogLevel(PropAccess.DEFAULT);
- if(stderr!=null) {
- System.setErr(stderr);
- }
+ System.setErr(System.err);
}
public void setLogDefault(Level level) {
access.setLogLevel(level);
- if(stdout!=null) {
- System.setOut(stdout);
- }
+ System.setOut(System.out);
}
-
+
public boolean loginOnly() {
return loginOnly;
}
public void addProp(String key, String value) {
- if(diskprops!=null) {
+ if (diskprops != null) {
diskprops.setProperty(key, value);
}
}
-
+
public void writeFiles() throws IOException {
- // Store Creds, if they work
- if(diskprops!=null) {
- if(!dot_aaf.exists()) {
+ // Store Creds, if they work
+ if (diskprops != null) {
+ if (!dot_aaf.exists()) {
dot_aaf.mkdirs();
}
FileOutputStream fos = new FileOutputStream(sso);
diskprops.store(fos, "AAF Single Signon");
} finally {
fos.close();
- sso.setWritable(false,false);
- sso.setExecutable(false,false);
- sso.setReadable(false,false);
- sso.setReadable(true,true);
+ setReadonly(sso);
}
}
- if(sso!=null) {
- sso.setReadable(false,false);
- sso.setWritable(false,false);
- sso.setExecutable(false,false);
- sso.setReadable(true,true);
- sso.setWritable(true,true);
+ if (sso != null) {
+ setReadonly(sso);
+ sso.setWritable(true, true);
}
}
public StringBuilder err() {
return err;
}
-
+
public String user() {
return user;
}
-
+
public String enc_pass() {
return encrypted_pass;
}
-
+
public boolean useX509() {
return use_X509;
}
-
+
public void close() {
- if(close!=null) {
+ if (close != null) {
try {
close.invoke(null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
close = null;
}
}
+
+ private String[] parseArgs(String[] args)
+ {
+ List<String> larg = new ArrayList<String>(args.length);
+
+ // Cover for bash's need to escape *.. (\\*)
+ // also, remove SSO if required
+ for (int i = 0; i < args.length; ++i) {
+ if ("\\*".equals(args[i])) {
+ args[i] = "*";
+ }
+
+ if ("-logout".equalsIgnoreCase(args[i])) {
+ removeSSO = true;
+ } else if ("-login".equalsIgnoreCase(args[i])) {
+ loginOnly = true;
+ } else if ("-noexit".equalsIgnoreCase(args[i])) {
+ doExit = false;
+ } else {
+ larg.add(args[i]);
+ }
+ }
+ String[] nargs = new String[larg.size()];
+ larg.toArray(nargs);
+ return nargs;
+ }
+
+ private void setReadonly(File file) {
+ file.setExecutable(false, false);
+ file.setWritable(false, false);
+ file.setReadable(false, false);
+ file.setReadable(true, true);
+ }
}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.aaf.cert.test;
+
+import static org.mockito.Mockito.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
+import org.junit.*;
+import org.mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.aaf.cert.AAFListedCertIdentity;
+import org.onap.aaf.cadi.aaf.v2_0.AAFCon;
+import org.onap.aaf.cadi.client.Future;
+import org.onap.aaf.cadi.client.Rcli;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.misc.env.util.Chrono;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
+
+import aaf.v2_0.Certs;
+import aaf.v2_0.Certs.Cert;
+import aaf.v2_0.Users;
+import aaf.v2_0.Users.User;
+
+public class JU_AAFListedCertIdentity {
+
+ @Mock private AAFCon<?> conMock;
+ @Mock private Rcli<Object> rcliMock;
+ @Mock private RosettaDF<Users> userDFMock;
+ @Mock private RosettaDF<Certs> certDFMock;
+ @Mock private Future<Users> futureUsersMock;
+ @Mock private Future<Certs> futureCertsMock;
+
+ @Mock private Users usersMock;
+ @Mock private User userMock1;
+ @Mock private User userMock2;
+ @Mock private User userMock3;
+
+ @Mock private Certs certsMock;
+ @Mock private Cert certMock1;
+ @Mock private Cert certMock2;
+ @Mock private Cert certMock3;
+
+ @Mock private HttpServletRequest reqMock;
+ @Mock private X509Certificate x509Mock;
+
+ private List<User> usersList;
+ private List<Cert> certsList;
+
+ private PropAccess access;
+
+ private ByteArrayOutputStream outStream;
+
+ private static final String USERS = "user1,user2,user3";
+ private static final String ID = "id";
+ private static final String FINGERPRINT = "fingerprint";
+
+ private static final byte[] certBytes = "certificate".getBytes();
+
+ @Before
+ public void setup() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
+ MockitoAnnotations.initMocks(this);
+
+ certsList = new ArrayList<>();
+ certsList.add(certMock1);
+ certsList.add(certMock2);
+ certsList.add(certMock3);
+
+ usersList = new ArrayList<>();
+ usersList.add(userMock1);
+ usersList.add(userMock2);
+ usersList.add(userMock3);
+
+ outStream = new ByteArrayOutputStream();
+ access = new PropAccess(new PrintStream(outStream), new String[0]);
+ outStream.reset();
+ access.setProperty(Config.AAF_CERT_IDS, USERS);
+ setFinal(conMock, conMock.getClass().getField("usersDF"), userDFMock);
+ setFinal(conMock, conMock.getClass().getField("certsDF"), certDFMock);
+ setFinal(conMock, conMock.getClass().getField("access"), access);
+ }
+
+ @Test
+ public void test() throws APIException, CadiException, CertificateException {
+ doReturn(rcliMock).when(conMock).client(Config.AAF_DEFAULT_VERSION);
+ when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/tguard/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock);
+ when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/basicAuth/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock);
+ when(rcliMock.read("/authz/users/perm/com.att.aaf.trust/csp/authenticate", Users.class, userDFMock)).thenReturn(futureUsersMock);
+
+ when(futureUsersMock.get(5000)).thenReturn(true);
+ futureUsersMock.value = usersMock;
+ when(usersMock.getUser()).thenReturn(usersList);
+
+ when(rcliMock.read("/authn/cert/id/user1", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock);
+ when(rcliMock.read("/authn/cert/id/user2", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock);
+ when(rcliMock.read("/authn/cert/id/user3", Certs.class, conMock.certsDF)).thenReturn(futureCertsMock);
+
+ when(futureCertsMock.get(5000)).thenReturn(true);
+ futureCertsMock.value = certsMock;
+ when(certsMock.getCert()).thenReturn(certsList);
+
+ when(userMock1.getId()).thenReturn("user1");
+ when(userMock2.getId()).thenReturn("user2");
+ when(userMock3.getId()).thenReturn("user3");
+
+ prepareCert(certMock1);
+ prepareCert(certMock2);
+ prepareCert(certMock3);
+
+ AAFListedCertIdentity certID = new AAFListedCertIdentity(access, conMock);
+
+ when(x509Mock.getEncoded()).thenReturn(certBytes);
+ certID.identity(reqMock, null, null);
+ certID.identity(reqMock, null, certBytes);
+ certID.identity(reqMock, x509Mock, null);
+ certID.identity(reqMock, x509Mock, certBytes);
+
+ Set<String> hashSetOfUsers = AAFListedCertIdentity.trusted("basicAuth");
+ assertThat(hashSetOfUsers.contains("user1"), is(true));
+ assertThat(hashSetOfUsers.contains("user2"), is(true));
+ assertThat(hashSetOfUsers.contains("user3"), is(true));
+
+ }
+
+ private void setFinal(Object object, Field field, Object newValue) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
+ field.setAccessible(true);
+
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(field, field.getModifiers() & Modifier.FINAL);
+
+ field.set(object, newValue);
+ }
+
+ private void prepareCert(Cert cert) {
+ Date date = new Date();
+ when(cert.getExpires()).thenReturn(Chrono.timeStamp(new Date(date.getTime() + (60 * 60 * 24))));
+ when(cert.getId()).thenReturn(ID);
+ when(cert.getFingerprint()).thenReturn(FINGERPRINT.getBytes());
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.aaf.marshal.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.junit.*;
+
+import org.onap.aaf.cadi.aaf.marshal.CertMarshal;
+import org.onap.aaf.misc.env.util.Chrono;
+import org.onap.aaf.misc.rosetta.OutRaw;
+import org.onap.aaf.misc.rosetta.ParseException;
+import org.onap.aaf.misc.rosetta.marshal.DataWriter;
+
+import aaf.v2_0.Certs.Cert;
+
+public class JU_CertMarshal {
+
+ private static final String fingerprint = "fingerprint";
+ private static final String id = "id";
+ private static final String x500 = "x500";
+
+ private String fingerprintAsString;
+
+ private XMLGregorianCalendar expires;
+
+ private ByteArrayOutputStream outStream;
+
+ @Before
+ public void setup() {
+ expires = Chrono.timeStamp();
+ outStream = new ByteArrayOutputStream();
+ StringBuilder sb = new StringBuilder();
+ DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb);
+ fingerprintAsString = sb.toString();
+ }
+
+ @Test
+ public void test() throws ParseException, IOException {
+ Cert cert = setupCert();
+ CertMarshal cm = new CertMarshal();
+ OutRaw raw = new OutRaw();
+
+ raw.extract(cert, new PrintStream(outStream), cm);
+
+ String[] output = outStream.toString().split("\n");
+
+ String[] expected = new String[] {
+ "{ - ",
+ ", - fingerprint : \"" + fingerprintAsString + "\"",
+ ", - id : \"" + id + "\"",
+ ", - x500 : \"" + x500 + "\"",
+ ", - expires : \"" + Chrono.dateTime(expires) + "\"",
+ "} - ",
+ };
+
+ assertThat(output.length, is(expected.length));
+
+ for (int i = 0; i < output.length; i++) {
+ assertThat(output[i], is(expected[i]));
+ }
+ }
+
+ private Cert setupCert() {
+ Cert cert = new Cert();
+ cert.setId(id);
+ cert.setX500(x500);
+ cert.setExpires(expires);
+ cert.setFingerprint(fingerprint.getBytes());
+ return cert;
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.aaf.marshal.test;
+
+import org.junit.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.ArrayList;
+
+import javax.xml.datatype.XMLGregorianCalendar;
+import org.onap.aaf.cadi.aaf.marshal.CertsMarshal;
+import org.onap.aaf.misc.env.util.Chrono;
+import org.onap.aaf.misc.rosetta.OutRaw;
+import org.onap.aaf.misc.rosetta.ParseException;
+import org.onap.aaf.misc.rosetta.marshal.DataWriter;
+
+import aaf.v2_0.Certs;
+import aaf.v2_0.Certs.Cert;
+
+public class JU_CertsMarshal {
+
+ private static final String fingerprint = "fingerprint";
+ private static final String id = "id";
+ private static final String x500 = "x500";
+
+ private String fingerprintAsString;
+
+ private XMLGregorianCalendar expires;
+
+ private ByteArrayOutputStream outStream;
+
+ @Before
+ public void setup() {
+ expires = Chrono.timeStamp();
+ outStream = new ByteArrayOutputStream();
+ StringBuilder sb = new StringBuilder();
+ DataWriter.HEX_BINARY.write(fingerprint.getBytes(), sb);
+ fingerprintAsString = sb.toString();
+ }
+
+ @Test
+ public void test() throws ParseException, IOException {
+ CertsStub certs = new CertsStub();
+ CertsMarshal cm = new CertsMarshal();
+ OutRaw raw = new OutRaw();
+
+ raw.extract(certs, new PrintStream(outStream), cm);
+ String[] output = outStream.toString().split("\n");
+
+ String[] expected = new String[] {
+ "{ - ",
+ "[ - cert",
+ "{ - ",
+ ", - fingerprint : \"" + fingerprintAsString + "\"",
+ ", - id : \"" + id + "\"",
+ ", - x500 : \"" + x500 + "\"",
+ ", - expires : \"" + Chrono.dateTime(expires) + "\"",
+ "} - ",
+ ", - ",
+ "{ - ",
+ ", - fingerprint : \"" + fingerprintAsString + "\"",
+ ", - id : \"" + id + "\"",
+ ", - x500 : \"" + x500 + "\"",
+ ", - expires : \"" + Chrono.dateTime(expires) + "\"",
+ "} - ",
+ "] - ",
+ "} - ",
+ };
+
+ assertThat(output.length, is(expected.length));
+
+ for (int i = 0; i < output.length; i++) {
+ assertThat(output[i], is(expected[i]));
+ }
+ }
+
+ private Cert setupCert() {
+ Cert cert = new Cert();
+ cert.setId(id);
+ cert.setX500(x500);
+ cert.setExpires(expires);
+ cert.setFingerprint(fingerprint.getBytes());
+ return cert;
+ }
+
+ private class CertsStub extends Certs {
+ public CertsStub() {
+ cert = new ArrayList<>();
+ for (int i = 0; i < 2; i++) {
+ cert.add(setupCert());
+ }
+ }
+ }
+
+}
package org.onap.aaf.cadi.aaf.v2_0.test;
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.mockito.Mockito.*;
+
+import org.junit.*;
+import org.mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URI;
-import static org.junit.Assert.*;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
import org.onap.aaf.cadi.PropAccess;
-import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.LocatorException;
import org.onap.aaf.cadi.aaf.v2_0.AAFLocator;
import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator;
+import org.onap.aaf.cadi.client.Future;
import org.onap.aaf.cadi.config.Config;
import org.onap.aaf.cadi.config.SecurityInfoC;
+import org.onap.aaf.cadi.http.HClient;
+import org.onap.aaf.misc.env.Data.TYPE;
import org.onap.aaf.misc.env.impl.BasicTrans;
-import org.onap.aaf.misc.rosetta.env.RosettaEnv;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
-public class JU_AAFLocator {
+import locate.v1_0.Endpoint;
+import locate.v1_0.Endpoints;
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- }
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- }
+public class JU_AAFLocator {
+
+ @Mock private HClient clientMock;
+ @Mock private Future<Endpoints> futureMock;
+ @Mock private Endpoints endpointsMock;
+
+ private PropAccess access;
+
+ private ByteArrayOutputStream errStream;
+
+ private static final String uriString = "https://example.com";
@Before
public void setUp() throws Exception {
- }
+ MockitoAnnotations.initMocks(this);
+
+ doReturn(futureMock).when(clientMock).futureRead((RosettaDF<?>)any(), eq(TYPE.JSON));
+ when(clientMock.timeout()).thenReturn(1);
+ when(clientMock.getURI()).thenReturn(new URI(uriString));
+ when(futureMock.get(1)).thenReturn(true);
+
+ futureMock.value = endpointsMock;
+ List<Endpoint> endpoints = new ArrayList<>();
+ endpoints.add(new Endpoint());
+ when(endpointsMock.getEndpoint()).thenReturn(endpoints);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+
+ errStream = new ByteArrayOutputStream();
+ System.setErr(new PrintStream(errStream));
+ }
+
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
+ System.setErr(System.err);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ Field field = SecurityInfoC.class.getDeclaredField("sicMap");
+ field.setAccessible(true);
+ field.set(null, new HashMap<Class<?>,SecurityInfoC<?>>());
}
@Test
- public void test() {
- // TODO: Ian [JUnit] This fails because these files don't exist
- assertTrue(true);
- // try {
- // PropAccess propAccess = new PropAccess("cadi_prop_files=/opt/app/aaf/common/com.att.aaf.common.props:/opt/app/aaf/common/com.att.aaf.props");
- // SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(propAccess, HttpURLConnection.class);
- // String alu = propAccess.getProperty(Config.AAF_LOCATE_URL,"https://mithrilcsp.sbc.com:8095/locate");
- // URI locatorURI = new URI(alu+"/com.att.aaf.service/2.0");
- // AbsAAFLocator<BasicTrans> al = new AAFLocator(si, locatorURI);
- // Assert.assertTrue(al.refresh());
- // Item i = al.first();
- // i = al.next(i);
- // i = al.best();
- // } catch (Exception e) {
- // Assert.fail();
- // }
+ public void test() throws CadiException, URISyntaxException, LocatorException {
+ access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat
+ access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon
+ SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(access, HttpURLConnection.class);
+ String alu = access.getProperty(Config.AAF_LOCATE_URL,"https://mithrilcsp.sbc.com:8095/locate");
+ URI locatorURI = new URI(alu+"/com.att.aaf.service/2.0");
+ AbsAAFLocator<BasicTrans> al = new AAFLocator(si, locatorURI) {
+ @Override
+ protected HClient createClient(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout) throws LocatorException {
+ return clientMock;
+ }
+ };
+ assertThat(al.refresh(), is(true));
+ when(futureMock.get(1)).thenReturn(false);
+ assertThat(al.refresh(), is(false));
+ String errorMessage = errStream.toString().split(": ", 2)[1];
+ assertThat(errorMessage, is("Error reading location information from " + uriString + ": 0 null\n \n"));
}
}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.aaf.v2_0.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.aaf.cadi.Lur;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.principal.TaggedPrincipal;
+import org.onap.aaf.cadi.taf.TafResp;
+import org.onap.aaf.cadi.taf.TrustNotTafResp;
+import org.onap.aaf.cadi.taf.TrustTafResp;
+import org.onap.aaf.misc.env.Env;
+
+public class JU_AAFTrustChecker {
+
+ private final static String type = "type";
+ private final static String instance = "instance";
+ private final static String action = "action";
+ private final static String key = type + '|' + instance + '|' + action;
+ private final static String name = "name";
+ private final static String otherName = "otherName";
+
+ private PropAccess access;
+
+ @Mock private Env envMock;
+ @Mock private TafResp trespMock;
+ @Mock private HttpServletRequest reqMock;
+ @Mock private TaggedPrincipal tpMock;
+ @Mock private Lur lurMock;
+ @Mock private TaggedPrincipal princMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() {
+ AAFTrustChecker trustChecker;
+
+ // coverage calls
+ trustChecker = new AAFTrustChecker(access);
+ trustChecker = new AAFTrustChecker(envMock);
+
+ access.setProperty(Config.CADI_TRUST_PERM, "example");
+ when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn("example");
+ trustChecker = new AAFTrustChecker(access);
+ trustChecker = new AAFTrustChecker(envMock);
+
+ access.setProperty(Config.CADI_TRUST_PERM, key);
+ when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(key);
+ trustChecker = new AAFTrustChecker(access);
+ trustChecker = new AAFTrustChecker(envMock);
+
+ trustChecker.setLur(lurMock);
+
+ assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock));
+
+ when(reqMock.getHeader(null)).thenReturn("comma,comma,comma");
+ assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock));
+
+ when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:colon,comma,comma");
+ assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock));
+
+ when(reqMock.getHeader(null)).thenReturn("colon:colon:colon:AS,comma,comma");
+ when(trespMock.getPrincipal()).thenReturn(tpMock);
+ when(tpMock.getName()).thenReturn(name);
+ when(lurMock.fish(princMock, null)).thenReturn(true);
+ TafResp tntResp = trustChecker.mayTrust(trespMock, reqMock);
+
+ assertThat(tntResp instanceof TrustNotTafResp, is(true));
+ assertThat(tntResp.toString(), is("name requested trust as colon, but does not have Authorization"));
+
+ when(reqMock.getHeader(null)).thenReturn(name + ":colon:colon:AS,comma,comma");
+ assertThat(trustChecker.mayTrust(trespMock, reqMock), is(trespMock));
+
+ when(envMock.getProperty(Config.CADI_ALIAS, null)).thenReturn(name);
+ when(envMock.getProperty(Config.CADI_TRUST_PERM)).thenReturn(null);
+ trustChecker = new AAFTrustChecker(envMock);
+ trustChecker.setLur(lurMock);
+
+ when(trespMock.getPrincipal()).thenReturn(princMock);
+ when(princMock.getName()).thenReturn(otherName);
+ when(lurMock.fish(princMock, null)).thenReturn(true);
+ TafResp ttResp = trustChecker.mayTrust(trespMock, reqMock);
+ assertThat(ttResp instanceof TrustTafResp, is(true));
+ assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null"));
+
+ when(princMock.getName()).thenReturn(name);
+ ttResp = trustChecker.mayTrust(trespMock, reqMock);
+ assertThat(ttResp instanceof TrustTafResp, is(true));
+ assertThat(ttResp.toString(), is(name + " by trust of " + name + " validated using colon by colon, null"));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.aaf.v2_0.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
+import org.junit.*;
+import org.mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator;
+import org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator.LocatorCreator;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.misc.env.impl.BasicTrans;
+
+public class JU_AbsAAFLocator {
+
+ @Mock private LocatorCreator locatorCreatorMock;
+
+ private PropAccess access;
+ private URI uri;
+
+ private static final String uriString = "example.com";
+
+ @Before
+ public void setup() throws URISyntaxException {
+ MockitoAnnotations.initMocks(this);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat
+ access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon
+
+ uri = new URI(uriString);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ AbsAAFLocator.setCreator(null);
+ }
+
+ @Test
+ public void test() throws LocatorException {
+ AAFLocatorStub loc;
+
+ // Test with http
+ loc = new AAFLocatorStub(access, "httpname");
+ assertThat(loc.getName(), is("httpname"));
+ assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION));
+ assertThat(loc.toString(), is("AAFLocator for " + "httpname" + " on " + loc.getURI()));
+
+ loc = new AAFLocatorStub(access, "name");
+ assertThat(loc.getName(), is("name"));
+ assertThat(loc.getVersion(), is(Config.AAF_DEFAULT_VERSION));
+ loc = new AAFLocatorStub(access, "name:v2.0");
+ assertThat(loc.getName(), is("name"));
+ assertThat(loc.getVersion(), is("v2.0"));
+ }
+
+ @Test
+ public void createTest() throws LocatorException {
+ AbsAAFLocator.setCreator(locatorCreatorMock);
+
+ assertThat(AbsAAFLocator.create("nonsense"), is(nullValue()));
+ assertThat(AbsAAFLocator.create("nonsense/locate"), is(nullValue()));
+ assertThat(AbsAAFLocator.create("nonsense/locate/"), is(nullValue()));
+ assertThat(AbsAAFLocator.create("nonsense/locate//"), is(nullValue()));
+ assertThat(AbsAAFLocator.create("nonsense/locate/name:v2.0"), is(nullValue()));
+
+ assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue()));
+
+ doReturn(mock(AbsAAFLocator.class)).when(locatorCreatorMock).create(anyString(), anyString());
+ assertThat(AbsAAFLocator.create("http/locate/name:v2.0/path"), is(not(nullValue())));
+
+ AbsAAFLocator.setCreator(null);
+ assertThat(AbsAAFLocator.create("http/locate/name:v2.0"), is(nullValue()));
+
+ assertThat(AbsAAFLocator.create("http"), is(not(nullValue())));
+
+ AbsAAFLocator.setCreator(locatorCreatorMock);
+ assertThat(AbsAAFLocator.create("first", "second"), is(not(nullValue())));
+ }
+
+ @Test
+ public void nameFromLocatorURITest() throws LocatorException, URISyntaxException {
+ AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0");
+ assertThat(loc.getNameFromURI(new URI("example.com")), is("example.com"));
+ assertThat(loc.getNameFromURI(new URI("example.com/extra/stuff")), is("example.com/extra/stuff"));
+ assertThat(loc.getNameFromURI(new URI("example.com/locate/stuff")), is("stuff")); // n' stuff
+ }
+
+ @Test
+ public void setSelfTest() throws LocatorException {
+ AbsAAFLocator.setCreatorSelf("host", 8000);
+ AbsAAFLocator.setCreator(null);
+ AbsAAFLocator.setCreatorSelf("host", 8000);
+ (new AAFLocatorStub(access, "name:v2.0")).setSelf("host", 8000); // oof
+ }
+
+ @Test
+ public void coverage() throws LocatorException {
+ AAFLocatorStub loc = new AAFLocatorStub(access, "name:v2.0");
+ assertThat(loc.get(null), is(nullValue()));
+
+ try {
+ loc.get(mock(Item.class));
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+
+ try {
+ loc.invalidate(mock(Item.class));
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+
+ try {
+ loc.best();
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+
+ assertThat(loc.first(), is(nullValue()));
+
+ assertThat(loc.hasItems(), is(false));
+ assertThat(loc.next(null), is(nullValue()));
+
+ try {
+ loc.next(mock(Item.class));
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+
+ loc.destroy();
+
+
+ assertThat(loc.exposeGetURI(uri), is(uri));
+
+ assertThat(loc.setPathInfo("pathInfo"), is(not(nullValue())));
+ assertThat(loc.setQuery("query"), is(not(nullValue())));
+ assertThat(loc.setFragment("fragment"), is(not(nullValue())));
+
+ assertThat(loc.exposeGetURI(uri), is(not(uri)));
+ }
+
+
+ @Test(expected = LocatorException.class)
+ public void throwsTest() throws LocatorException {
+ @SuppressWarnings("unused")
+ AAFLocatorStub loc = new AAFLocatorStub(new PropAccess(), "name");
+ }
+
+ private class AAFLocatorStub extends AbsAAFLocator<BasicTrans> {
+ public AAFLocatorStub(Access access, String name) throws LocatorException {
+ super(access, name, 10000L);
+ }
+ @Override public boolean refresh() { return false; }
+ @Override protected URI getURI() { return uri; }
+ public String getName() { return name; }
+ public String getVersion() { return version; }
+ public String getNameFromURI(URI uri) { return nameFromLocatorURI(uri); }
+ public URI exposeGetURI(URI uri) throws LocatorException { return super.getURI(uri); }
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.cm.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.IOException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.cm.ArtifactDir;
+import org.onap.aaf.cadi.util.Chmod;
+import org.onap.aaf.misc.env.Trans;
+
+import certman.v1_0.Artifacts.Artifact;
+import certman.v1_0.CertInfo;
+
+public class JU_ArtifactDir {
+
+ @Mock private Trans transMock;
+ @Mock private CertInfo certInfoMock;
+ @Mock private Artifact artiMock;
+
+ private static final String dirName = "src/test/resources/artifacts";
+ private static final String nsName = "org.onap.test";
+ private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life
+
+ private List<String> issuers;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ issuers = new ArrayList<>();
+ issuers.add("issuer1");
+ issuers.add("issuer2");
+ }
+
+ @After
+ public void tearDown() {
+ ArtifactDir.clear();
+ }
+
+ @AfterClass
+ public static void tearDownOnce() {
+ cleanup();
+ }
+
+ @Test
+ public void test() throws CadiException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
+ ArtifactDirStud artiDir = new ArtifactDirStud();
+
+ try {
+ artiDir.place(transMock, certInfoMock, artiMock, "machine");
+ fail("Should've thrown an exception");
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is("File Artifacts require a path\nFile Artifacts require an AAF Namespace"));
+ }
+
+ when(artiMock.getDir()).thenReturn(dirName);
+ try {
+ artiDir.place(transMock, certInfoMock, artiMock, "machine");
+ fail("Should've thrown an exception");
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is("File Artifacts require an AAF Namespace"));
+ }
+
+ when(artiMock.getNs()).thenReturn(nsName);
+ when(certInfoMock.getCaIssuerDNs()).thenReturn(issuers);
+ when(certInfoMock.getChallenge()).thenReturn(luggagePassword);
+ artiDir.place(transMock, certInfoMock, artiMock, "machine");
+
+ File writableFile = new File(dirName + '/' + nsName + "writable.txt");
+ artiDir.write(writableFile, Chmod.to755, "first data point", "second data point");
+ try {
+ artiDir.write(writableFile, Chmod.to755, (String[])null);
+ fail("Should've thrown an exception");
+ } catch(NullPointerException e) {
+ }
+
+ KeyStore ks = KeyStore.getInstance("pkcs12");
+ try {
+ artiDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray());
+ fail("Should've thrown an exception");
+ } catch(CadiException e) {
+ }
+
+ ks.load(null, null);
+ artiDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray());
+
+ ArtifactDirStud artiDir2 = new ArtifactDirStud();
+ artiDir2.place(transMock, certInfoMock, artiMock, "machine");
+
+ // coverage
+ artiDir.place(transMock, certInfoMock, artiMock, "machine");
+
+ ArtifactDir.clear();
+ artiDir.place(transMock, certInfoMock, artiMock, "machine");
+
+ }
+
+ @Test(expected = CadiException.class)
+ public void throwsTest() throws CadiException {
+ ArtifactDirStud artiDir = new ArtifactDirStud();
+ when(artiMock.getDir()).thenReturn(dirName);
+ when(artiMock.getNs()).thenReturn(nsName);
+ artiDir.place(transMock, certInfoMock, artiMock, "machine");
+ }
+
+ private class ArtifactDirStud extends ArtifactDir {
+ @Override
+ protected boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException {
+ // This is only here so that we have a concrete class to test
+ return false;
+ }
+
+ // Expose the protected methods
+
+ public void write(File f, Chmod c, String ... data) throws IOException {
+ super.write(f, c, data);
+ }
+ public void write(File f, Chmod c, KeyStore ks, char[] pass ) throws IOException, CadiException {
+ super.write(f, c, ks, pass);
+ }
+ }
+
+ private static void cleanup() {
+ File dir = new File(dirName);
+ if (dir.exists()) {
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed 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.
+ * * ============LICENSE_END====================================================
+ * *
+ * *
+ ******************************************************************************/
+
+package org.onap.aaf.cadi.cm.test;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aaf.cadi.cm.CmAgent;
+
+public class JU_CmAgent {
+
+ private static final String resourceDirString = "src/test/resources";
+ private static final String aafDir = resourceDirString + "/aaf";
+
+ private ByteArrayInputStream inStream;
+
+ @Before
+ public void setup() {
+ System.setProperty("user.home", aafDir);
+
+ // Simulate user input
+ inStream = new ByteArrayInputStream("test\nhttp://example.com\nhttp://example.com".getBytes());
+ System.setIn(inStream);
+ }
+
+ @After
+ public void tearDown() {
+ recursiveDelete(new File(aafDir));
+ }
+
+ @Test
+ public void test() {
+ String[] args;
+ args = new String[] {
+ "-login",
+ "-noexit",
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "noexit=true",
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "place",
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "create"
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "read"
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "copy"
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "update"
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "delete"
+ };
+ CmAgent.main(args);
+
+ inStream.reset();
+ args = new String[] {
+ "showpass"
+ };
+ CmAgent.main(args);
+
+ }
+
+ private void recursiveDelete(File file) {
+ for (File f : file.listFiles()) {
+ if (f.isDirectory()) {
+ recursiveDelete(f);
+ }
+ f.delete();
+ }
+ file.delete();
+ }
+
+}
* * Licensed 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.
* *
* *
******************************************************************************/
+
package org.onap.aaf.cadi.cm.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.mockito.Mockito.*;
-import org.junit.*;
-import org.mockito.*;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyString;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import java.io.BufferedReader;
import java.io.File;
import org.onap.aaf.cadi.cm.CertException;
import org.onap.aaf.cadi.cm.Factory;
+import org.onap.aaf.cadi.cm.Factory.Base64InputStream;
import org.onap.aaf.cadi.cm.Factory.StripperInputStream;
import org.onap.aaf.misc.env.Env;
public class JU_Factory {
- @Mock
- Trans transMock;
-
- @Mock
- TimeTaken timeTakenMock;
-
- @Mock
- LogTarget logTargetMock;
-
- @Mock
- X509Certificate x509CertMock;
-
- @Mock
- Certificate certMock;
-
- @Mock
- Principal subjectDN;
+ private static final String message = "The quick brown fox jumps over the lazy dog.";
+ private static final String subjectDNText = "subjectDN";
+ private static final String certText = "Some text that might be included in a certificate";
+ private static final String resourceDirName = "src/test/resources";
- private final String resourceDirName = "src/test/resources";
private File resourceDir;
private File publicKeyFile;
private File privateKeyFile;
private File certFile;
-
- private static final String message = "The quick brown fox jumps over the lazy dog.";
- private static final String subjectDNText = "subjectDN";
- private static final String certText = "Some text that might be included in a certificate";
+ @Mock private Trans transMock;
+ @Mock private TimeTaken timeTakenMock;
+ @Mock private LogTarget logTargetMock;
+ @Mock private X509Certificate x509CertMock;
+ @Mock private Certificate certMock;
+ @Mock private Principal subjectDN;
+
@Before
public void setup() throws CertificateEncodingException {
privateKeyFile = new File(resourceDirName, "/privateKey");
publicKeyFile.delete();
privateKeyFile.delete();
-
- if (resourceDir.list().length == 0) {
- resourceDir.delete();
- }
}
@Test
assertThat(Factory.verify(transMock, signedString.getBytes(), signedBytes, kp.getPublic()), is(true));
}
- // TODO: Ian - finish these tests
- // @Test
- // public void base64ISTest() throws Exception {
- // KeyPair kp = Factory.generateKeyPair(transMock);
-
- // String privateKeyString = Factory.toString(transMock, kp.getPrivate());
- // String cleaned = cleanupString(privateKeyString);
- // System.out.println(cleaned);
- // writeToFile(privateKeyFile, cleaned);
- // Base64InputStream b64is = new Base64InputStream(privateKeyFile);
- // byte[] buffer = new byte[10000];
- // b64is.read(buffer);
- // System.out.println(new String(buffer));
- // b64is.close();
- // }
-
- // @Test
- // public void getSecurityProviderTest() {
- // }
+ @Test
+ public void base64ISTest() throws Exception {
+ KeyPair kp = Factory.generateKeyPair(transMock);
+
+ String privateKeyString = Factory.toString(transMock, kp.getPrivate());
+ String cleaned = cleanupString(privateKeyString);
+ writeToFile(privateKeyFile, cleaned, null);
+ Base64InputStream b64is = new Base64InputStream(privateKeyFile);
+ byte[] buffer = new byte[10000];
+ b64is.read(buffer);
+ b64is.close();
+
+ FileInputStream fis = new FileInputStream(privateKeyFile);
+ b64is = new Base64InputStream(fis);
+ b64is.close();
+ fis.close();
+ }
+
+ @Test
+ public void getSecurityProviderTest() throws CertException {
+ String[][] params = {
+ {"test", "test"},
+ {"test", "test"},
+ };
+ assertThat(Factory.getSecurityProvider("PKCS12", params), is(nullValue()));
+ }
private String cleanupString(String str) {
String[] lines = str.split("\n", 0);
return join("", rawLines);
}
- /**
+ /**
* Note: String.join is not part of JDK 7, which is what we compile to for CADI
*/
private String join(String delim, List<String> rawLines) {
}
return sb.toString();
}
-
+
private void writeToFile(File file, String contents, String header) throws Exception {
PrintWriter writer = new PrintWriter(file, "UTF-8");
if (header != null) {
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.cm.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.*;
+import org.mockito.*;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.cm.PlaceArtifactInFiles;
+import org.onap.aaf.misc.env.Trans;
+
+import certman.v1_0.Artifacts.Artifact;
+import certman.v1_0.CertInfo;
+
+public class JU_PlaceArtifactInFiles {
+
+ @Mock private Trans transMock;
+ @Mock private CertInfo certInfoMock;
+ @Mock private Artifact artiMock;
+
+ private static final String dirName = "src/test/resources/artifacts";
+ private static final String nsName = "org.onap.test";
+ private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life
+
+ private List<String> certs;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ certs = new ArrayList<>();
+ certs.add("cert1");
+ certs.add("cert2");
+
+ when(certInfoMock.getChallenge()).thenReturn(luggagePassword);
+ when(certInfoMock.getCerts()).thenReturn(certs);
+
+ when(artiMock.getDir()).thenReturn(dirName);
+ when(artiMock.getNs()).thenReturn(nsName);
+ }
+
+ @AfterClass
+ public static void tearDownOnce() {
+ cleanup();
+ PlaceArtifactInFiles.clear();
+ }
+
+ @Test
+ public void test() throws CadiException {
+ PlaceArtifactInFiles placer = new PlaceArtifactInFiles();
+ placer.place(transMock, certInfoMock, artiMock, "machine");
+ assertThat(placer._place(transMock, certInfoMock, artiMock), is(true));
+ assertThat(new File(dirName + '/' + nsName + ".crt").exists(), is(true));
+ assertThat(new File(dirName + '/' + nsName + ".key").exists(), is(true));
+
+ when(certInfoMock.getCerts()).thenReturn(null);
+ try {
+ placer._place(transMock, certInfoMock, artiMock);
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+ }
+
+ private static void cleanup() {
+ File dir = new File(dirName);
+ if (dir.exists()) {
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.cm.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import java.security.cert.CertificateException;
+
+import org.junit.*;
+import org.mockito.*;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.cm.PlaceArtifactInKeystore;
+import org.onap.aaf.misc.env.Env;
+import org.onap.aaf.misc.env.TimeTaken;
+import org.onap.aaf.misc.env.Trans;
+
+import certman.v1_0.Artifacts.Artifact;
+import certman.v1_0.CertInfo;
+
+public class JU_PlaceArtifactInKeystore {
+
+ @Mock private Trans transMock;
+ @Mock private CertInfo certInfoMock;
+ @Mock private Artifact artiMock;
+
+ private static final String caName = "onap";
+ private static final String dirName = "src/test/resources/artifacts";
+ private static final String nsName = "org.onap.test";
+ private static final String mechID = "m12345";
+ private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life
+
+ private static String privateKeyString;
+ private static String x509Chain;
+ private static String x509String;
+
+ private List<String> certs;
+
+ @Before
+ public void setup() throws FileNotFoundException, IOException, CertificateException {
+ MockitoAnnotations.initMocks(this);
+
+ x509Chain = fromFile(new File("src/test/resources/cert.pem"));
+ x509String = fromFile(new File("src/test/resources/exampleCertificate.cer"));
+ privateKeyString = fromFile(new File("src/test/resources/key.pem"));
+
+ certs = new ArrayList<>();
+
+ when(certInfoMock.getChallenge()).thenReturn(luggagePassword);
+ when(certInfoMock.getCerts()).thenReturn(certs);
+
+ when(artiMock.getCa()).thenReturn(caName);
+ when(artiMock.getDir()).thenReturn(dirName);
+ when(artiMock.getNs()).thenReturn(nsName);
+ when(artiMock.getMechid()).thenReturn(mechID);
+
+ when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString);
+
+ when(transMock.start("Reconstitute Private Key", Env.SUB)).thenReturn(mock(TimeTaken.class));
+ }
+
+ @AfterClass
+ public static void tearDownOnce() {
+ cleanup();
+ PlaceArtifactInKeystore.clear();
+ }
+
+ @Test
+ public void test() throws CadiException {
+ // Note: PKCS12 can't be tested in JDK 7 and earlier. Can't handle Trusting Certificates.
+ PlaceArtifactInKeystore placer = new PlaceArtifactInKeystore("jks");
+
+ certs.add(x509String);
+ certs.add(x509Chain);
+ assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true));
+ for (String ext : new String[] {"chal", "keyfile", "jks", "props", "trust.jks"}) {
+ assertThat(new File(dirName + '/' + nsName + '.' + ext).exists(), is(true));
+ }
+
+ // coverage
+ assertThat(placer.place(transMock, certInfoMock, artiMock, "machine"), is(true));
+
+ when(certInfoMock.getCerts()).thenReturn(null);
+ try {
+ placer._place(transMock, certInfoMock, artiMock);
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+
+ }
+
+ private static void cleanup() {
+ File dir = new File(dirName);
+ if (dir.exists()) {
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+ }
+
+ public String fromFile(File file) throws IOException {
+ BufferedReader br = new BufferedReader(new FileReader(file));
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ String line;
+ baos.write(br.readLine().getBytes());
+ // Here comes the hacky part
+ baos.write("\n".getBytes());
+ while((line=br.readLine())!=null) {
+ if(line.length()>0) {
+ baos.write(line.getBytes());
+ baos.write("\n".getBytes());
+ }
+ }
+ br.close();
+ return baos.toString();
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.cm.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.*;
+import org.mockito.*;
+
+import org.onap.aaf.cadi.cm.PlaceArtifactOnStream;
+import org.onap.aaf.misc.env.LogTarget;
+import org.onap.aaf.misc.env.Trans;
+
+import certman.v1_0.Artifacts.Artifact;
+import certman.v1_0.CertInfo;
+
+public class JU_PlaceArtifactOnStream {
+
+ @Mock private Trans transMock;
+ @Mock private CertInfo certInfoMock;
+ @Mock private Artifact artiMock;
+
+ private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life
+ private static final String privateKeyString = "I'm a private key!";
+
+ private ByteArrayOutputStream outStream;
+
+ private List<String> certs;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ certs = new ArrayList<>();
+ certs.add("cert1");
+ certs.add("cert2");
+
+ when(certInfoMock.getChallenge()).thenReturn(luggagePassword);
+ when(certInfoMock.getCerts()).thenReturn(certs);
+ when(certInfoMock.getPrivatekey()).thenReturn(privateKeyString);
+
+ outStream = new ByteArrayOutputStream();
+ }
+
+ @Test
+ public void test() {
+ PlaceArtifactOnStream placer = new PlaceArtifactOnStream(new PrintStream(outStream));
+ placer.place(transMock, certInfoMock, artiMock, "machine");
+
+ String[] output = outStream.toString().split("\n", 0);
+
+ String[] expected = {
+ "Challenge: " + luggagePassword,
+ "PrivateKey:",
+ privateKeyString,
+ "Certificate Chain:",
+ "cert1",
+ "cert2"
+ };
+
+ assertThat(output.length, is(expected.length));
+ for (int i = 0; i < output.length; i++) {
+ assertThat(output[i], is(expected[i]));
+ }
+
+ // coverage
+ when(certInfoMock.getNotes()).thenReturn("");
+ placer.place(transMock, certInfoMock, artiMock, "machine");
+
+ when(certInfoMock.getNotes()).thenReturn("Some Notes");
+ when(transMock.info()).thenReturn(mock(LogTarget.class));
+ placer.place(transMock, certInfoMock, artiMock, "machine");
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.cm.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.io.File;
+
+import org.junit.*;
+import org.mockito.*;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.cm.PlaceArtifactScripts;
+import org.onap.aaf.misc.env.Trans;
+
+import certman.v1_0.Artifacts.Artifact;
+import certman.v1_0.CertInfo;
+
+public class JU_PlaceArtifactScripts {
+
+ @Mock private Trans transMock;
+ @Mock private CertInfo certInfoMock;
+ @Mock private Artifact artiMock;
+
+ private static final String dirName = "src/test/resources/artifacts";
+ private static final String nsName = "org.onap.test";
+ private static final String luggagePassword = "12345"; // That's the stupidest combination I've ever heard in my life
+ private static final String notification = "A notification";
+ private static final String osUser = "user"; // That's the stupidest combination I've ever heard in my life
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ when(artiMock.getDir()).thenReturn(dirName);
+ when(artiMock.getNs()).thenReturn(nsName);
+ when(artiMock.getNotification()).thenReturn(notification);
+ when(artiMock.getOsUser()).thenReturn(osUser);
+
+ when(certInfoMock.getChallenge()).thenReturn(luggagePassword);
+ }
+
+ @AfterClass
+ public static void tearDownOnce() {
+ cleanup();
+ PlaceArtifactScripts.clear();
+ }
+
+ @Test
+ public void test() throws CadiException {
+ PlaceArtifactScripts placer = new PlaceArtifactScripts();
+ placer.place(transMock, certInfoMock, artiMock, "machine");
+
+ assertThat(new File(dirName + '/' + nsName + ".crontab.sh").exists(), is(true));
+ assertThat(new File(dirName + '/' + nsName + ".check.sh").exists(), is(true));
+
+ //coverage
+ when(artiMock.getNotification()).thenReturn("mailto: " + notification);
+ placer.place(transMock, certInfoMock, artiMock, "machine");
+ }
+
+ private static void cleanup() {
+ File dir = new File(dirName);
+ if (dir.exists()) {
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+ }
+
+}
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
+import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.security.Principal;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import org.onap.aaf.cadi.aaf.v2_0.AAFLurPerm;
import org.onap.aaf.cadi.aaf.v2_0.AAFTaf;
import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.config.SecurityInfoC;
import org.onap.aaf.cadi.locator.DNSLocator;
import org.onap.aaf.cadi.principal.CachedBasicPrincipal;
};
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ Field field = SecurityInfoC.class.getDeclaredField("sicMap");
+ field.setAccessible(true);
+ field.set(null, new HashMap<Class<?>,SecurityInfoC<?>>());
+ }
+
private static int index = -1;
private synchronized Principal getIndex() {
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.oauth.test;
+
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.any;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.oauth.OAuth2HttpTaf;
+import org.onap.aaf.cadi.oauth.OAuth2Principal;
+import org.onap.aaf.cadi.oauth.TokenMgr;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.cadi.Taf.LifeForm;
+import org.onap.aaf.cadi.client.Result;
+
+public class JU_OAuth2HttpTaf {
+
+ private static final String authz = "Bearer John Doe";
+
+ @Mock private TokenMgr tmgrMock;
+ @Mock private HttpServletResponse respMock;
+ @Mock private HttpServletRequest reqMock;
+ @Mock private OAuth2Principal princMock;
+
+ private PropAccess access;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() throws APIException, CadiException, LocatorException {
+ OAuth2HttpTaf taf = new OAuth2HttpTaf(access, tmgrMock);
+
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+ when(reqMock.getHeader("Authorization")).thenReturn(authz);
+
+ doReturn(Result.ok(200, princMock)).when(tmgrMock).toPrincipal(anyString(), (byte[])any());
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ when(reqMock.isSecure()).thenReturn(true);
+
+ doReturn(Result.err(404, "not found")).when(tmgrMock).toPrincipal(anyString(), (byte[])any());
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ taf.revalidate(null, null);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.oauth.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.oauth.OAuth2HttpTafResp;
+import org.onap.aaf.cadi.oauth.OAuth2Principal;
+import org.onap.aaf.cadi.principal.TrustPrincipal;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+
+public class JU_OAuth2HttpTafResp {
+
+ private static final String description = "description";
+
+ @Mock private TrustPrincipal princMock;
+ @Mock private OAuth2Principal oauthMock;
+ @Mock private HttpServletResponse respMock;
+
+ private PropAccess access;
+
+ private RESP status;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ status = RESP.NO_FURTHER_PROCESSING;
+ }
+
+ @Test
+ public void test() throws IOException {
+ OAuth2HttpTafResp resp = new OAuth2HttpTafResp(access, princMock, description, status, respMock);
+ resp = new OAuth2HttpTafResp(access, oauthMock, description, status, respMock, true);
+ assertThat(resp.isFailedAttempt(), is(true));
+ assertThat(resp.isAuthenticated(), is(status));
+ assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.oauth.test;
+
+import static org.mockito.Mockito.when;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.Permission;
+import org.onap.aaf.cadi.aaf.AAFPermission;
+import org.onap.aaf.cadi.oauth.OAuth2Lur;
+import org.onap.aaf.cadi.oauth.OAuth2Principal;
+import org.onap.aaf.cadi.oauth.TokenMgr;
+import org.onap.aaf.cadi.oauth.TokenPerm;
+import org.onap.aaf.cadi.principal.BearerPrincipal;
+
+public class JU_OAuth2Lur {
+
+ private List<AAFPermission> aafPerms;
+ private List<Permission> perms;
+
+ @Mock private TokenMgr tmMock;
+ @Mock private AAFPermission pondMock;
+ @Mock private Principal princMock;
+ @Mock private OAuth2Principal oauthPrincMock;
+ @Mock private BearerPrincipal bearPrincMock;
+ @Mock private TokenPerm tpMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void test() {
+ OAuth2Lur lur = new OAuth2Lur(tmMock);
+ lur.createPerm("testPerm");
+ lur.createPerm("testPerm1|testPerm2|testPerm3");
+
+ assertThat(lur.fish(princMock, pondMock), is(false));
+ assertThat(lur.fish(oauthPrincMock, pondMock), is(false));
+
+ when(oauthPrincMock.tokenPerm()).thenReturn(tpMock);
+ assertThat(lur.fish(oauthPrincMock, pondMock), is(false));
+
+ aafPerms = new ArrayList<>();
+ aafPerms.add(pondMock);
+ aafPerms.add(pondMock);
+ when(tpMock.perms()).thenReturn(aafPerms);
+ when(pondMock.match(pondMock)).thenReturn(false).thenReturn(true);
+ assertThat(lur.fish(oauthPrincMock, pondMock), is(true));
+
+ perms = new ArrayList<>();
+ perms.add(pondMock);
+ perms.add(pondMock);
+ lur.fishAll(oauthPrincMock, perms);
+
+ when(oauthPrincMock.tokenPerm()).thenReturn(null);
+ lur.fishAll(oauthPrincMock, perms);
+
+ assertThat(lur.handlesExclusively(pondMock), is(false));
+
+ assertThat(lur.handles(null), is(false));
+ assertThat(lur.handles(princMock), is(false));
+ assertThat(lur.handles(bearPrincMock), is(false));
+ when(bearPrincMock.getBearer()).thenReturn("not null :)");
+ assertThat(lur.handles(bearPrincMock), is(true));
+
+ lur.destroy();
+ lur.clear(null, null);
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.oauth.test;
+
+import static org.junit.Assert.assertThat;
+import static org.hamcrest.CoreMatchers.is;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.oauth.OAuth2Principal;
+import org.onap.aaf.cadi.oauth.TokenPerm;
+
+public class JU_OAuth2Principal {
+
+ @Mock TokenPerm tpMock;
+
+
+ private static final String username = "username";
+
+ private static final byte[] hash = "hashstring".getBytes();
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ when(tpMock.getUsername()).thenReturn(username);
+ }
+
+ @Test
+ public void test() {
+ OAuth2Principal princ = new OAuth2Principal(tpMock, hash);
+ assertThat(princ.getName(), is(username));
+ assertThat(princ.tokenPerm(), is(tpMock));
+ assertThat(princ.tag(), is("OAuth"));
+ assertThat(princ.personalName(), is(username));
+ }
+
+}
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
+import java.lang.reflect.Field;
import java.net.ConnectException;
import java.util.Date;
import java.util.GregorianCalendar;
+import java.util.HashMap;
import org.junit.After;
import org.junit.AfterClass;
import org.onap.aaf.cadi.client.Result;
import org.onap.aaf.cadi.client.Retryable;
import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.config.SecurityInfoC;
import org.onap.aaf.cadi.oauth.TimedToken;
import org.onap.aaf.cadi.oauth.TokenClient;
import org.onap.aaf.cadi.oauth.TokenClientFactory;
@AfterClass
public static void tearDownAfterClass() throws Exception {
+ Field field = SecurityInfoC.class.getDeclaredField("sicMap");
+ field.setAccessible(true);
+ field.set(null, new HashMap<Class<?>,SecurityInfoC<?>>());
}
@Before
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.oauth.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.mockito.Mockito.when;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.oauth.TimedToken;
+import org.onap.aaf.cadi.persist.Persist;
+
+import aafoauth.v2_0.Token;
+
+public class JU_TimedToken {
+
+ private static final byte[] hash = "hashstring".getBytes();
+
+ private static final int expires = 10000;
+
+ private Path path;
+
+ @Mock private Persist<Token, ?> persistMock;
+ @Mock private Token tokenMock;
+
+ @Before
+ public void setup() throws IOException {
+ MockitoAnnotations.initMocks(this);
+
+ when(tokenMock.getExpiresIn()).thenReturn(expires);
+ path = Files.createTempFile("fake", ".txt");
+ }
+
+ @Test
+ public void test() {
+ int actuallyExpires = ((int)(System.currentTimeMillis() / 1000)) + expires;
+ TimedToken ttoken = new TimedToken(persistMock, tokenMock, hash, path);
+
+ assertThat(ttoken.get(), is(tokenMock));
+ assertThat(ttoken.checkSyncTime(), is(true));
+ assertThat(ttoken.checkReloadable(), is(false));
+ assertThat(ttoken.hasBeenTouched(), is(false));
+ assertThat(Math.abs(ttoken.expires() - actuallyExpires) < 10, is(true));
+ assertThat(ttoken.expired(), is(false));
+
+ assertThat(ttoken.match(hash), is(true));
+ assertThat(ttoken.getHash(), is(hash));
+
+ assertThat(ttoken.path(), is(path));
+
+ assertThat(ttoken.count(), is(0));
+ ttoken.inc();
+ assertThat(ttoken.count(), is(1));
+ ttoken.clearCount();
+ assertThat(ttoken.count(), is(0));
+ }
+
+}
* Licensed 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.
package org.onap.aaf.cadi.oauth.test;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-import org.junit.*;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import java.io.IOException;
import java.io.StringReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
import org.onap.aaf.cadi.Permission;
+import org.onap.aaf.cadi.oauth.TokenPerm;
import org.onap.aaf.cadi.oauth.TokenPerm.LoadPermissions;
+import org.onap.aaf.cadi.persist.Persist;
+import org.onap.aaf.misc.env.APIException;
import org.onap.aaf.misc.rosetta.ParseException;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
+
+import aaf.v2_0.Perms;
+import aafoauth.v2_0.Introspect;
public class JU_TokenPerm {
+ private static final byte[] hash = "hashstring".getBytes();
+
+ private static final String clientId = "clientId";
+ private static final String username = "username";
+ private static final String token = "token";
+ private static final String scopes = "scopes";
+ private static final String content = "content";
+
+ private static final long expires = 10000L;
+
+ private static Path path;
+
+ @Mock private Persist<Introspect, ?> persistMock;
+ @Mock private RosettaDF<Perms> dfMock;
+ @Mock private Introspect introspectMock;
+
+ @Before
+ public void setup() throws IOException {
+ MockitoAnnotations.initMocks(this);
+
+ when(introspectMock.getExp()).thenReturn(expires);
+ when(introspectMock.getClientId()).thenReturn(clientId);
+ when(introspectMock.getUsername()).thenReturn(username);
+ when(introspectMock.getAccessToken()).thenReturn(token);
+ when(introspectMock.getScope()).thenReturn(scopes);
+ when(introspectMock.getExp()).thenReturn(expires);
+
+ path = Files.createTempFile("fake", ".txt");
+ }
+
+ @Test
+ public void tokenTest() throws APIException {
+ TokenPerm tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path);
+ assertThat(tokenPerm.perms().size(), is(0));
+ assertThat(tokenPerm.getClientId(), is(clientId));
+ assertThat(tokenPerm.getUsername(), is(username));
+ assertThat(tokenPerm.getToken(), is(token));
+ assertThat(tokenPerm.getScopes(), is(scopes));
+ assertThat(tokenPerm.getIntrospect(), is(introspectMock));
+
+ when(introspectMock.getContent()).thenReturn(content);
+ tokenPerm = new TokenPerm(persistMock, dfMock, introspectMock, hash, path);
+ }
+
@Test
public void test() throws ParseException {
String json;
fail(e.getMessage());
}
}
-
+
}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.oauth.test;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.doReturn;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.net.HttpURLConnection;
+import java.net.URI;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.client.Rcli;
+import org.onap.aaf.cadi.client.Retryable;
+import org.onap.aaf.cadi.oauth.TimedToken;
+import org.onap.aaf.cadi.oauth.TzHClient;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.config.SecurityInfoC;
+
+public class JU_TzHClient {
+
+ @Mock private Retryable<Integer> retryableMock;
+ @Mock private TimedToken tokenMock;
+ @Mock private SecurityInfoC<HttpURLConnection> siMock;
+ @Mock private Locator<URI> locMock;
+ @Mock private Item itemMock;
+ @Mock private Rcli<HttpURLConnection> clientMock;
+
+ private PropAccess access;
+
+ private ByteArrayOutputStream errStream;
+
+ private final static String client_id = "id";
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ access.setProperty(Config.CADI_LATITUDE, "38.62"); // St Louis approx lat
+ access.setProperty(Config.CADI_LONGITUDE, "90.19"); // St Louis approx lon }
+
+ errStream = new ByteArrayOutputStream();
+ System.setErr(new PrintStream(errStream));
+ }
+
+ @After
+ public void tearDown() {
+ System.setErr(System.err);
+ }
+
+ @Test
+ public void test() throws CadiException, LocatorException, APIException, IOException {
+ TzHClient client = new TzHClient(access, "tag");
+ try {
+ client.best(retryableMock);
+ fail("Should've thrown an exception");
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is("OAuth2 Token has not been set"));
+ }
+ client.setToken(client_id, tokenMock);
+ when(tokenMock.expired()).thenReturn(true);
+ try {
+ client.best(retryableMock);
+ fail("Should've thrown an exception");
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is("Expired Token"));
+ }
+
+ client = new TzHClient(access, siMock, locMock);
+ when(tokenMock.expired()).thenReturn(false);
+ doReturn(clientMock).when(retryableMock).lastClient();
+
+ when(retryableMock.item()).thenReturn(itemMock);
+ client.setToken(client_id, tokenMock);
+ assertThat(client.best(retryableMock), is(nullValue()));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.persist.test;
+
+import static org.junit.Assert.assertThat;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Matchers.any;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.file.Path;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.client.Holder;
+import org.onap.aaf.cadi.client.Result;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.persist.Persist;
+import org.onap.aaf.cadi.persist.Persist.Loader;
+import org.onap.aaf.cadi.persist.Persistable;
+import org.onap.aaf.cadi.persist.Persisting;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
+import org.onap.aaf.misc.rosetta.env.RosettaData;
+import org.onap.aaf.misc.rosetta.env.RosettaEnv;
+
+public class JU_Persist {
+
+ private static final String resourceDirString = "src/test/resources";
+ private static final String tokenDirString = "tokenDir";
+ private static final String key = "key";
+
+ private static final int data = 5;
+
+ private static final byte[] cred = "password".getBytes();
+
+ private PropAccess access;
+ private Result<Persistable<Integer>> result;
+
+ @Mock private RosettaEnv envMock;
+ @Mock private Persist<Integer, ?> persistMock;
+ @Mock private RosettaDF<Integer> dfMock;
+ @Mock private RosettaData<Integer> dataMock;
+ @Mock private Persistable<Integer> ctMock1;
+ @Mock private Persisting<Integer> ctMock2;
+ @Mock private Loader<Persistable<Integer>> loaderMock;
+
+ @Before
+ public void setup() throws APIException, CadiException, LocatorException {
+ MockitoAnnotations.initMocks(this);
+
+ doReturn(dfMock).when(envMock).newDataFactory((Class<?>[]) any());
+ when(dfMock.newData()).thenReturn(dataMock);
+ when(dataMock.load(data)).thenReturn(dataMock);
+
+
+ result = Result.ok(200, ctMock1);
+ when(loaderMock.load(key)).thenReturn(result);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString);
+ }
+
+ @After
+ public void tearDown() {
+ File dir = new File(resourceDirString + '/' + tokenDirString);
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+
+ @Test
+ public void test() throws CadiException, APIException, LocatorException, InterruptedException {
+ Persist<Integer, Persistable<Integer>> persist = new PersistStub(access, envMock, null, tokenDirString);
+ // Second call for coverage
+ persist = new PersistStub(access, envMock, null, tokenDirString);
+ assertThat(persist.getDF(), is(dfMock));
+ persist.put(key, ctMock2);
+ Result<Persistable<Integer>> output = persist.get(key, cred, loaderMock);
+ assertThat(output.code, is(200));
+ assertThat(output.isOK(), is(true));
+
+ when(ctMock2.checkSyncTime()).thenReturn(true);
+ when(ctMock2.hasBeenTouched()).thenReturn(true);
+ output = persist.get(key, cred, loaderMock);
+ assertThat(output.code, is(200));
+ assertThat(output.isOK(), is(true));
+
+ persist.delete(key);
+
+ assertThat(persist.get(null, null, null), is(nullValue()));
+
+ // Uncommenting this lets us begin to test the nested Clean class, but
+ // will dramatically slow down every build that runs tests - We need to
+ // either refactor or find a more creative way to test Clean
+// Thread.sleep(25000);
+
+ persist.close();
+ }
+
+ private class PersistStub extends Persist<Integer, Persistable<Integer>> {
+ public PersistStub(Access access, RosettaEnv env, Class<Integer> cls, String sub_dir)
+ throws CadiException, APIException { super(access, env, cls, sub_dir); }
+ @Override
+ protected Persistable<Integer> newCacheable(Integer t, long expires_secsFrom1970, byte[] hash, Path path)
+ throws APIException, IOException { return null; }
+ @Override
+ public<T> Path writeDisk(final RosettaDF<T> df, final T t, final byte[] cred, final Path target, final long expires) throws CadiException {
+ return null;
+ }
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T readDisk(final RosettaDF<T> df, final byte[] cred, final String filename,final Holder<Path> hp, final Holder<Long> hl) throws CadiException {
+ return (T)new Integer(data);
+ }
+
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.persist.test;
+
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.mockito.Mockito.when;
+import static org.mockito.Matchers.any;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+
+import javax.crypto.CipherInputStream;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.client.Holder;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.persist.PersistFile;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
+import org.onap.aaf.misc.rosetta.env.RosettaData;
+
+public class JU_PersistFile {
+
+ private static final String resourceDirString = "src/test/resources";
+ private static final String tokenDirString = "tokenDir";
+ private static final String tokenFileName = "token";
+
+ private static final int data = 5;
+ private static final long expires = 10000;
+
+ private static final byte[] cred = "password".getBytes();
+
+ private PropAccess access;
+ private Holder<Path> hp = new Holder<Path>(null);
+ private Holder<Long> hl = new Holder<Long>(null);
+
+ @Mock private RosettaDF<Integer> dfMock;
+ @Mock private RosettaData<Integer> dataMock;
+ @Mock private Holder<Path> hpMock;
+
+ @Before
+ public void setup() throws APIException {
+ MockitoAnnotations.initMocks(this);
+
+ when(dfMock.newData()).thenReturn(dataMock);
+ when(dataMock.load(data)).thenReturn(dataMock);
+ when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString);
+ }
+
+ @After
+ public void tearDown() {
+ File dir = new File(resourceDirString + '/' + tokenDirString);
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+
+ @Test
+ public void test() throws CadiException, APIException, IOException {
+ PersistFile persistFile = new PersistFile(access, tokenDirString);
+ // Second call is for coverage
+ persistFile = new PersistFile(access, tokenDirString);
+ Path filepath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires);
+ persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl);
+ assertThat(persistFile.readExpiration(filepath), is(expires));
+
+ FileTime ft1 = persistFile.getFileTime(tokenFileName, hp);
+ FileTime ft2 = persistFile.getFileTime(tokenFileName, hpMock);
+ assertThat(ft1.toMillis(), is(ft2.toMillis()));
+
+ persistFile.deleteFromDisk(filepath);
+ persistFile.deleteFromDisk(resourceDirString + '/' + tokenDirString + '/' + tokenFileName);
+ assertThat(persistFile.readExpiration(filepath), is(0L));
+
+ persistFile.getPath(resourceDirString + '/' + tokenDirString + '/' + tokenFileName);
+
+ persistFile.writeDisk(dfMock, data, null, tokenFileName, expires);
+ try {
+ persistFile.readDisk(dfMock, cred, tokenFileName, hp, hl);
+ fail("Should've thrown an exception");
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is(CadiException.class.getName() + ": Hash does not match in Persistence"));
+ }
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.persist.test;
+
+import static org.junit.Assert.assertThat;
+import static org.hamcrest.CoreMatchers.is;
+import static org.mockito.Mockito.when;
+import static org.mockito.Matchers.any;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import javax.crypto.CipherInputStream;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.persist.Persist;
+import org.onap.aaf.cadi.persist.PersistFile;
+import org.onap.aaf.cadi.persist.Persisting;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
+import org.onap.aaf.misc.rosetta.env.RosettaData;
+
+public class JU_Persisting {
+
+ private static final String resourceDirString = "src/test/resources";
+ private static final String tokenDirString = "tokenDir";
+ private static final String tokenFileName = "token";
+
+ private static final int data = 5;
+ private static final long expires = 10000;
+
+ private static final byte[] cred = "password".getBytes();
+
+ private PropAccess access;
+
+ @Mock private Persist<Integer, ?> persistMock;
+ @Mock private RosettaDF<Integer> dfMock;
+ @Mock private RosettaData<Integer> dataMock;
+
+ @Before
+ public void setup() throws APIException {
+ MockitoAnnotations.initMocks(this);
+
+ when(dfMock.newData()).thenReturn(dataMock);
+ when(dataMock.load(data)).thenReturn(dataMock);
+ when(dataMock.load((CipherInputStream)any())).thenReturn(dataMock);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ access.setProperty(Config.CADI_TOKEN_DIR, resourceDirString);
+
+ persistMock.access = access;
+ }
+
+ @After
+ public void tearDown() {
+ File dir = new File(resourceDirString + '/' + tokenDirString);
+ for (File f : dir.listFiles()) {
+ f.delete();
+ }
+ dir.delete();
+ }
+
+ @Test
+ public void test() throws CadiException, APIException {
+ Path tokenPath = Paths.get(resourceDirString, tokenDirString);
+
+ Persisting<Integer> persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath);
+ assertThat(persisting.get(), is(data));
+ assertThat(persisting.expires(), is(expires));
+ assertThat(persisting.expired(), is(true));
+ assertThat(persisting.hasBeenTouched(), is(true));
+
+ PersistFile persistFile = new PersistFile(access, tokenDirString);
+ tokenPath = persistFile.writeDisk(dfMock, data, cred, tokenFileName, expires);
+ persisting = new Persisting<>(persistMock, data, expires, cred, tokenPath);
+ assertThat(persisting.hasBeenTouched(), is(false));
+
+ persisting = new Persisting<>(persistMock, data, expires * (int)10e9, cred, tokenPath);
+ assertThat(persisting.expired(), is(false));
+
+ assertThat(persisting.checkSyncTime(), is(true));
+ assertThat(persisting.checkSyncTime(), is(false));
+
+ assertThat(persisting.checkReloadable(), is(false));
+
+ assertThat(persisting.getHash(), is(cred));
+
+ assertThat(persisting.match(null), is(false));
+ assertThat(persisting.match("random!".getBytes()), is(false));
+ assertThat(persisting.match("passwrod".getBytes()), is(false));
+ assertThat(persisting.match(cred), is(true));
+
+ persisting.clearCount();
+ assertThat(persisting.count(), is(0));
+ persisting.inc();
+ assertThat(persisting.count(), is(1));
+
+ assertThat(persisting.path(), is(tokenPath));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.sso.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.sso.AAFSSO;
+
+public class JU_AAFSSO {
+
+ private static final String resourceDirString = "src/test/resources";
+ private static final String aafDir = resourceDirString + "/aaf";
+
+ private ByteArrayInputStream inStream;
+
+ @Before
+ public void setup() {
+ System.setProperty("user.home", aafDir);
+
+ // Simulate user input
+ inStream = new ByteArrayInputStream("test\npassword".getBytes());
+ System.setIn(inStream);
+ }
+
+ @After
+ public void tearDown() {
+ recursiveDelete(new File(aafDir));
+ }
+
+ @Test
+ public void test() throws IOException, CadiException {
+ AAFSSO sso;
+ String[] args;
+
+ args = new String[] {
+ "-login",
+ "-noexit",
+ };
+ sso = new AAFSSO(args);
+
+ assertThat(new File(aafDir).exists(), is(true));
+ assertThat(new File(aafDir + "/.aaf").exists(), is(true));
+ assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(true));
+ assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true));
+ assertThat(sso.loginOnly(), is(true));
+
+ assertThat(new File(aafDir + "/.aaf/sso.props").exists(), is(false));
+ sso.writeFiles();
+ assertThat(new File(aafDir + "/.aaf/sso.props").exists(), is(true));
+
+ sso.setLogDefault();
+ sso.setStdErrDefault();
+
+ inStream.reset();
+ args = new String[] {
+ "-logout",
+ "\\*",
+ "-noexit",
+ };
+ sso = new AAFSSO(args);
+
+ assertThat(new File(aafDir).exists(), is(true));
+ assertThat(new File(aafDir + "/.aaf").exists(), is(true));
+ assertThat(new File(aafDir + "/.aaf/keyfile").exists(), is(true));
+ assertThat(new File(aafDir + "/.aaf/sso.out").exists(), is(true));
+ assertThat(sso.loginOnly(), is(false));
+
+ PropAccess access = sso.access();
+ assertThat(sso.enc_pass(), is(access.getProperty(Config.AAF_APPPASS)));
+ assertThat(sso.user(), is(access.getProperty(Config.AAF_APPID)));
+
+ sso.addProp("key", "value");
+ assertThat(sso.err(), is(nullValue()));
+
+ assertThat(sso.useX509(), is(false));
+
+ sso.close();
+ sso.close();
+ }
+
+ private void recursiveDelete(File file) {
+ for (File f : file.listFiles()) {
+ if (f.isDirectory()) {
+ recursiveDelete(f);
+ }
+ f.delete();
+ }
+ file.delete();
+ }
+
+}
import java.io.StringReader;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.*;
import org.onap.aaf.misc.rosetta.env.RosettaDF;
import org.onap.aaf.misc.rosetta.env.RosettaData;
import org.onap.aaf.misc.rosetta.env.RosettaEnv;
import aaf.v2_0.Error;
-public class JU_Content {
-
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- }
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- }
+// TODO: This test doesn't really do anything. It should be deleted as soon as coverage is above 50%
+public class JU_Content {
@Test
public void parseErrorJSON() throws Exception {
errDF.out(RosettaData.TYPE.JSON);
RosettaData<Error> data = errDF.newData();
data.load(err);
- System.out.println(data.asString());
+
+ @SuppressWarnings("unused")
+ String output = data.asString();
+// System.out.println(output);
data.load(new StringReader(msg));
err = data.asObject();
- System.out.println(err.getText());
+ output = err.getText();
+// System.out.println(output);
}
--- /dev/null
+-----BEGIN CERTIFICATE-----
+MIIFqzCCA5OgAwIBAgIJAKR74mLLmqGoMA0GCSqGSIb3DQEBCwUAMGwxCzAJBgNV
+BAYTAlVTMREwDwYDVQQIDAhNaXNzb3VyaTERMA8GA1UEBwwIU3QgTG91aXMxETAP
+BgNVBAoMCEZha2UgT3JnMREwDwYDVQQLDAhmYWtlLm9yZzERMA8GA1UEAwwISm9o
+biBEb2UwHhcNMTgwNTAzMjEwMzEzWhcNMTgwNjAyMjEwMzEzWjBsMQswCQYDVQQG
+EwJVUzERMA8GA1UECAwITWlzc291cmkxETAPBgNVBAcMCFN0IExvdWlzMREwDwYD
+VQQKDAhGYWtlIE9yZzERMA8GA1UECwwIZmFrZS5vcmcxETAPBgNVBAMMCEpvaG4g
+RG9lMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvfadEz8rdI3Q6LsA
+3e4cPYGkYkty7gyVmD52DYxQYsrykJewI4iqJ+jZb2kfEYjz5Tw3hAi1cw2Db5Vr
+2yB3GLR9lk6Eryj1/tDEVXrWDJpXPSEKcyLDzvsLEXi6ZabVZbSzX41/YSct1Hn/
+ucHo2oFtKz6GLVQ0Jb5dp5sQiV8KDdrj2+KDRkQR6WeEY5a89wAwcoYEOlIXx6+4
+jurhUzdvyRiXFxEl2B20IGDQ0byEUnbXEgcCDBJVNyU+dxXMSLHcxFNKEjhaYcn1
+29nEzStfEV8NuxqiE7TCZNUCy2BAMxd9k4kmZ4Tb6tOyza+fEUBu4BLBywusyeVb
+D/mupHyG6K/xyMAVmSqGYVjweEFX+UkITHsvkZS2+Iizjt1x658RuLcI8YvEHPbm
+lU+wirNoc/1wOxR3V53ZSjqnghLql8TUDVH7ysp+khthiJnr26fRSZNSkNBbNhax
+FkC9UYuVuoHscUjsRzX0RkELo4OJG6n11SUyB0K9WLI6b33yfBXFOpOXByavvjkS
+BZM7pNOG77GSz/uCaQ/glE7PSnDx1AzGWGdv9YqKAFU6lEMdw2HCozzc2aX/GXPW
+hvh2Hjvt2ZKJc87DVvLsdySQwsJ05YF71kxMmxqnwqnD5/h0pMjxThyDm7DfaGek
+9gAw7nqCOQJbvafl8ZnKFKnAI/0CAwEAAaNQME4wHQYDVR0OBBYEFFn1zEUXwHY2
+odqzPA0BTkoBqTzWMB8GA1UdIwQYMBaAFFn1zEUXwHY2odqzPA0BTkoBqTzWMAwG
+A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIBADWOO+YOdwIL0Wdws89s2h1I
+TAN2glpQNDcwiMlT5VISqrb4R5oGYQuc7eR3X6fUArZwo38QW2C5+A4gXCUmy+UE
+Hyneac+RXTxD29Glxn14dt174VsJ7mlFxkOd7ft8beaRhga5DAot6HyjJwS2K8GP
+cNoM9zJFbJcRjs4oO93fOdp5M3mOOcwMbfQLZIFUx93Y7cn3Uoyz/Yfws/KKuY9r
+faUGNB9bSSZc+aM7ZLorMwDb45Beu443czUfzOhWLxiDK9pqwY9k7DV4x4ahvPhx
+OiRl31ksL/esCc4G2oOe9wATh1gwnIDJWE1bgNepKwjqinlWRQqq7JcRbpXyQ2t0
+0v0P60cVcIMO6iCuCvKO4wZh5nUrHQlTfHfWDyH5UN2nUa12BpOidvgp5AzuVG6e
+pIYbRViwdOzEOAKOlHCuZN/rFkQAmi6baz4/7JV9GeW92xZyDc9GGM/JQY3lMRfw
+ablgXEuJFJGVQkO6/LkqcEvFpLVcdTeJeWxJvR9lwJJX1NXTQN91aFqLznc50idK
+UiKjE+3eBG/S64htp48+a6xi2r6uujRl/VAOoTjunGuSvDdmThlwnnlnp4iqcm7k
+m4nB2/4SvSzQ8r4cUl0sFCZ7OLW8WM4dpZcfklk7ApZ4TFTMzUi4zUtCk4Vfdxbm
+MX+3SmP+Pjf0p+1DtdhM
+-----END CERTIFICATE-----
--- /dev/null
+-----BEGIN PRIVATE KEY-----
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQC99p0TPyt0jdDo
+uwDd7hw9gaRiS3LuDJWYPnYNjFBiyvKQl7AjiKon6NlvaR8RiPPlPDeECLVzDYNv
+lWvbIHcYtH2WToSvKPX+0MRVetYMmlc9IQpzIsPO+wsReLplptVltLNfjX9hJy3U
+ef+5wejagW0rPoYtVDQlvl2nmxCJXwoN2uPb4oNGRBHpZ4Rjlrz3ADByhgQ6UhfH
+r7iO6uFTN2/JGJcXESXYHbQgYNDRvIRSdtcSBwIMElU3JT53FcxIsdzEU0oSOFph
+yfXb2cTNK18RXw27GqITtMJk1QLLYEAzF32TiSZnhNvq07LNr58RQG7gEsHLC6zJ
+5VsP+a6kfIbor/HIwBWZKoZhWPB4QVf5SQhMey+RlLb4iLOO3XHrnxG4twjxi8Qc
+9uaVT7CKs2hz/XA7FHdXndlKOqeCEuqXxNQNUfvKyn6SG2GImevbp9FJk1KQ0Fs2
+FrEWQL1Ri5W6gexxSOxHNfRGQQujg4kbqfXVJTIHQr1YsjpvffJ8FcU6k5cHJq++
+ORIFkzuk04bvsZLP+4JpD+CUTs9KcPHUDMZYZ2/1iooAVTqUQx3DYcKjPNzZpf8Z
+c9aG+HYeO+3ZkolzzsNW8ux3JJDCwnTlgXvWTEybGqfCqcPn+HSkyPFOHIObsN9o
+Z6T2ADDueoI5Alu9p+XxmcoUqcAj/QIDAQABAoICADRkPuAfDQIhVtvJL60Fzd4c
+0lSV0IXdDKknmPGVoFoO9SVx4I98UsmdC9MRYBM6/WFc4UbWDA1GTdjJkiymYJJ8
+vSJmV2vj1SzJMU0OCtkA/EyMv1AP54c/b8cK0AXXJIXfd5VD9jy6TIaMez4lP+57
+wbsqjGEWFyfNwBDI0J/CiYhWtX9gkqofff0sorPA0C8jazk6wxG+sHZPfYxVNX35
+DSieUpV3EkPvtU00xoMCBlCkHB8JtcPUjpIeAINhjK0D+Qpgmk46IptT0y4meoPH
+kXm+CJBxAQCEWxTqNtIWor40nVrCecgVOX4jku3toOZmKe483hv9BVPNoPbf+w1C
+5PI8eLCVeKp10dhSP9+HsKhwENqac/pF4RISnf5St0hccdyzHlwyRXVY2UJDd8Ik
+Hv4zh3iSzuhd5ar4Pgpwvl/9dsJBDQtxf2RgBMLlf9TbIaFTA+Q55Ir/+BsaCxkr
+Uz+bk00cF2nrUU7cqu0TXzsOCmCq02Oc4ELZ3zXGu1t2EjeIkAatbrCTigdiGimj
+gpB5bSRUNKyu9lQgHP/XIiWeiYmRb1I9j2ICxbvdZm5Kj5o2/6i9vy4ouCvd9qF3
+IdK2/U+sBF6XFKvGMzRC3giID+PYSqMcoBybuUzWgfKLu3WMpuhnPKPtorokc7d7
+M3+Wc7UfSbQUn2JY/2wBAoIBAQDjLLIaFLkbfg6HMQu/JPspLibYzAXbGRw+SJj5
+vkqVmlPFj2pNpEFHLHdN7gmmKxmq3crTL47g3XoOAI4vk5obpO5ICtrsXF/OSL4a
+MAm63wvY+KiIUAhRTNzu53xjQ+PwaG1A7VghkPeAtk/HCI2vqJH7UoLWUcR7abUL
+gCILuGnxk7QnjJNWoD6pJ6RV4vnkRx/2cZO+rYE6Wm2kBeaNoW/aEKXYYBsAty2E
+/dJ1GkEm4x59+R43Lu665GTaDKJPItxTyv7QpKvWbdPUab8g5YdA12p2//HrLCb3
+yMBedxys2VDpaIBSN6INi/6BMCRMtoDdol1gzHm2/dlMWuD9AoIBAQDWES+VNosh
+MkLsPcAp1Psq0+ucQCWpyAMgpgkN0SbBJDcMR+xqrmrxunOWuFeWg5A48xiCQNdW
+uA8X6X3TWGsFaNyFD5BNPl1WncmzwtqTCjqgn/EDdTWS40eLFZJMxBf0infjPMFS
+dkrIcbLOHb56miBf+CnMZ1uEmwo0h2epwkaU6Kk1wm3X8bojUVGzY5O5x8AJzDeP
+EC4hmC34FnPu19LRNT/29vzX5X8mLuy7RYcdzCy9ut//G+m+OVoMImvTI6cxLN0v
+zcJyJmrYoR9yVfHjcUA43CgkCSqIlVPSYIvBFLL/O9ZZspfZqAERYcCFT38uAtF/
+nPfuTk6mUz8BAoIBABGkzQhdh6rs9W/mjUUBOEiQfw/jeKj1oE3uEYOEFgLcg5ka
+dGUnVrKSb4mr7S/stQeiRjh0vyIT0YD45hIn4pY3DxKlVS96VS6OU8Vw6bCL1j25
+wk0j+iFmWNptPCnxgeiQE7wxMuEYg0CJ6FRLA8Yaz4u3ctX2b84t/ZOxFfPXFNNg
+Z2OS9XaK55L3sznAcSwbog3f8Fuk2h6QG2fb1XY2jZtgI6FUhYRetbhYhln1+g1t
+IlciXAhpKr11M6gDxy9iQ752S6gkwfvbd9JNjDyf1wtgL7KiWkWrnjMsclRj5+Q8
+1J3sMdsw2vM2ZkPeW1Nh8UxFaf80oldmC9R0UnkCggEAbmLwWY6F0jl73xy8shWc
+62najnlZsqJsUnKsKo7W4DQPmuqf1CdbCInwPyGSMRBo16Ur10cehB5n0hnag5iN
+n32Cca8j52EoepjlQShS1A4rS1cOzoyrcrJ22xblmWZpP/YDeo+C1UYgrBpNbRJT
+fh9qYHK1Ay2tOMVGTu4gG58ODI2pbAp14CxLoxi0+792lw+VTLgdUk2yrCowUkUp
+xVlP4ggGkxCsM5ypo4QBGVTyJwB5deEezwuSzj/+2lEJrxgsiCQtbxA4m+qJoGn9
+sFT3ZiSpTGji3ipH36S5U7vrdUZ6QzmVAC4jNd73pgH1aAkleRGE/Lxx8VY6InS9
+AQKCAQEAjUxVkW7ei0XOvz3hzEM8s84StZAzz/OOchxxLIDwWtmrnTRlDCDFNgfn
+kjWggY8ySvEGeeh/Bq1UjZn46yJEnbBaluSlwtpB9/QNlvVESfi72F6qXxPrAb7w
+wvMLFk2abUQk1MUursiC4Xch5Br9wGAQqzPIFNQRlhH3t47ZGyQn9Sc0FONLfPpO
+NR+A0BBvfQG7/fg1JLNcmh9AdQr0gxTUJyR4a32An4IcSQZqCyF7Zzr3ERJ3n2tR
+0S0NaYmQEs7sqULnG2f8USc53z5/skAo2OXeOZXmCpY7PH7Zfq85ojnsB/d9rAfm
+43jbRd3vVTO310fh3QIgNQ3tg+u3mg==
+-----END PRIVATE KEY-----
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
}
pi.append(pathinfo);
}
- URL url = new URI(
- uri.getScheme(),
- uri.getUserInfo(),
- uri.getHost(),
- uri.getPort(),
- pi==null?uri.getPath():pi.toString(),
- query,
- fragment).toURL();
pathinfo=null;
query=null;
fragment=null;
- huc = (HttpURLConnection) url.openConnection();
+ //huc = (HttpURLConnection) url.openConnection();
+ huc = getConnection(uri, pi);
huc.setRequestMethod(meth);
if(ss!=null) {
ss.setSecurity(huc);
return connectTimeout;
}
- public abstract class HFuture<T> extends Future<T> {
+ protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException {
+ URL url = new URI(
+ uri.getScheme(),
+ uri.getUserInfo(),
+ uri.getHost(),
+ uri.getPort(),
+ pi==null?uri.getPath():pi.toString(),
+ query,
+ fragment).toURL();
+ return (HttpURLConnection) url.openConnection();
+ }
+
+ public abstract class HFuture<T> extends Future<T> {
protected HttpURLConnection huc;
protected int respCode;
- protected String respMessage;
protected IOException exception;
protected StringBuilder errContent;
return exception;
}
- public String respMessage() {
- return respMessage;
- }
-
@Override
public String header(String tag) {
return huc.getHeaderField(tag);
public String body() {
if (errContent != null) {
return errContent.toString();
-
- } else if (respMessage != null) {
- return respMessage;
}
return "";
}
return value;
} else if (errContent != null) {
return errContent.toString();
- } else if (respMessage != null) {
- return respMessage;
}
return "";
}
}
} else if (errContent != null) {
return errContent.toString();
- } else if (respMessage != null) {
- return respMessage;
}
return "";
}
public String body() {
if (errContent != null) {
return errContent.toString();
- } else if (respMessage != null) {
- return respMessage;
}
return Integer.toString(respCode);
}
@Override
public String body() {
- return errContent==null?respMessage:errContent.toString();
+ return errContent==null?null:errContent.toString();
}
};
}
throw new LocatorException("DNSLocator accepts only https or http protocols. (requested URL " + aaf_locate + ')');
}
- int colon = aaf_locate.indexOf(':',start);
- int slash;
- if(colon>0) {
- start = colon+1;
- int left = aaf_locate.indexOf('[',start);
- if(left>0) {
- int right = aaf_locate.indexOf(']',left+1);
- if(right>0) {
- int dash = aaf_locate.indexOf('-',left+1);
- if(dash<0) {
- startPort = endPort = Integer.parseInt(aaf_locate.substring(left+1,right));
- } else {
- startPort = Integer.parseInt(aaf_locate.substring(left+1,dash));
- endPort = Integer.parseInt(aaf_locate.substring(dash + 1,right));
- }
- }
-
- } else {
- slash = aaf_locate.indexOf('/',colon+1);
- if(slash<0) {
- startPort = endPort = Integer.parseInt(aaf_locate.substring(start));
- } else {
- startPort = endPort = Integer.parseInt(aaf_locate.substring(start,slash));
- }
- }
- } else {
- startPort = endPort = port;
- }
+ parsePorts(aaf_locate.substring(start), port);
}
@Override
}
return false;
}
+
+ private void parsePorts(String aaf_locate, int defaultPort) throws LocatorException {
+ int slash, start;
+ int colon = aaf_locate.indexOf(':');
+ if(colon > 0) {
+ start = colon + 1;
+ int left = aaf_locate.indexOf('[', start);
+ if(left > 0) {
+ int right = aaf_locate.indexOf(']', left + 1);
+ if (right < 0) {
+ throw new LocatorException("Missing closing bracket in DNSLocator constructor. (requested URL " + aaf_locate + ')');
+ } else if (right == (left + 1)) {
+ throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')');
+ }
+ int dash = aaf_locate.indexOf('-', left + 1);
+ if (dash == (right - 1) || dash == (left + 1)) {
+ throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')');
+ }
+ if(dash < 0) {
+ startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right));
+ } else {
+ startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash));
+ endPort = Integer.parseInt(aaf_locate.substring(dash + 1, right));
+ }
+
+ } else {
+ slash = aaf_locate.indexOf('/', start);
+ if (slash == start) {
+ throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')');
+ }
+ if(slash < 0) {
+ startPort = endPort = Integer.parseInt(aaf_locate.substring(start));
+ } else {
+ startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash));
+ }
+ }
+ } else {
+ startPort = endPort = defaultPort;
+ }
+ }
private class Host {
private URI uri;
* Licensed 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.
import org.onap.aaf.misc.env.util.Split;
/**
- * This Locator is to handle Hot Peer load protection, when the Servers are
+ * This Locator is to handle Hot Peer load protection, when the Servers are
* 1) Static
* 2) Well known client URL
- *
+ *
* The intention is to change traffic over to the Hot Peer, if a server goes down, and reinstate
* when it is back up.
- *
+ *
* Example of this kind of Service is a MS Certificate Server
- *
+ *
* @author Jonathan
*
* @param <CLIENT>
*/
public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> {
- private final String[] urlstrs;
- private final CLIENT[] clients;
- private final long[] failures;
- private final double[] distances;
- private int preferred;
- private long invalidateTime;
- private Thread refreshThread;
- protected Access access;
+ private final String[] urlstrs;
+ private final CLIENT[] clients;
+ private final long[] failures;
+ private final double[] distances;
+ private int preferred;
+ private long invalidateTime;
+ private Thread refreshThread;
+ protected Access access;
- /**
- * Construct: Expect one or more Strings in the form:
- * 192.555.112.223:39/38.88087/-77.30122
- * separated by commas
- *
- * @param trans
- * @param urlstr
- * @param invalidateTime
- * @param localLatitude
- * @param localLongitude
- * @throws LocatorException
- */
- @SuppressWarnings("unchecked")
- protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException {
- this.access = access;
- urlstrs = Split.split(',', urlstr);
- clients = (CLIENT[])new Object[urlstrs.length];
- failures = new long[urlstrs.length];
- distances= new double[urlstrs.length];
- this.invalidateTime = invalidateTime;
-
- double distance = Double.MAX_VALUE;
- for(int i=0;i<urlstrs.length;++i) {
- String[] info = Split.split('/', urlstrs[i]);
- if(info.length<3) {
- throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long");
- }
- try {
- clients[i] = _newClient(urlstrs[i]);
- failures[i] = 0L;
- } catch(LocatorException le) {
- failures[i] = System.currentTimeMillis()+invalidateTime;
- }
-
- double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude);
- distances[i]=d;
-
- // find preferred server
- if(d<distance) {
- preferred = i;
- distance=d;
- }
- }
-
- access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]);
- for(int i=0;i<urlstrs.length;++i) {
- if(i!=preferred) {
- access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]);
- }
- }
- }
-
- protected abstract CLIENT _newClient(String hostInfo) throws LocatorException;
- /**
- * If client can reconnect, then return. Otherwise, destroy and return null;
- * @param client
- * @return
- * @throws LocatorException
- */
- protected abstract CLIENT _invalidate(CLIENT client);
-
- protected abstract void _destroy(CLIENT client);
-
- @Override
- public Item best() throws LocatorException {
- if(failures[preferred]==0L) {
- return new HPItem(preferred);
- } else {
- long now = System.currentTimeMillis();
- double d = Double.MAX_VALUE;
- int best = -1;
- boolean tickle = false;
- // try for best existing client
- for(int i=0;i<urlstrs.length;++i) {
- if(failures[i]<now && distances[i]<d) {
- if(clients[i]!=null) {
- best = i;
- break;
- } else {
- tickle = true; // There's some failed clients which can be restored
- }
+ /**
+ * Construct: Expect one or more Strings in the form:
+ * 192.555.112.223:39/38.88087/-77.30122
+ * separated by commas
+ *
+ * @param trans
+ * @param urlstr
+ * @param invalidateTime
+ * @param localLatitude
+ * @param localLongitude
+ * @throws LocatorException
+ */
+ @SuppressWarnings("unchecked")
+ protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException {
+ this.access = access;
+ urlstrs = Split.split(',', urlstr);
+ clients = (CLIENT[])new Object[urlstrs.length];
+ failures = new long[urlstrs.length];
+ distances= new double[urlstrs.length];
+ this.invalidateTime = invalidateTime;
+
+ double distance = Double.MAX_VALUE;
+ for(int i=0;i<urlstrs.length;++i) {
+ String[] info = Split.split('/', urlstrs[i]);
+ if(info.length<3) {
+ throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long");
+ }
+ try {
+ clients[i] = _newClient(urlstrs[i]);
+ failures[i] = 0L;
+ } catch(LocatorException le) {
+ failures[i] = System.currentTimeMillis()+invalidateTime;
+ }
+
+ double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude);
+ distances[i]=d;
+
+ // find preferred server
+ if(d<distance) {
+ preferred = i;
+ distance=d;
+ }
+ }
+
+ access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]);
+ for(int i=0;i<urlstrs.length;++i) {
+ if(i!=preferred) {
+ access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]);
+ }
+ }
+ }
+
+ protected abstract CLIENT _newClient(String hostInfo) throws LocatorException;
+ /**
+ * If client can reconnect, then return. Otherwise, destroy and return null;
+ * @param client
+ * @return
+ * @throws LocatorException
+ */
+ protected abstract CLIENT _invalidate(CLIENT client);
+
+ protected abstract void _destroy(CLIENT client);
+
+ @Override
+ public Item best() throws LocatorException {
+ if(failures[preferred]==0L) {
+ return new HPItem(preferred);
+ } else {
+ long now = System.currentTimeMillis();
+ double d = Double.MAX_VALUE;
+ int best = -1;
+ boolean tickle = false;
+ // try for best existing client
+ for(int i=0;i<urlstrs.length;++i) {
+ if(failures[i]<now && distances[i]<d) {
+ if(clients[i]!=null) {
+ best = i;
+ break;
+ } else {
+ tickle = true; // There's some failed clients which can be restored
}
}
- if(best<0 && tickle) {
- tickle=false;
- if(refresh()) {
- // try again
- for(int i=0;i<urlstrs.length;++i) {
- if(failures[i]==0L && distances[i]<d) {
- if(clients[i]!=null) {
- best = i;
- break;
- }
+ }
+ if(best<0 && tickle) {
+ tickle=false;
+ if(refresh()) {
+ // try again
+ for(int i=0;i<urlstrs.length;++i) {
+ if(failures[i]==0L && distances[i]<d) {
+ if(clients[i]!=null) {
+ best = i;
+ break;
}
}
}
}
-
- /*
- * If a valid client is available, but there are some that can refresh, return the client immediately
- * but start a Thread to do the background Client setup.
- */
- if(tickle) {
- synchronized(clients) {
- if(refreshThread==null) {
- refreshThread = new Thread(new Runnable(){
- @Override
- public void run() {
- refresh();
- refreshThread = null;
- }
- });
- refreshThread.setDaemon(true);
- refreshThread.start();
- }
- }
- }
-
- if(best<0) {
- throw new LocatorException("No Clients available");
- }
-
-
- return new HPItem(best);
}
- }
-
- @Override
- public CLIENT get(Item item) throws LocatorException {
- HPItem hpi = (HPItem)item;
- CLIENT c = clients[hpi.idx];
- if(c==null) {
- if(failures[hpi.idx]>System.currentTimeMillis()) {
- throw new LocatorException("Client requested is invalid");
- } else {
- synchronized(clients) {
- c = _newClient(urlstrs[hpi.idx]);
- failures[hpi.idx]=0L;
+ /*
+ * If a valid client is available, but there are some that can refresh, return the client immediately
+ * but start a Thread to do the background Client setup.
+ */
+ if(tickle) {
+ synchronized(clients) {
+ if(refreshThread==null) {
+ refreshThread = new Thread(new Runnable(){
+ @Override
+ public void run() {
+ refresh();
+ refreshThread = null;
+ }
+ });
+ refreshThread.setDaemon(true);
+ refreshThread.start();
}
}
- } else if(failures[hpi.idx]>0){
- throw new LocatorException("Client requested is invalid");
}
- return c;
- }
-
- public String info(Item item) {
- HPItem hpi = (HPItem)item;
- if(hpi!=null && hpi.idx<urlstrs.length) {
- return urlstrs[hpi.idx];
- } else {
- return "Invalid Item";
+
+ if(best<0) {
+ throw new LocatorException("No Clients available");
}
+
+ return new HPItem(best);
}
+ }
+
- @Override
- public boolean hasItems() {
- for(int i=0;i<clients.length;++i) {
- if(clients[i]!=null && failures[i]==0L) {
- return true;
+ @Override
+ public CLIENT get(Item item) throws LocatorException {
+ HPItem hpi = (HPItem)item;
+ CLIENT c = clients[hpi.idx];
+ if(c==null) {
+ if(failures[hpi.idx]>System.currentTimeMillis()) {
+ throw new LocatorException("Client requested is invalid");
+ } else {
+ synchronized(clients) {
+ c = _newClient(urlstrs[hpi.idx]);
+ failures[hpi.idx]=0L;
}
}
- return false;
- }
-
- @Override
- public synchronized void invalidate(Item item) throws LocatorException {
- HPItem hpi = (HPItem)item;
- failures[hpi.idx] = System.currentTimeMillis() + invalidateTime;
- CLIENT c = clients[hpi.idx];
- clients[hpi.idx] = _invalidate(c);
+ } else if(failures[hpi.idx]>0){
+ throw new LocatorException("Client requested is invalid");
}
-
- @Override
- public Item first() throws LocatorException {
- return new HPItem(0);
+ return c;
+ }
+
+ public String info(Item item) {
+ HPItem hpi = (HPItem)item;
+ if(hpi!=null && hpi.idx<urlstrs.length) {
+ return urlstrs[hpi.idx];
+ } else {
+ return "Invalid Item";
}
-
- @Override
- public Item next(Item item) throws LocatorException {
- HPItem hpi = (HPItem)item;
- if(++hpi.idx>=clients.length) {
- return null;
+ }
+
+ @Override
+ public boolean hasItems() {
+ for(int i=0;i<clients.length;++i) {
+ if(clients[i]!=null && failures[i]==0L) {
+ return true;
}
- return hpi;
}
-
- @Override
- public boolean refresh() {
- boolean force = !hasItems(); // If no Items at all, reset
- boolean rv = true;
- long now = System.currentTimeMillis();
- for(int i=0;i<clients.length;++i) {
- if(failures[i]>0L && (failures[i]<now || force)) { // retry
- try {
- synchronized(clients) {
- if(clients[i]==null) {
- clients[i]=_newClient(urlstrs[i]);
- }
- failures[i]=0L;
+ return false;
+ }
+
+ @Override
+ public synchronized void invalidate(Item item) throws LocatorException {
+ HPItem hpi = (HPItem)item;
+ failures[hpi.idx] = System.currentTimeMillis() + invalidateTime;
+ CLIENT c = clients[hpi.idx];
+ clients[hpi.idx] = _invalidate(c);
+ }
+
+ @Override
+ public Item first() throws LocatorException {
+ return new HPItem(0);
+ }
+
+ @Override
+ public Item next(Item item) throws LocatorException {
+ HPItem hpi = (HPItem)item;
+ if(++hpi.idx>=clients.length) {
+ return null;
+ }
+ return hpi;
+ }
+
+ @Override
+ public boolean refresh() {
+ boolean force = !hasItems(); // If no Items at all, reset
+ boolean rv = true;
+ long now = System.currentTimeMillis();
+ for(int i=0;i<clients.length;++i) {
+ if(failures[i]>0L && (failures[i]<now || force)) { // retry
+ try {
+ synchronized(clients) {
+ if(clients[i]==null) {
+ clients[i]=_newClient(urlstrs[i]);
}
- } catch (LocatorException e) {
- failures[i]=now+invalidateTime;
- rv = false;
+ failures[i]=0L;
}
+ } catch (LocatorException e) {
+ failures[i]=now+invalidateTime;
+ rv = false;
}
}
- return rv;
}
-
- @Override
- public void destroy() {
- for(int i=0;i<clients.length;++i) {
- if(clients[i]!=null) {
- _destroy(clients[i]);
- clients[i] = null;
- }
+ return rv;
+ }
+
+ @Override
+ public void destroy() {
+ for(int i=0;i<clients.length;++i) {
+ if(clients[i]!=null) {
+ _destroy(clients[i]);
+ clients[i] = null;
}
}
+ }
- private static class HPItem implements Item {
- private int idx;
+ private static class HPItem implements Item {
+ private int idx;
- public HPItem(int i) {
- idx = i;
- }
+ public HPItem(int i) {
+ idx = i;
}
-
+ }
- /*
- * Convenience Functions
- */
- public CLIENT bestClient() throws LocatorException {
- return get(best());
- }
- public boolean invalidate(CLIENT client) throws LocatorException {
- for(int i=0;i<clients.length;++i) {
- if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference
- invalidate(new HPItem(i));
- return true;
- }
+ /*
+ * Convenience Functions
+ */
+ public CLIENT bestClient() throws LocatorException {
+ return get(best());
+ }
+
+ public boolean invalidate(CLIENT client) throws LocatorException {
+ for(int i=0;i<clients.length;++i) {
+ if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference
+ invalidate(new HPItem(i));
+ return true;
}
- return false;
}
+ return false;
+ }
- }
\ No newline at end of file
+}
\ No newline at end of file
import java.io.PrintStream;
import java.net.HttpURLConnection;
-import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
-import static org.hamcrest.CoreMatchers.*;
import org.junit.*;
import org.mockito.*;
@Test
public void test() throws IOException {
// All the constructors accomplish the same thing
+ @SuppressWarnings("unused")
HBasicAuthSS auth = new HBasicAuthSS(si);
// TODO: While these test _should_ pass, and they _do_ pass on my local machine, they won't
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.http.test;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+
+import static org.hamcrest.CoreMatchers.*;
+import org.junit.*;
+import org.mockito.*;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.SecuritySetter;
+import org.onap.aaf.cadi.client.EClient.Transfer;
+import org.onap.aaf.cadi.client.Future;
+import org.onap.aaf.cadi.http.HClient;
+import org.onap.aaf.cadi.http.HClient.HFuture;
+import org.onap.aaf.misc.env.APIException;
+import org.onap.aaf.misc.rosetta.env.RosettaDF;
+import org.onap.aaf.misc.rosetta.env.RosettaData;
+
+public class JU_HClient {
+
+ @Mock private SecuritySetter<HttpURLConnection> ssMock;
+ @Mock private Transfer transferMock;
+ @Mock private HttpURLConnection hucMock;
+ @Mock private HttpServletResponse respMock;
+ @Mock private RosettaDF<HttpURLConnection> dfMock;
+ @Mock private RosettaData<HttpURLConnection> dataMock;
+
+ private static final String uriString = "http://example.com:8080/path/to/a/file.txt";
+ private static final String fragment = "fragment";
+ private static final String method = "method";
+ private static final String pathinfo = "pathinfo";
+ private static final String queryParams = "queryParams";
+
+ private static final String errorString = "error string";
+ private static final String successString = "success string";
+
+ private static final String tag1 = "tag1";
+ private static final String tag2 = "tag2";
+ private static final String value1 = "value1";
+ private static final String value2 = "value2";
+
+ private URI uri;
+
+ @Before
+ public void setup() throws URISyntaxException {
+ MockitoAnnotations.initMocks(this);
+
+ uri = new URI(uriString);
+ }
+
+ @Test
+ public void accessorsMutatorsTest() throws LocatorException {
+ HClient client = new HClient(ssMock, uri, 0);
+ client.setFragment(fragment);
+ client.setMethod(method);
+ client.setPathInfo(pathinfo);
+ client.setPayload(transferMock);
+ client.setQueryParams(queryParams);
+ assertThat(client.getURI(), is(uri));
+ assertThat(client.timeout(), is(0));
+ assertThat(client.toString(), is("HttpURLConnection Client configured to " + uri.toString()));
+ }
+
+ @Test
+ public void sendTest() throws LocatorException, APIException, URISyntaxException {
+ HClientStub client;
+ client = new HClientStub(ssMock, uri, 0, null);
+ client.send();
+
+ client.setPathInfo("/pathinfo");
+ client.send();
+
+ client.setPathInfo("pathinfo");
+ client.send();
+
+ client = new HClientStub(null, uri, 0, null);
+ client.send();
+
+ client.addHeader(tag1, value1);
+ client.addHeader(tag2, value2);
+ client.send();
+
+ client.setPayload(transferMock);
+ client.send();
+ }
+
+ @Test(expected = APIException.class)
+ public void sendThrows1Test() throws APIException, LocatorException, URISyntaxException {
+ HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null);
+ client.send();
+ }
+
+ @Test(expected = APIException.class)
+ public void sendThrows2Test() throws APIException, LocatorException, URISyntaxException {
+ HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null);
+ client.addHeader(tag1, value1);
+ client.addHeader(tag2, value2);
+ client.send();
+ }
+
+ @Test
+ public void futureCreateTest() throws LocatorException, CadiException, IOException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ HFuture<HttpURLConnection> future = (HFuture<HttpURLConnection>) client.futureCreate(HttpURLConnection.class);
+
+ // Test a bad response code (default 0) without output
+ assertThat(future.get(0), is(false));
+ assertThat(future.body().length(), is(0));
+
+ // Test a bad response code (default 0) with output
+ ByteArrayInputStream bais = new ByteArrayInputStream(errorString.getBytes());
+ when(hucMock.getInputStream()).thenReturn(bais);
+ assertThat(future.get(0), is(false));
+ assertThat(future.body(), is(errorString));
+
+ // Test a good response code
+ when(hucMock.getResponseCode()).thenReturn(201);
+ assertThat(future.get(0), is(true));
+ }
+
+ @Test
+ public void futureReadStringTest() throws LocatorException, CadiException, IOException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ Future<String> future = client.futureReadString();
+
+ // Test a bad response code (default 0) without output
+ assertThat(future.get(0), is(false));
+ assertThat(future.body().length(), is(0));
+
+ // Test a bad response code (default 0) with output
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes()));
+ assertThat(future.get(0), is(false));
+ assertThat(future.body(), is(errorString));
+
+ // Test a good response code
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes()));
+ when(hucMock.getResponseCode()).thenReturn(200);
+ assertThat(future.get(0), is(true));
+ assertThat(future.body(), is(successString));
+ }
+
+ @Test
+ public void futureReadTest() throws LocatorException, CadiException, IOException, APIException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ Future<HttpURLConnection> future = client.futureRead(dfMock, null);
+
+ // Test a bad response code (default 0) without output
+ assertThat(future.get(0), is(false));
+ assertThat(future.body().length(), is(0));
+
+ // Test a bad response code (default 0) with output
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes()));
+ assertThat(future.get(0), is(false));
+ assertThat(future.body(), is(errorString));
+
+ // Test a good response code
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes()));
+ when(dfMock.newData()).thenReturn(dataMock);
+ when(dataMock.in(null)).thenReturn(dataMock);
+ when(dataMock.load((InputStream)any())).thenReturn(dataMock);
+ when(dataMock.asObject()).thenReturn(hucMock);
+ when(dataMock.asString()).thenReturn(successString);
+ when(hucMock.getResponseCode()).thenReturn(200);
+ assertThat(future.get(0), is(true));
+ assertThat(future.body(), is(successString));
+ }
+
+ @Test
+ public void future1Test() throws LocatorException, CadiException, IOException, APIException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ Future<HttpURLConnection> future = client.future(hucMock);
+
+ // Test a good response code
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes()));
+ when(hucMock.getResponseCode()).thenReturn(200);
+ assertThat(future.get(0), is(true));
+ assertThat(future.body(), is("200"));
+
+ // Test a bad response code
+ when(hucMock.getResponseCode()).thenReturn(0);
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes()));
+ assertThat(future.get(0), is(false));
+ assertThat(future.body(), is(errorString));
+ }
+
+ @Test
+ public void future2Test() throws LocatorException, CadiException, IOException, APIException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ Future<Void> future = client.future(respMock, 200);
+
+ ServletOutputStream sos = new ServletOutputStream() {
+ @Override public void write(int arg0) throws IOException { }
+ };
+ when(respMock.getOutputStream()).thenReturn(sos);
+
+ // Test a good response code
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes()));
+ when(hucMock.getResponseCode()).thenReturn(200);
+ assertThat(future.get(0), is(true));
+ assertThat(future.body(), is(nullValue()));
+
+ // Test a bad response code
+ when(hucMock.getResponseCode()).thenReturn(0);
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes()));
+ assertThat(future.get(0), is(false));
+ assertThat(future.body(), is(""));
+ }
+
+ @Test
+ public void hfutureTest() throws CadiException, IOException, LocatorException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ HFutureStub future = new HFutureStub(client, hucMock);
+ assertThat(future.get(0), is(false));
+
+ // Test a bad response code (default 0) with output
+ when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes()));
+ assertThat(future.get(0), is(false));
+
+ assertThat(future.get(0), is(false));
+
+ when(hucMock.getResponseCode()).thenReturn(200);
+ assertThat(future.get(0), is(true));
+
+ StringBuilder sb = future.inputStreamToString(new ByteArrayInputStream(errorString.getBytes()));
+ assertThat(sb.toString(), is(errorString));
+
+ assertThat(future.code(), is(200));
+ assertThat(future.huc(), is(hucMock));
+
+ assertThat(future.exception(), is(nullValue()));
+ assertThat(future.header("string"), is(nullValue()));
+
+ // coverage...
+ future.setHuc(null);
+ future.close();
+ }
+
+ @Test
+ public void headerTest() throws LocatorException {
+ HClient client = new HClientStub(ssMock, uri, 0, hucMock);
+ String tag1 = "tag1";
+ String tag2 = "tag2";
+ String value1 = "value1";
+ String value2 = "value2";
+ client.addHeader(tag1, value1);
+ client.addHeader(tag2, value2);
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws1Test() throws LocatorException {
+ @SuppressWarnings("unused")
+ HClient client = new HClient(ssMock, null, 0);
+ }
+
+ private class HClientStub extends HClient {
+ public HClientStub(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout, HttpURLConnection huc) throws LocatorException {
+ super(ss, uri, connectTimeout);
+ setHuc(huc);
+ }
+ public void setHuc(HttpURLConnection huc) {
+ Field field;
+ try {
+ field = HClient.class.getDeclaredField("huc");
+ field.setAccessible(true);
+ field.set(this, huc);
+ field.setAccessible(false);
+ } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
+ e.printStackTrace();
+ fail("Caught an exception: " + e.getMessage());
+ }
+ }
+ @Override
+ public HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException {
+ return hucMock;
+ }
+ }
+
+ private class HFutureStub extends HFuture<HttpURLConnection> {
+ public HFutureStub(HClient hClient, HttpURLConnection huc) {
+ hClient.super(huc);
+ }
+
+ @Override public String body() { return null; }
+ public void setHuc(HttpURLConnection huc) { this.huc = huc; }
+ }
+
+}
package org.onap.aaf.cadi.locator.test;
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import org.junit.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
-import org.junit.AfterClass;
-import org.junit.Test;
+import org.onap.aaf.cadi.LocatorException;
import org.onap.aaf.cadi.PropAccess;
import org.onap.aaf.cadi.Locator.Item;
import org.onap.aaf.cadi.locator.DNSLocator;
public class JU_DNSLocator {
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
+
+ private PropAccess access;
+
+ @Before
+ public void setup() {
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
}
@Test
- public void test() {
- // TODO: Actually test this class - Ian
+ public void test() throws LocatorException {
+ DNSLocator dl;
+ Item item;
+ URI uri;
+
+ dl = new DNSLocator(access, "https", "localhost", "8100-8101");
- DNSLocator dl = new DNSLocator(new PropAccess(), "https", "aaf.it.att.com","8150-8152");
- try {
- Item item = dl.best();
- URI uri = dl.get(item);
- URL url = uri.toURL();
- URLConnection conn = url.openConnection();
- conn.connect();
- } catch (Exception e) {
+ item = dl.best();
+ uri = dl.get(item);
+ assertThat(uri.toString(), is("https://127.0.0.1:8100"));
+ item = dl.best();
+ assertThat(uri.toString(), is("https://127.0.0.1:8100"));
+
+ assertThat(dl.hasItems(), is(true));
+ for (item = dl.first(); item != null; item = dl.next(item)) {
+ dl.invalidate(item);
}
+ assertThat(dl.hasItems(), is(false));
+
+ // This doesn't actually do anything besides increase coverage
+ dl.destroy();
+ }
+
+ @Test
+ public void constructorTest() throws LocatorException {
+ // For coverage
+ new DNSLocator(access, "https", "localhost", "8100");
+ new DNSLocator(access, "https", "localhost", "8100-8101");
+
+ new DNSLocator(access, "http:localhost");
+ new DNSLocator(access, "https:localhost");
+ new DNSLocator(access, "https:localhost:8100");
+ new DNSLocator(access, "https:localhost:[8100]");
+ new DNSLocator(access, "https:localhost:[8100-8101]");
+ new DNSLocator(access, "https:localhost:8000/");
+ }
+
+ @Test
+ public void refreshTest() throws LocatorException {
+ DNSLocator dl = new DNSLocator(access, "https", "bogushost", "8100-8101");
+ assertThat(dl.refresh(), is(false));
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws1Test() throws LocatorException {
+ new DNSLocator(access, null);
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws2Test() throws LocatorException {
+ new DNSLocator(access, "ftp:invalid");
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws3Test() throws LocatorException {
+ new DNSLocator(access, "https:localhost:[8100");
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws4Test() throws LocatorException {
+ new DNSLocator(access, "https:localhost:[]");
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws5Test() throws LocatorException {
+ new DNSLocator(access, "https:localhost:[8100-]");
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws6Test() throws LocatorException {
+ new DNSLocator(access, "https:localhost:[-8101]");
+ }
+
+ @Test(expected = LocatorException.class)
+ public void throws7Test() throws LocatorException {
+ new DNSLocator(access, "https:localhost:/");
}
}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.locator.test;
+
+import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
+import org.junit.*;
+import org.mockito.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.http.HClient;
+import org.onap.aaf.cadi.http.HX509SS;
+import org.onap.aaf.cadi.locator.HClientHotPeerLocator;
+
+public class JU_HClientHotPeerLocator {
+
+ @Mock private HX509SS ssMock;
+
+ private PropAccess access;
+ private ByteArrayOutputStream outStream;
+
+ // Note: - The IP and port are irrelevant for these tests
+ private static final String goodURL1 = "fakeIP1:fakePort1/38/-90"; // Approx St Louis
+ private static final String goodURL2 = "fakeIP2:fakePort2/33/-96"; // Approx Dallas
+ private static final String badURL = "~%$!@#$//";
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ outStream = new ByteArrayOutputStream();
+ access = new PropAccess(new PrintStream(outStream), new String[0]);
+ }
+
+ @Test
+ public void test() throws LocatorException {
+ HClientHotPeerLocator loc;
+ String urlStr = goodURL1 + ',' + goodURL2;
+ loc = new HClientHotPeerLocator(access, urlStr, 0, "38.627", "-90.199", ssMock);
+ assertThat(loc.hasItems(), is(true));
+
+ String[] messages = outStream.toString().split("\n");
+ String preffered = messages[0].split(" ", 4)[3];
+ String alternate = messages[1].split(" ", 4)[3];
+ assertThat(preffered, is("Preferred Client is " + goodURL1));
+ assertThat(alternate, is("Alternate Client is " + goodURL2));
+
+ HClient firstClient = loc.get(loc.first());
+ HClient bestClient = loc.bestClient();
+ assertThat(bestClient, is(firstClient));
+
+ Locator.Item item = loc.first();
+ assertThat(loc.info(item), is(goodURL1));
+
+ item = loc.next(item);
+ assertThat(loc.info(item), is(goodURL2));
+
+ item = loc.next(item);
+ assertThat(item, is(nullValue()));
+ assertThat(loc.info(item), is("Invalid Item"));
+
+ item = loc.first();
+ loc.invalidate(item);
+
+ loc.invalidate(loc.bestClient());
+ loc.invalidate(loc.get(loc.next(item)));
+ loc.destroy();
+ }
+
+ @Test(expected = LocatorException.class)
+ public void failuresTest() throws LocatorException {
+ HClientHotPeerLocator loc;
+ String urlStr = goodURL1 + ',' + goodURL2 + ',' + badURL;
+ loc = new HClientHotPeerLocator(access, urlStr, 1000000, "38.627", "-90.199", ssMock);
+ String[] messages = outStream.toString().split("\n");
+ String preffered = messages[0].split(" ", 4)[3];
+ String alternate1 = messages[1].split(" ", 4)[3];
+ String alternate2 = messages[2].split(" ", 4)[3];
+ assertThat(preffered, is("Preferred Client is " + badURL));
+ assertThat(alternate1, is("Alternate Client is " + goodURL1));
+ assertThat(alternate2, is("Alternate Client is " + goodURL2));
+
+ outStream.reset();
+
+ loc.invalidate(loc.first());
+
+ loc.destroy();
+ loc.best();
+ }
+
+ @Test
+ public void hasNoItemTest() throws LocatorException {
+ HClientHotPeerLocator loc;
+ loc = new HClientHotPeerLocator(access, badURL, 0, "38.627", "-90.199", ssMock);
+ assertThat(loc.hasItems(), is(false));
+ loc.invalidate(loc.first());
+ }
+
+ @Test(expected = LocatorException.class)
+ public void invalidClientTest() throws LocatorException {
+ @SuppressWarnings("unused")
+ HClientHotPeerLocator loc = new HClientHotPeerLocator(access, "InvalidClient", 0, "38.627", "-90.199", ssMock);
+ }
+
+ @Test(expected = LocatorException.class)
+ public void coverageTest() throws LocatorException {
+ CoverageLocator loc;
+ String urlStr = goodURL1 + ',' + goodURL2;
+ loc = new CoverageLocator(access, urlStr, 0, "38.627", "-90.199", ssMock);
+ assertThat(loc._invalidate(null), is(nullValue()));
+ loc._destroy(null);
+
+ loc._newClient("bad string");
+ }
+
+ private class CoverageLocator extends HClientHotPeerLocator {
+ public CoverageLocator(Access access, String urlstr, long invalidateTime, String localLatitude,
+ String localLongitude, HX509SS ss) throws LocatorException {
+ super(access, urlstr, invalidateTime, localLatitude, localLongitude, ss);
+ }
+ public HClient _newClient(String clientInfo) throws LocatorException { return super._newClient(clientInfo); }
+ public HClient _invalidate(HClient client) { return super._invalidate(client); }
+ public void _destroy(HClient client) { super._destroy(client); }
+ }
+}
private Clean clean;
protected Access access;
-// private final static Permission teaser = new LocalPermission("***NoPERM****");
protected AbsUserCache(Access access, long cleanInterval, int highCount, int usageCount) {
this.access = access;
}
Miss miss = missMap.get(mkey);
if(miss==null) {
- missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval));
+ missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval,key));
return true;
}
return miss.mayContinue();
for(User<PERM> user : al) {
++total;
if(user.count>usageTriggerCount) {
- // access.log(Level.AUDIT, "Checking Thread", new Date(now));
boolean touched = false, removed=false;
if(user.principal instanceof CachedPrincipal) {
CachedPrincipal cp = (CachedPrincipal)user.principal;
break;
case REVALIDATED:
user.resetCount();
- // access.log(Level.AUDIT, "CACHE revalidated credentials");
touched = true;
break;
default:
}
}
- // access.log(Level.AUDIT, "User Perm Expires", new Date(user.permExpires));
if(!removed && lur!=null && user.permExpires<= now ) {
- // access.log(Level.AUDIT, "Reloading");
if(lur.reload(user).equals(Resp.REVALIDATED)) {
user.renewPerm();
access.log(Level.DEBUG, "Reloaded Perms for",user);
keys.addAll(missMap.keySet());
for(String key : keys) {
Miss m = missMap.get(key);
- if(m!=null && m.timestamp<System.currentTimeMillis()) {
- synchronized(missMap) {
- missMap.remove(key);
+ if(m!=null) {
+ long timeLeft = m.timestamp - System.currentTimeMillis();
+ if(timeLeft<0) {
+ synchronized(missMap) {
+ missMap.remove(key);
+ }
+ access.log(Level.INFO, m.name, " has been removed from Missed Credential Map (" + m.tries + " invalid tries)");
+ ++miss;
+ } else {
+ access.log(Level.INFO, m.name, " remains in Missed Credential Map (" + m.tries + " invalid tries) for " + (timeLeft/1000) + " more seconds");
}
- access.log(Level.INFO, key, "has been removed from Missed Credential Map (" + m.tries + " invalid tries)");
- ++miss;
}
}
}
private long timetolive;
private long tries;
+
+ private final String name;
- public Miss(byte[] first, long timeInterval) {
+ public Miss(final byte[] first, final long timeInterval, final String name) {
timestamp = System.currentTimeMillis() + timeInterval;
this.timetolive = timeInterval;
tries = 0L;
+ this.name = name;
}
}
return true;
}
+
}
/**
*/
public class CmdLine {
- public static Access access;
-
+ private static boolean systemExit = true;
/**
* @param args
*/
System.out.println(" sha256 <text> <salts(s)> (Digest String into SHA256 Hash)");
System.out.println(" md5 <text> (Digest String into MD5 Hash)");
}
- String forceExit = access.getProperty("force_exit", null);
- if (forceExit == null) {
+ if (systemExit) {
System.exit(1);
}
}
+ public static void setSystemExit(boolean shouldExit) {
+ systemExit = shouldExit;
+ }
+
}
*/
public class Config {
+ private static final String AAF_V2_0 = "org.onap.aaf.cadi.aaf.v2_0";
+ private static final String AAF_V2_0_AAFCON = AAF_V2_0+".AAFCon";
+ private static final String AAF_V2_0_AAF_LUR_PERM = AAF_V2_0+".AAFLurPerm";
+ private static final String OAUTH = "org.onap.auth.oauth";
+ private static final String OAUTH_TOKEN_MGR = OAUTH+".TokenMgr";
+ private static final String OAUTH_HTTP_TAF = OAUTH+".OAuth2HttpTaf";
+ private static final String OAUTH_DIRECT_TAF = OAUTH+".OAuthDirectTAF";
+
public static final String UTF_8 = "UTF-8";
// Property Names associated with configurations.
public static final String AAF_APPPASS = "aaf_password";
public static final String AAF_LUR_CLASS = "aaf_lur_class";
public static final String AAF_TAF_CLASS = "aaf_taf_class";
- public static final String AAF_TAF_CLASS_DEF = "org.osaaf.cadi.aaf.v2_0.AAFTaf";
public static final String AAF_CONNECTOR_CLASS = "aaf_connector_class";
public static final String AAF_LOCATOR_CLASS = "aaf_locator_class";
public static final String AAF_CONN_TIMEOUT = "aaf_conn_timeout";
public static final String AAF_CONN_TIMEOUT_DEF = "3000";
public static final String AAF_CONN_IDLE_TIMEOUT = "aaf_conn_idle_timeout"; // only for Direct Jetty Access.
public static final String AAF_CONN_IDLE_TIMEOUT_DEF = "10000"; // only for Direct Jetty Access.
-
+
+ // Default Classes: These are for Class loading to avoid direct compile links
+ public static final String AAF_TAF_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFTaf";
+ public static final String AAF_LOCATOR_CLASS_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFLocator";
+ public static final String CADI_OLUR_CLASS_DEF = "org.onap.aaf.cadi.olur.OLur";
+ public static final String CADI_OBASIC_HTTP_TAF_DEF = "org.onap.aaf.cadi.obasic.OBasicHttpTaf";
+ public static final String CADI_AAF_CON_DEF = "org.onap.aaf.cadi.aaf.v2_0.AAFCon";
+
public static final String AAF_CALL_TIMEOUT = "aaf_timeout";
public static final String AAF_CALL_TIMEOUT_DEF = "5000";
public static final String AAF_USER_EXPIRES = "aaf_user_expires";
private static String defaultRealm="none";
public static final String AAF_DOMAIN_SUPPORT = "aaf_domain_support";
- public static final String AAF_DOMAIN_SUPPORT_DEF = ".com";
+ public static final String AAF_DOMAIN_SUPPORT_DEF = ".com:.org";
// OAUTH2
public static final String AAF_OAUTH2_TOKEN_URL = "aaf_oauth2_token_url";
public static void setDefaultRealm(Access access) throws CadiException {
try {
- boolean hasCSP;
- try {
- Class.forName("org.osaaf.cadi.taf.csp.CSPTaf");
- hasCSP=true;
- } catch(ClassNotFoundException e) {
- hasCSP = logProp(access,Config.CSP_DOMAIN, null)!=null;
- }
defaultRealm = logProp(access,Config.AAF_DEFAULT_REALM,
- hasCSP?"csp.att.com":
- logProp(access,Config.BASIC_REALM,
- logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName())
- )
- );
+ logProp(access,Config.BASIC_REALM,
+ logProp(access,HOSTNAME,InetAddress.getLocalHost().getHostName())
+ )
+ );
} catch (UnknownHostException e) {
//defaultRealm="none";
}
/////////////////////////////////////////////////////
// Setup AAFCon for any following
/////////////////////////////////////////////////////
- Class<?> aafConClass = loadClass(access,"org.onap.aaf.cadi.aaf.v2_0.AAFCon");
+ Class<?> aafConClass = loadClass(access,CADI_AAF_CON_DEF);
Object aafcon = null;
if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) {
aafcon = con;
if(!hasOAuthDirectTAF) {
if(basic_realm!=null) {
@SuppressWarnings("unchecked")
- Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,"org.osaaf.cadi.obasic.OBasicHttpTaf");
+ Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF);
if(obasicCls!=null) {
try {
String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null);
String oauth_token_url = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null);
Class<?> oadtClss;
try {
- oadtClss = Class.forName("org.osaaf.authz.oauth.OAuthDirectTAF");
+ oadtClss = Class.forName(OAUTH_DIRECT_TAF);
} catch (ClassNotFoundException e1) {
oadtClss = null;
}
} else if(oauth_token_url!=null) {
String oauth_introspect_url = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null);
@SuppressWarnings("unchecked")
- Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,"org.osaaf.cadi.oauth.OAuth2HttpTaf");
+ Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,OAUTH_HTTP_TAF);
if(oaTCls!=null) {
- Class<?> oaTTmgrCls = loadClass(access, "org.osaaf.cadi.oauth.TokenMgr");
+ Class<?> oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR);
if(oaTTmgrCls!=null) {
try {
Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class);
String introspect_url = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null);
if(token_url!=null && introspect_url !=null) {
try {
- Class<?> olurCls = loadClass(access, "org.osaaf.cadi.olur.OLur");
+ Class<?> olurCls = loadClass(access, CADI_OLUR_CLASS_DEF);
if(olurCls!=null) {
Constructor<?> olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class);
Lur olur = (Lur)olurCnst.newInstance(access,token_url,introspect_url);
if(aafURL==null) {
access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded");
} else {// There's an AAF_URL... try to configure an AAF
- String aafLurClassStr = logProp(access,AAF_LUR_CLASS,"org.osaaf.cadi.aaf.v2_0.AAFLurPerm");
+ String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM);
////////////AAF Lur 2.0 /////////////
- if(aafLurClassStr!=null && aafLurClassStr.startsWith("org.osaaf.cadi.aaf.v2_0")) {
+ if(aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) {
try {
Object aafcon = loadAAFConnector(si, aafURL);
if(aafcon==null) {
access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object.");
} else {
- Class<?> aafAbsAAFCon = loadClass(access, "org.osaaf.cadi.aaf.v2_0.AAFCon");
+ Class<?> aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON);
if(aafAbsAAFCon!=null) {
Method mNewLur = aafAbsAAFCon.getMethod("newLur");
Object aaflur = mNewLur.invoke(aafcon);
return false;
}
- private static final String COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP = "org.osaaf.cadi.aaf.v2_0.AAFConHttp";
+ private static final String AAF_V2_0_AAF_CON_HTTP = "org.onap.aaf.cadi.aaf.v2_0.AAFConHttp";
+
public static Object loadAAFConnector(SecurityInfoC<HttpURLConnection> si, String aafURL) {
Access access = si.access;
Object aafcon = null;
Class<?> aafConClass = null;
try {
- if(aafURL!=null) {
- String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP);
- if(COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) {
- aafConClass = loadClass(access, COM_ATT_CADI_AAF_V2_0_AAF_CON_HTTP);
- if(aafConClass!=null) {
- for(Constructor<?> c : aafConClass.getConstructors()) {
+ if (aafURL!=null) {
+ String aafConnector = access.getProperty(AAF_CONNECTOR_CLASS, AAF_V2_0_AAF_CON_HTTP);
+ if (AAF_V2_0_AAF_CON_HTTP.equals(aafConnector)) {
+ aafConClass = loadClass(access, AAF_V2_0_AAF_CON_HTTP);
+ if (aafConClass != null) {
+ for (Constructor<?> c : aafConClass.getConstructors()) {
List<Object> lo = new ArrayList<Object>();
- for(Class<?> pc : c.getParameterTypes()) {
- if(pc.equals(PropAccess.class)) {
+ for (Class<?> pc : c.getParameterTypes()) {
+ if (pc.equals(Access.class)) {
lo.add(access);
- } else if(pc.equals(Locator.class)) {
+ } else if (pc.equals(Locator.class)) {
lo.add(loadLocator(si, aafURL));
} else {
continue;
}
}
- if(c.getParameterTypes().length!=lo.size()) {
+ if (c.getParameterTypes().length != lo.size()) {
continue; // back to another Constructor
} else {
aafcon = c.newInstance(lo.toArray());
}
}
}
- if(aafcon!=null) {
- String mechid = logProp(access,Config.AAF_APPID, null);
+ if (aafcon != null) {
+ String mechid = logProp(access, Config.AAF_APPID, null);
String pass = access.getProperty(Config.AAF_APPPASS, null);
- if(mechid!=null && pass!=null) {
+ if (mechid != null && pass != null) {
try {
Method basicAuth = aafConClass.getMethod("basicAuth", String.class, String.class);
- basicAuth.invoke(aafcon, mechid,pass);
+ basicAuth.invoke(aafcon, mechid, pass);
} catch (NoSuchMethodException nsme) {
// it's ok, don't use
}
}
}
} catch (Exception e) {
- access.log(e,"AAF Connector could not be constructed with given Constructors.");
+ access.log(e, "AAF Connector could not be constructed with given Constructors.");
}
-
+
return aafcon;
}
}
try {
- Class<?> lcls = loadClass(access,"org.onap.aaf.cadi.aaf.v2_0.AAFLocator");
+ Class<?> lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF);
if(lcls==null) {
throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator");
}
}
TrustManager tms[] = tmf.getTrustManagers();
- if(tms != null) {
- tm = new X509TrustManager[(tms == null) ? 0 : tms.length];
+ if(tms != null && tms.length>0) {
+ tm = new X509TrustManager[tms.length];
for(int i = 0; i < tms.length; ++i) {
try {
tm[i] = (X509TrustManager)tms[i];
delegate = null;
}
RolesAllowed rolesAllowed = cls.getAnnotation(RolesAllowed.class);
- if(rolesAllowed == null) {
+ if (rolesAllowed == null) {
roles = null;
} else {
roles = rolesAllowed.value();
}
public void init(ServletConfig sc) throws ServletException {
- if(delegate == null) throw new ServletException("Invalid Servlet Delegate");
+ if (delegate == null) {
+ throw new ServletException("Invalid Servlet Delegate");
+ }
delegate.init(sc);
}
}
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
- if(roles==null) {
- delegate.service(req,resp);
- } else { // Validate
- try {
- HttpServletRequest hreq = (HttpServletRequest)req;
- boolean proceed = false;
- for(String role : roles) {
- if(hreq.isUserInRole(role)) {
- proceed = true;
- break;
- }
- }
- if(proceed) {
- delegate.service(req,resp);
- } else {
- //baseRequest.getServletContext().log(hreq.getUserPrincipal().getName()+" Refused " + roles);
- ((HttpServletResponse)resp).sendError(403); // forbidden
+ if (roles == null) {
+ delegate.service(req, resp);
+ return;
+ }
+
+ // Validate
+ try {
+ HttpServletRequest hreq = (HttpServletRequest)req;
+ for (String role : roles) {
+ if (hreq.isUserInRole(role)) {
+ delegate.service(req, resp);
+ return;
}
- } catch(ClassCastException e) {
- throw new ServletException("JASPIServlet only supports HTTPServletRequest/HttpServletResponse");
}
+
+ ((HttpServletResponse)resp).sendError(403); // forbidden
+ } catch (ClassCastException e) {
+ throw new ServletException("JASPIServlet only supports HTTPServletRequest/HttpServletResponse");
}
}
delegate.destroy();
}
-
}
}
SecurityInfoC<HttpURLConnection> si;
si = SecurityInfoC.instance(access, HttpURLConnection.class);
+
lur = Config.configLur(si, con, additionalTafLurs);
tc.setLur(lur);
* @param value
*/
public MapPermConverter() {
- map = new HashMap<String,String>();
+ map = new HashMap<>();
}
/**
public String convert(String minimal) {
String rv = map.get(minimal);
- return rv==null?minimal:rv;
+ return (rv == null) ? minimal : rv;
}
}
* Licensed 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.
/**
- * A NullPermConverter
- *
+ * A NullPermConverter
+ *
* Obey the PermConverter Interface, but passed in "minimal" String is not converted.
- *
+ *
* @author Jonathan
*
*/
public class NullPermConverter implements PermConverter {
- private NullPermConverter() {}
private static final NullPermConverter singleton = new NullPermConverter();
- public static NullPermConverter singleton() {return singleton;}
+
+ private NullPermConverter() {}
+
+ public static NullPermConverter singleton() { return singleton; }
public String convert(String minimal) {
return minimal;
* Licensed 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.
/**
* PathFilter
- *
+ *
* This class implements Servlet Filter, and uses AAF to validate access to a Path.
- *
+ *
* This class can be used in a standard J2EE Servlet manner.
- *
+ *
* @author Jonathan, collaborating with Xue Gao
*
*/
public class PathFilter implements Filter {
- private ServletContext context;
- private String aaf_type;
- private String not_authorized_msg;
private final Log log;
+ private ServletContext context;
+ private String aafType;
+ private String notAuthorizedMsg;
+
/**
* Construct a viable Filter for installing in Container WEB.XML, etc.
- *
+ *
*/
public PathFilter() {
log = new Log() {
public void info(String ... msg) {
- context.log(build("INFO:",msg));
+ context.log(build("INFO:", msg));
}
public void audit(String ... msg) {
- context.log(build("AUDIT:",msg));
+ context.log(build("AUDIT:", msg));
}
private String build(String type, String []msg) {
StringBuilder sb = new StringBuilder(type);
- for(String s : msg) {
+ for (String s : msg) {
sb.append(' ');
sb.append(s);
}
return sb.toString();
}
-
};
}
-
+
/**
* Filter that can be constructed within Java
* @param access
}
};
}
-
+
/**
* Init
- *
+ *
* Standard Filter "init" call with FilterConfig to obtain properties. POJOs can construct a
* FilterConfig with the mechanism of their choice, and standard J2EE Servlet engines utilize this
* mechanism already.
// need the Context for Logging, instantiating ClassLoader, etc
context = filterConfig.getServletContext();
StringBuilder sb = new StringBuilder();
- StringBuilder err = new StringBuilder();
+ StringBuilder err = new StringBuilder();
Object attr = context.getAttribute(Config.PATHFILTER_NS);
- if(attr==null) {
+ if (attr == null) {
err.append("PathFilter - pathfilter_ns is not set");
} else {
- sb.append(attr.toString());
+ sb.append(attr.toString());
}
attr = context.getAttribute(Config.PATHFILTER_STACK);
- if(attr==null) {
+ if (attr == null) {
log.info("PathFilter - No pathfilter_stack set, ignoring");
} else {
sb.append('.');
}
attr = context.getAttribute(Config.PATHFILTER_URLPATTERN);
- if(attr==null) {
+ if (attr == null) {
log.info("PathFilter - No pathfilter_urlpattern set, defaulting to 'urlpattern'");
sb.append(".urlpattern");
} else {
sb.append(attr.toString());
}
- log.info("PathFilter - AAF Permission Type is",sb.toString());
-
+ log.info("PathFilter - AAF Permission Type is", sb.toString());
+
sb.append('|');
-
- aaf_type = sb.toString();
+
+ aafType = sb.toString();
attr = context.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG);
- if(attr==null) {
- not_authorized_msg = "Forbidden - Not Authorized to access this Path";
+ if (attr == null) {
+ notAuthorizedMsg = "Forbidden - Not Authorized to access this Path";
} else {
- not_authorized_msg = attr.toString();
+ notAuthorizedMsg = attr.toString();
}
- if(err.length()>0) {
+ if (err.length() > 0) {
throw new ServletException(err.toString());
}
}
/**
* doFilter
- *
+ *
* This is the standard J2EE invocation. Analyze the request, modify response as necessary, and
* only call the next item in the filterChain if request is suitably Authenticated.
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest hreq = (HttpServletRequest)request;
HttpServletResponse hresp = (HttpServletResponse)response;
- String perm = aaf_type+hreq.getPathInfo()+'|'+hreq.getMethod();
- if(hreq.isUserInRole(perm)) {
+ String perm = aafType + hreq.getPathInfo() + '|' + hreq.getMethod();
+ if (hreq.isUserInRole(perm)) {
chain.doFilter(request, response);
} else {
- log.audit("PathFilter has denied",hreq.getUserPrincipal().getName(),"access to",perm);
- hresp.sendError(403,not_authorized_msg);
+ log.audit("PathFilter has denied", hreq.getUserPrincipal().getName(), "access to", perm);
+ hresp.sendError(403, notAuthorizedMsg);
}
}
/**
- * Containers call "destroy" when time to cleanup
+ * Containers call "destroy" when time to cleanup
*/
public void destroy() {
log.info("PathFilter destroyed.");
}
-
-
}
-
* Licensed 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.
import org.onap.aaf.cadi.Access.Level;
import org.onap.aaf.cadi.config.Config;
-
/**
* An in-memory Lur that can be configured locally with User info via properties, similar to Tomcat-users.xml mechanisms.
- *
+ *
* @author Jonathan
*
*/
public static final String COLON = "\\s*:\\s*";
public static final String COMMA = "\\s*,\\s*";
public static final String PERCENT = "\\s*%\\s*";
-
+
// Use to quickly determine whether any given group is supported by this LUR
private final Set<String> supportingGroups;
- private String supportedRealm;
-
+ private String supportedRealm;
+
/**
* Construct by building structure, see "build"
- *
+ *
* Reconstruct with "build"
- *
- * @param userProperty
- * @param groupProperty
+ *
+ * @param userProperties
+ * @param groupProperties
* @param decryptor
* @throws IOException
*/
- public LocalLur(Access access, String userProperty, String groupProperty) throws IOException {
+ public LocalLur(Access access, String userProperties, String groupProperties) throws IOException {
super(access, 0, 0, Integer.MAX_VALUE); // data doesn't expire
supportedRealm = access.getProperty(Config.BASIC_REALM, "localized");
- supportingGroups = new TreeSet<String>();
-
- if(userProperty!=null) {
- // For each User name...
- for(String user : userProperty.trim().split(SEMI)) {
- String[] us = user.split(COLON,2);
- String[] userpass = us[0].split(PERCENT,2);
- String u;
- User<LocalPermission> usr;
- if(userpass.length>1) {
- if(userpass.length>0 && userpass[0].indexOf('@')<0) {
- userpass[0]=userpass[0] + '@' + access.getProperty(Config.AAF_DEFAULT_REALM,Config.getDefaultRealm());
- }
-
- u = userpass[0];
- byte[] pass = access.decrypt(userpass[1], true).getBytes();
- usr = new User<LocalPermission>(new ConfigPrincipal(u, pass));
- } else {
- u = us[0];
- usr = new User<LocalPermission>(new ConfigPrincipal(u, (byte[])null));
- }
- addUser(usr);
- access.log(Level.INIT, "Local User:",usr.principal);
-
- if(us.length>1) {
- Map<String, Permission> newMap = usr.newMap();
- for(String group : us[1].split(COMMA)) {
- supportingGroups.add(group);
- usr.add(newMap,new LocalPermission(group));
- }
- usr.setMap(newMap);
- }
- }
+ supportingGroups = new TreeSet<>();
+
+ if (userProperties != null) {
+ parseUserProperties(userProperties);
}
- if(groupProperty!=null) {
- // For each Group name...
- for(String group : groupProperty.trim().split(SEMI)) {
- String[] gs = group.split(COLON,2);
- if(gs.length>1) {
- supportingGroups.add(gs[0]);
- LocalPermission p = new LocalPermission(gs[0]);
- // Add all users (known by comma separators)
-
- for(String grpMem : gs[1].split(COMMA)) {
- // look for password, if so, put in passMap
- String[] userpass = grpMem.split(PERCENT,2);
- if(userpass.length>0 && userpass[0].indexOf('@')<0) {
- userpass[0]=userpass[0] + '@' + access.getProperty(Config.AAF_DEFAULT_REALM,Config.getDefaultRealm());
- }
- User<LocalPermission> usr = null;
- if(userpass.length>1) {
- byte[] pass = access.decrypt(userpass[1], true).getBytes();
- usr = getUser(userpass[0],pass);
- if(usr==null)addUser(usr=new User<LocalPermission>(new ConfigPrincipal(userpass[0],pass)));
- else usr.principal=new ConfigPrincipal(userpass[0],pass);
- } else {
- addUser(usr=new User<LocalPermission>(new ConfigPrincipal(userpass[0],(byte[])null)));
- }
- usr.add(p);
- access.log(Level.INIT, "Local User:",usr.principal);
- }
- }
- }
+
+ if (groupProperties != null) {
+ parseGroupProperties(groupProperties);
}
}
-
+
public boolean validate(String user, CredVal.Type type, byte[] cred, Object state) {
- User<LocalPermission> usr = getUser(user,cred);
- switch(type) {
- case PASSWORD:
- // covers null as well as bad pass
- if(usr!=null && cred!=null && usr.principal instanceof ConfigPrincipal) {
- return Hash.isEqual(cred,((ConfigPrincipal)usr.principal).getCred());
- }
- break;
+ if (cred == null) {
+ return false;
+ }
+ User<LocalPermission> usr = getUser(user, cred);
+ if (usr == null) {
+ return false;
+ }
+ // covers null as well as bad pass
+ if ((type == Type.PASSWORD) && (usr.principal instanceof ConfigPrincipal)) {;
+ return Hash.isEqual(cred, ((ConfigPrincipal)usr.principal).getCred());
}
return false;
}
// @Override
public boolean fish(Principal bait, Permission pond) {
- if(pond == null) {
+ if (pond == null) {
return false;
}
- if(handles(bait) && pond instanceof LocalPermission) { // local Users only have LocalPermissions
- User<LocalPermission> user = getUser(bait);
- return user==null?false:user.contains((LocalPermission)pond);
+ if (handles(bait) && pond instanceof LocalPermission) { // local Users only have LocalPermissions
+ User<LocalPermission> user = getUser(bait);
+ if (user != null) {
+ return user.contains((LocalPermission)pond);
}
+ }
return false;
}
// We do not want to expose the actual Group, so make a copy.
public void fishAll(Principal bait, List<Permission> perms) {
- if(handles(bait)) {
+ if (handles(bait)) {
User<LocalPermission> user = getUser(bait);
- if(user!=null) {
+ if (user != null) {
user.copyPermsTo(perms);
}
}
*/
@Override
public boolean handles(Principal principal) {
- return principal!=null && principal.getName().endsWith(supportedRealm);
+ if (principal == null) {
+ return false;
+ }
+ return principal.getName().endsWith(supportedRealm);
}
-// public boolean supports(String userName) {
-// return userName!=null && userName.endsWith(supportedRealm);
-// }
-//
public boolean handlesExclusively(Permission pond) {
return supportingGroups.contains(pond.getKey());
}
public Permission createPerm(String p) {
return new LocalPermission(p);
}
+
+ private void parseUserProperties(String userProperties) throws IOException {
+ // For each User name...
+ for (String userProperty : userProperties.trim().split(SEMI)) {
+ String[] userInfo = userProperty.split(COLON, 2);
+ String[] userPass = userInfo[0].split(PERCENT, 2);
+ String userName = userPass[0];
+
+ byte[] password = null;
+ if (userPass.length > 1) {
+ password = access.decrypt(userPass[1], true).getBytes();
+ if (userName.indexOf('@') < 0) {
+ userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm());
+ }
+ }
+ User<LocalPermission> usr;
+ usr = new User<>(new ConfigPrincipal(userName, password));
+ addUser(usr);
+ access.log(Level.INIT, "Local User:", usr.principal);
+
+ if (userInfo.length > 1) {
+ Map<String, Permission> newMap = usr.newMap();
+ for (String group : userInfo[1].split(COMMA)) {
+ supportingGroups.add(group);
+ usr.add(newMap, new LocalPermission(group));
+ }
+ usr.setMap(newMap);
+ }
+ }
+ }
+
+
+ private void parseGroupProperties(String groupProperties) throws IOException {
+ // For each Group name...
+ for (String group : groupProperties.trim().split(SEMI)) {
+ String[] groups = group.split(COLON, 2);
+ if (groups.length <= 1) {
+ continue;
+ }
+ supportingGroups.add(groups[0]);
+ LocalPermission p = new LocalPermission(groups[0]);
+
+ // Add all users (known by comma separators)
+ for (String groupMember : groups[1].split(COMMA)) {
+ // look for password, if so, put in passMap
+ String[] userPass = groupMember.split(PERCENT, 2);
+ String userName = userPass[0];
+ if (userName.indexOf('@') < 0) {
+ userName += '@' + access.getProperty(Config.AAF_DEFAULT_REALM, Config.getDefaultRealm());
+ }
+
+ User<LocalPermission> usr = null;
+ byte[] password = null;
+ if (userPass.length > 1) {
+ password = access.decrypt(userPass[1], true).getBytes();
+ }
+ usr = getUser(userName, password);
+ if (usr == null) {
+ usr = new User<>(new ConfigPrincipal(userName, password));
+ addUser(usr);
+ }
+ else {
+ usr.principal = new ConfigPrincipal(userName, password);
+ }
+ usr.add(p);
+ access.log(Level.INIT, "Local User:", usr.principal);
+ }
+ }
+ }
}
@Override
public String personalName() {
- return null; // personalName not available with Basic Auth
+ return name; // personalName not available with Basic Auth
}
}
* Respond in the affirmative if the TAF was able to Authenticate
*/
public boolean isValid() {
- return principal!=null;
+ return principal != null;
}
/**
* Licensed 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.
import javax.servlet.http.HttpServletResponse;
import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Access.Level;
import org.onap.aaf.cadi.CachedPrincipal;
+import org.onap.aaf.cadi.CachedPrincipal.Resp;
import org.onap.aaf.cadi.CadiException;
import org.onap.aaf.cadi.Locator;
-import org.onap.aaf.cadi.TrustChecker;
-import org.onap.aaf.cadi.Access.Level;
-import org.onap.aaf.cadi.CachedPrincipal.Resp;
import org.onap.aaf.cadi.Taf.LifeForm;
+import org.onap.aaf.cadi.TrustChecker;
/**
* HttpEpiTaf
- *
+ *
* An extension of the basic "EpiTAF" concept, check known HTTP Related TAFs for valid credentials
- *
+ *
* @author Jonathan
*
*/
private Access access;
private Locator<URI> locator;
private TrustChecker trustChecker;
-
+
/**
* HttpEpiTaf constructor
- *
+ *
* Construct the HttpEpiTaf from variable Http specific TAF parameters
* @param tafs
this.access = access;
this.locator = locator;
this.trustChecker = tc;
- // Establish what Header Property to look for UserChain/Trust Props
-// trustChainProp = access.getProperty(Config.CADI_TRUST_PROP, Config.CADI_TRUST_PROP_DEFAULT);
+ // Establish what Header Property to look for UserChain/Trust Props
- if(tafs.length==0) throw new CadiException("Need at least one HttpTaf implementation in constructor");
+ if (tafs.length == 0) {
+ throw new CadiException("Need at least one HttpTaf implementation in constructor");
+ }
}
/**
* validate
- *
- * Respond with the first Http specific TAF to authenticate user based on variable info
+ *
+ * Respond with the first Http specific TAF to authenticate user based on variable info
* and "LifeForm" (is it a human behind a browser, or a server utilizing HTTP Protocol).
- *
+ *
* If there is no HttpTAF that can authenticate, respond with the first TAF that suggests it can
* establish an Authentication conversation (TRY_AUTHENTICATING) (Examples include a redirect to CSP
- * Servers for CSP Cookie, or BasicAuth 401 response, suggesting User/Password for given Realm
+ * Servers for CSP Cookie, or BasicAuth 401 response, suggesting User/Password for given Realm
* submission
- *
+ *
* If no TAF declares either, respond with NullTafResp (which denies all questions)
*/
public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) {
// Given a LifeForm Neutral, for HTTP, we need to discover true Life-Form Readings
- if(reading==LifeForm.LFN) {
+ if (reading == LifeForm.LFN) {
reading = tricorderScan(req);
}
- TafResp tresp=null, firstTry = null;
+ TafResp tresp = null;
+ TafResp firstTry = null;
List<Redirectable> redirectables = null;
- List<TafResp> trlog = access.willLog(Level.DEBUG)?new ArrayList<TafResp>():null;
+ List<TafResp> log = (access.willLog(Level.DEBUG)) ? new ArrayList<TafResp>() : null;
try {
- for(HttpTaf taf : tafs) {
+ for (HttpTaf taf : tafs) {
tresp = taf.validate(reading, req, resp);
- if(trlog!=null) {
- trlog.add(tresp);
- }
+ addToLog(log, tresp);
switch(tresp.isAuthenticated()) {
case TRY_ANOTHER_TAF:
break; // and loop
case TRY_AUTHENTICATING:
- if(tresp instanceof Redirectable) {
- if(redirectables==null) {
- redirectables = new ArrayList<Redirectable>();
+ if (tresp instanceof Redirectable) {
+ if (redirectables == null) {
+ redirectables = new ArrayList<>();
}
redirectables.add((Redirectable)tresp);
- } else if(firstTry==null) {
+ } else if (firstTry == null) {
firstTry = tresp;
}
- break;
+ break;
case IS_AUTHENTICATED:
tresp = trustChecker.mayTrust(tresp, req);
return tresp;
return tresp;
}
}
- } finally {
- if(trlog!=null) {
- for( TafResp tr : trlog) {
- access.log(Level.DEBUG, tr.desc());
- }
- }
+ } finally {
+ printLog(log);
}
-
- // If No TAFs configured, at this point. It is safer at this point to be "not validated",
+
+ // If No TAFs configured, at this point. It is safer at this point to be "not validated",
// rather than "let it go"
// Note: if exists, there will always be more than 0 entries, according to above code
- if(redirectables==null) {
- return firstTry!=null?firstTry:NullTafResp.singleton();
+ if (redirectables == null) {
+ return (firstTry != null) ? firstTry : NullTafResp.singleton();
}
-
+
// If there is one Tryable entry then return it
- if(redirectables.size()>1) {
- return LoginPageTafResp.create(access,locator,resp,redirectables);
+ if (redirectables.size() > 1) {
+ return LoginPageTafResp.create(access, locator, resp, redirectables);
} else {
return redirectables.get(0);
}
}
-
+
public boolean revalidate(Principal prin) throws Exception {
return false;
}
/*
* Since this is internal, we use a little Star Trek humor to indicate looking in the HTTP Request to see if we can determine what kind
- * of "LifeForm" reading we can determine, i.e. is there a Human (CarbonBasedLifeForm) behind a browser, or is it mechanical
+ * of "LifeForm" reading we can determine, i.e. is there a Human (CarbonBasedLifeForm) behind a browser, or is it mechanical
* id (SiliconBasedLifeForm)? This makes a difference in some Authentication, i.e CSP, which doesn't work well for SBLFs
*/
private LifeForm tricorderScan(HttpServletRequest req) {
// For simplicity's sake, we'll say Humans use FQDNs, not IPs.
-
- String auth = req.getParameter("Authentication");
- if(auth!=null) {
- if("BasicAuth".equals(auth)) {
- return LifeForm.SBLF;
- }
- }
+
// Current guess that only Browsers bother to set "Agent" codes that identify the kind of browser they are.
// If mechanical frameworks are found that populate this, then more advanced analysis may be required
// Jonathan 1/22/2013
String agent = req.getHeader("User-Agent");
- if(agent!=null && agent.startsWith("Mozilla")) // covers I.E./Firefox/Safari/probably any other "advanced" Browser see http://en.wikipedia.org/wiki/User_agent
- return LifeForm.CBLF;
+ if (agent != null && agent.startsWith("Mozilla")) { // covers I.E./Firefox/Safari/probably any other "advanced" Browser see http://en.wikipedia.org/wiki/User_agent
+ return LifeForm.CBLF;
+ }
return LifeForm.SBLF; // notably skips "curl","wget", (which is desired behavior. We don't want to try CSP, etc on these)
}
public Resp revalidate(CachedPrincipal prin, Object state) {
Resp resp;
- for(HttpTaf taf : tafs) {
- resp = taf.revalidate(prin,state);
- switch(resp) {
- case NOT_MINE:
- break;
- default:
- return resp;
+ for (HttpTaf taf : tafs) {
+ resp = taf.revalidate(prin, state);
+ if (resp != Resp.NOT_MINE) {
+ return resp;
}
+// switch(resp) {
+// case NOT_MINE:
+// break;
+// default:
+// return resp;
+// }
}
return Resp.NOT_MINE;
}
+
+ private void addToLog(List<TafResp> log, TafResp tresp) {
+ if (log == null) {
+ return;
+ }
+ log.add(tresp);
+ }
+
+ private void printLog(List<TafResp> log) {
+ if (log == null) {
+ return;
+ }
+ for (TafResp tresp : log) {
+ access.log(Level.DEBUG, tresp.desc());
+ }
+ }
/**
* List HttpTafs with their "toString" representations... primarily useful for Debugging in an IDE
*/
public String toString() {
StringBuilder sb = new StringBuilder();
- for(HttpTaf ht : tafs) {
+ for (HttpTaf ht : tafs) {
sb.append(ht.toString());
sb.append(". ");
}
return RESP.TRY_AUTHENTICATING;
}
- public static TafResp create(Access access, Locator<URI> locator, final HttpServletResponse resp, List<Redirectable> redir) {
- if(locator!=null) {
- try {
- Item item = locator.best();
- URI uri = locator.get(item);
- if(uri!=null) {
- StringBuilder sb = new StringBuilder(uri.toString());
- String query = uri.getQuery();
- boolean first = query==null || query.length()==0;
- int count=0;
- for(Redirectable t : redir) {
- if(first) {
- sb.append('?');
- first=false;
- }
- else sb.append('&');
- sb.append(t.get());
- ++count;
- }
- if(count>0)return new LoginPageTafResp(access, resp, sb.toString());
+ public static TafResp create(Access access, Locator<URI> locator, final HttpServletResponse resp, List<Redirectable> redirectables) {
+ if (locator == null) {
+ if (!redirectables.isEmpty()) {
+ access.log(Level.DEBUG,"LoginPage Locator is not configured. Taking first Redirectable Taf");
+ return redirectables.get(0);
+ }
+ return NullTafResp.singleton();
+ }
+
+ try {
+ Item item = locator.best();
+ URI uri = locator.get(item);
+ if (uri == null) {
+ return NullTafResp.singleton();
+ }
+
+ StringBuilder sb = new StringBuilder(uri.toString());
+ String query = uri.getQuery();
+ boolean first = ((query == null) || (query.length() == 0));
+ for (Redirectable redir : redirectables) {
+ if (first) {
+ sb.append('?');
+ first = false;
+ }
+ else {
+ sb.append('&');
}
- } catch (Exception e) {
- access.log(e, "Error deriving Login Page location");
+ sb.append(redir.get());
}
- } else if(!redir.isEmpty()) {
- access.log(Level.DEBUG,"LoginPage Locator is not configured. Taking first Redirectable Taf");
- return redir.get(0);
+ if (!redirectables.isEmpty()) {
+ return new LoginPageTafResp(access, resp, sb.toString());
+ }
+ } catch (Exception e) {
+ access.log(e, "Error deriving Login Page location");
}
+
return NullTafResp.singleton();
}
}
package org.onap.aaf.cadi.wsse;
-import java.io.IOException;
import java.io.InputStream;
import javax.xml.stream.XMLStreamException;
private static final String SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/";
private static final String WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private Match<BasicCred> parseTree;
- //private XMLInputFactory inputFactory;
public WSSEParser() {
// soap:Envelope/soap:Header/wsse:Security/wsse:UsernameToken/[wsse:Password&wsse:Username]
).stopAfter() // Stop Processing when Header Ends
).exclusive()// Envelope must match Header, and no other. FYI, Body comes after Header short circuits (see above), so it's ok
).exclusive(); // root must be Envelope
- //inputFactory = XMLInputFactory.newInstance();
}
- public XMLStreamException parse(BasicCred bc, InputStream is) throws IOException {
+ public XMLStreamException parse(BasicCred bc, InputStream is) {
try {
parseTree.onMatch(bc, new XReader(is));
return null;
package org.onap.aaf.cadi.config.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.mockito.Mockito.*;
-import org.junit.*;
-import org.mockito.*;
+
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
package org.onap.aaf.cadi.config.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import org.junit.*;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
private final static String names = "admin:myname,yourname;suser:hisname,hername,m1234";
private AbsUserCache<LocalPermission> lur;
-
+
@Before
public void setup() throws IOException {
outStream = new ByteArrayOutputStream();
UsersDump.write(outStream, lur);
String[] actualLines = Split.splitTrim('\n', outStream.toString());
String[] expectedLines = Split.splitTrim('\n', expected);
+ for (String s : actualLines) {
+ System.out.println(s);
+ }
assertThat(actualLines.length, is(expectedLines.length));
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.filter.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.filter.AUTHZServlet;
+
+import javax.servlet.Servlet;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequestWrapper;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class JU_AUTHZServlet {
+
+ @Mock private Servlet servletMock;
+ @Mock private ServletConfig servletConfigMock;
+ @Mock private HttpServletRequest reqMock;
+ @Mock private HttpServletResponse respMock;
+ @Mock private ServletRequestWrapper servletWrapperMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void test() throws ServletException, IOException {
+ AUTHZServletStub servlet = new AUTHZServletStub(Servlet.class);
+
+ try {
+ servlet.init(servletConfigMock);
+ fail("Should've thrown an exception");
+ } catch (ServletException e) {
+ assertThat(e.getMessage(), is("Invalid Servlet Delegate"));
+ }
+
+ setPrivateField(AUTHZServlet.class, "delegate", servlet, servletMock);
+ servlet.init(servletConfigMock);
+ servlet.getServletConfig();
+ servlet.getServletInfo();
+
+ servlet.service(reqMock, respMock);
+
+ String[] roles = new String[] {"role1", "role2"};
+ setPrivateField(AUTHZServlet.class, "roles", servlet, roles);
+ servlet.service(reqMock, respMock);
+
+ when(reqMock.isUserInRole("role1")).thenReturn(true);
+ servlet.service(reqMock, respMock);
+
+ try {
+ servlet.service(servletWrapperMock, respMock);
+ fail("Should've thrown an exception");
+ } catch (ServletException e) {
+ assertThat(e.getMessage(), is("JASPIServlet only supports HTTPServletRequest/HttpServletResponse"));
+ }
+ servlet.destroy();
+ }
+
+ private class AUTHZServletStub extends AUTHZServlet<Servlet> {
+ public AUTHZServletStub(Class<Servlet> cls) { super(cls); }
+ }
+
+ private void setPrivateField(Class<?> clazz, String fieldName, Object target, Object value) {
+ try {
+ Field field = clazz.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ field.set(target, value);
+ field.setAccessible(false);
+ } catch(Exception e) {
+ System.err.println("Could not set field [" + fieldName + "] to " + value);
+ }
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.filter.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.filter.AccessGetter;
+
+public class JU_AccessGetter {
+
+ private static final String tag = "tag";
+ private static final String value = "value";
+
+ private PropAccess access;
+
+ @Before
+ public void setup() {
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ access.setProperty(tag, value);
+ }
+
+ @Test
+ public void test() {
+ AccessGetter getter = new AccessGetter(access);
+ assertThat(getter.get(tag, null, false), is(value));
+ }
+
+}
+++ /dev/null
-/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * * ===========================================================================
- * * Licensed 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.
- * * ============LICENSE_END====================================================
- * *
- * *
- ******************************************************************************/
-package org.onap.aaf.cadi.filter.test;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.when;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.aaf.cadi.PropAccess;
-
-public class JU_FCGetTest {
-
- @Test
- public void netYetTested() {
- //fail("Tests not yet implemented");
- }
-
-// @Mock
-// private ServletContext context;
-
-// @Mock
-// private FilterConfig config;
-
-// @Mock
-// private PropAccess access = new PropAccess();
-
-// @Before
-// public void setUp() {
-// MockitoAnnotations.initMocks(this);
-// }
-
-// @Test
-// public void testGetStringFromDef() {
-// PropAccess access = new PropAccess();
-
-// FCGet fcGet = new FCGet(access, context, config);
-
-// String user = fcGet.get("user", "DefaultUser", true);
-
-// assertEquals(user, "DefaultUser");
-// }
-
-// @Test
-// public void testGetStringFromContext() {
-// PropAccess access = new PropAccess();
-// when(context.getInitParameter("user")).thenReturn("ContextUser");
-
-// FCGet fcGet = new FCGet(access, context, null);
-
-// String user = fcGet.get("user", "DefaultUser", true);
-
-// assertEquals(user,"ContextUser");
-// }
-
-// @Test
-// public void testGetStringFromFilter() {
-// PropAccess access = new PropAccess();
-// when(config.getInitParameter("user")).thenReturn("FilterUser");
-
-// FCGet fcGet = new FCGet(access, null, config);
-
-// String user = fcGet.get("user", "DefaultUser", true);
-
-// assertEquals(user,"FilterUser");
-// }
-
-// @Test
-// public void testGetStringWithNullContextFilter() {
-
-// when(access.getProperty("user", "DefaultUser")).thenReturn(null);
-
-// FCGet fcGet = new FCGet(access, null, null);
-
-// String user = fcGet.get("user", "DefaultUser", true);
-
-// assertEquals(user,"DefaultUser");
-// }
-}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.filter.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import org.junit.Test;
+import org.onap.aaf.cadi.filter.MapPermConverter;
+
+public class JU_MapPermConverter {
+
+ private static final String tag = "tag";
+ private static final String value = "value";
+ private static final String nontag = "nontag";
+
+ @Test
+ public void test() {
+ MapPermConverter converter = new MapPermConverter();
+ assertThat(converter.map().isEmpty(), is(true));
+ converter.map().put(tag, value);
+ assertThat(converter.convert(tag), is(value));
+ assertThat(converter.convert(nontag), is(nontag));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.filter.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import org.junit.Test;
+import org.onap.aaf.cadi.filter.NullPermConverter;
+
+public class JU_NullPermConverter {
+
+ @Test
+ public void test() {
+ NullPermConverter converter = NullPermConverter.singleton();
+ assertThat(converter.convert("test"), is("test"));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.filter.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.security.Principal;
+
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.filter.PathFilter;
+
+public class JU_PathFilter {
+
+ private PropAccess access;
+
+ @Mock private FilterConfig filterConfigMock;
+ @Mock private ServletContext contextMock;
+ @Mock private HttpServletRequest reqMock;
+ @Mock private HttpServletResponse respMock;
+ @Mock private FilterChain chainMock;
+ @Mock private Principal princMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ when(filterConfigMock.getServletContext()).thenReturn(contextMock);
+ when(reqMock.getUserPrincipal()).thenReturn(princMock);
+ when(princMock.getName()).thenReturn("name");
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() throws ServletException, IOException {
+ PathFilter pathFilter = new PathFilter(access);
+ try {
+ pathFilter.init(filterConfigMock);
+ fail("Should've thrown an exception");
+ } catch (ServletException e) {
+ assertThat(e.getMessage(), is("PathFilter - pathfilter_ns is not set"));
+ }
+
+ when(contextMock.getAttribute(Config.PATHFILTER_NS)).thenReturn(5);
+ when(contextMock.getAttribute(Config.PATHFILTER_STACK)).thenReturn(5);
+ when(contextMock.getAttribute(Config.PATHFILTER_URLPATTERN)).thenReturn(5);
+ when(contextMock.getAttribute(Config.PATHFILTER_NOT_AUTHORIZED_MSG)).thenReturn(5);
+ pathFilter.init(filterConfigMock);
+
+ pathFilter.doFilter(reqMock, respMock, chainMock);
+
+ when(reqMock.isUserInRole(anyString())).thenReturn(true);
+ pathFilter.doFilter(reqMock, respMock, chainMock);
+
+ pathFilter.destroy();
+
+ pathFilter = new PathFilter();
+ pathFilter.init(filterConfigMock);
+
+ pathFilter.doFilter(reqMock, respMock, chainMock);
+
+ when(reqMock.isUserInRole(anyString())).thenReturn(false);
+ pathFilter.doFilter(reqMock, respMock, chainMock);
+
+ pathFilter.destroy();
+ }
+
+}
--- /dev/null
+/**
+ *
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.lur.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.CachingLur;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.CredVal;
+import org.onap.aaf.cadi.Lur;
+import org.onap.aaf.cadi.Permission;
+import org.onap.aaf.cadi.lur.EpiLur;
+
+public class JU_EpiLur {
+
+ private ArrayList<Permission> perms;
+ private CredValStub lurMock3;
+
+ @Mock private Lur lurMock1;
+ @Mock private CachingLur<?> lurMock2;
+ @Mock private Principal princMock;
+ @Mock private Permission permMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+
+ perms = new ArrayList<>();
+ perms.add(permMock);
+
+ lurMock3 = new CredValStub();
+ }
+
+ @Test
+ public void test() throws CadiException {
+ EpiLur lur;
+ try {
+ lur = new EpiLur();
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is("Need at least one Lur implementation in constructor"));
+ }
+ lur = new EpiLur(lurMock1, lurMock2, lurMock3);
+ assertThat(lur.fish(null, null), is(false));
+
+ assertThat(lur.fish(princMock, permMock), is(false));
+
+ when(lurMock2.handlesExclusively(permMock)).thenReturn(true);
+ assertThat(lur.fish(princMock, permMock), is(false));
+
+ when(lurMock2.fish(princMock, permMock)).thenReturn(true);
+ assertThat(lur.fish(princMock, permMock), is(true));
+
+ lur.fishAll(princMock, perms);
+
+ assertThat(lur.handlesExclusively(permMock), is(false));
+
+ assertThat(lur.get(-1), is(nullValue()));
+ assertThat(lur.get(0), is(lurMock1));
+ assertThat(lur.get(1), is((Lur)lurMock2));
+ assertThat(lur.get(2), is((Lur)lurMock3));
+ assertThat(lur.get(3), is(nullValue()));
+
+ assertThat(lur.handles(princMock), is(false));
+ when(lurMock2.handles(princMock)).thenReturn(true);
+ assertThat(lur.handles(princMock), is(true));
+
+ lur.remove("id");
+
+ lur.clear(princMock, null);
+
+ assertThat(lur.createPerm("perm"), is(not(nullValue())));
+
+ lur.getUserPassImpl();
+ assertThat(lur.getUserPassImpl(), is((CredVal)lurMock3));
+
+ lur.toString();
+ lur.destroy();
+
+ lur = new EpiLur(lurMock1, lurMock2);
+ assertThat(lur.getUserPassImpl(), is(nullValue()));
+
+ assertThat(lur.subLur(Lur.class), is(nullValue()));
+ }
+
+ private class CredValStub implements Lur, CredVal {
+ @Override public boolean validate(String user, Type type, byte[] cred, Object state) { return false; }
+ @Override public Permission createPerm(String p) { return null; }
+ @Override public boolean fish(Principal bait, Permission pond) { return false; }
+ @Override public void fishAll(Principal bait, List<Permission> permissions) { }
+ @Override public void destroy() { }
+ @Override public boolean handlesExclusively(Permission pond) { return false; }
+ @Override public boolean handles(Principal principal) { return false; }
+ @Override public void clear(Principal p, StringBuilder report) { }
+ }
+
+}
* * Licensed 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.
* *
* *
******************************************************************************/
+
package org.onap.aaf.cadi.lur.test;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.PrintStream;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
+import org.junit.Before;
import org.junit.Test;
-import org.onap.aaf.cadi.Lur;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.onap.aaf.cadi.Permission;
import org.onap.aaf.cadi.PropAccess;
-import org.onap.aaf.cadi.Symm;
+import org.onap.aaf.cadi.AbsUserCache;
import org.onap.aaf.cadi.CredVal.Type;
-import org.onap.aaf.cadi.config.UsersDump;
+import org.onap.aaf.cadi.lur.ConfigPrincipal;
import org.onap.aaf.cadi.lur.LocalLur;
import org.onap.aaf.cadi.lur.LocalPermission;
public class JU_LocalLur {
+ private static final String password = "<pass>";
+ private String encrypted;
+
+ private PropAccess access;
+ private ByteArrayOutputStream outStream;
+
+ @Mock Permission permMock;
+
+ @Before
+ public void setup() throws IOException {
+ MockitoAnnotations.initMocks(this);
+
+ encrypted = rot13(password);
+
+ outStream = new ByteArrayOutputStream();
+ access = new PropAccess(new PrintStream(outStream), new String[0]) {
+ @Override public String decrypt(String encrypted, boolean anytext) throws IOException {
+ return rot13(encrypted);
+ }
+ @Override public String encrypt(String unencrypted) throws IOException {
+ return rot13(unencrypted);
+ }
+ };
+
+ }
+
@Test
public void test() throws IOException {
- Symm symmetric = Symm.baseCrypt().obtain();
- LocalLur up;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- baos.write(Symm.ENC.getBytes());
- symmetric.enpass("<pass>", baos);
- PropAccess ta = new PropAccess();
- Lur ml = up = new LocalLur(ta,"myname:groupA,groupB","admin:myname,yourname;suser:hisname,hername,m1234%"+baos.toString());
+ LocalLur lur;
+ List<AbsUserCache<LocalPermission>.DumpInfo> info;
+
+ lur = new LocalLur(access, null, null);
+ assertThat(lur.dumpInfo().size(), is(0));
+
+ lur = new LocalLur(access, "user1", null);
+ info = lur.dumpInfo();
+ assertThat(info.size(), is(1));
+ assertThat(info.get(0).user, is("user1"));
+
+ lur.clearAll();
+ assertThat(lur.dumpInfo().size(), is(0));
+
+ lur = new LocalLur(access, "user1%" + encrypted, null);
+ info = lur.dumpInfo();
+ assertThat(info.size(), is(1));
+ assertThat(info.get(0).user, is("user1@none"));
+
+ lur.clearAll();
+ assertThat(lur.dumpInfo().size(), is(0));
+
+ lur = new LocalLur(access, "user1@domain%" + encrypted, null);
+ info = lur.dumpInfo();
+ assertThat(info.size(), is(1));
+ assertThat(info.get(0).user, is("user1@domain"));
+ lur = new LocalLur(access, "user1@domain%" + encrypted + ":groupA", null);
+ info = lur.dumpInfo();
+ assertThat(info.size(), is(1));
+ assertThat(info.get(0).user, is("user1@domain"));
-// Permission admin = new LocalPermission("admin");
-// Permission suser = new LocalPermission("suser");
-//
-// // Check User fish
-// assertTrue(ml.fish(new JUPrincipal("myname"),admin));
-// assertTrue(ml.fish(new JUPrincipal("hisname"),admin));
-// assertFalse(ml.fish(new JUPrincipal("noname"),admin));
-// assertTrue(ml.fish(new JUPrincipal("itsname"),suser));
-// assertTrue(ml.fish(new JUPrincipal("hername"),suser));
-// assertFalse(ml.fish(new JUPrincipal("myname"),suser));
-//
-// // Check validate password
-// assertTrue(up.validate("m1234",Type.PASSWORD, "<pass>".getBytes()));
-// assertFalse(up.validate("m1234",Type.PASSWORD, "badPass".getBytes()));
-//
- // Check fishAll
- Set<String> set = new TreeSet<String>();
- List<Permission> perms = new ArrayList<Permission>();
- ml.fishAll(new JUPrincipal("myname"), perms);
- for(Permission p : perms) {
- set.add(p.getKey());
- }
-// assertEquals("[admin, groupA, groupB]",set.toString());
- UsersDump.write(System.out, up);
- System.out.flush();
+ when(permMock.getKey()).thenReturn("groupA");
+ assertThat(lur.handlesExclusively(permMock), is(true));
+ when(permMock.getKey()).thenReturn("groupB");
+ assertThat(lur.handlesExclusively(permMock), is(false));
+
+ assertThat(lur.fish(null, null), is(false));
+
+ Principal princ = new ConfigPrincipal("user1@localized", encrypted);
+
+ lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null);
+ assertThat(lur.fish(princ, lur.createPerm("groupA")), is(true));
+ assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false));
+ assertThat(lur.fish(princ, permMock), is(false));
+
+ princ = new ConfigPrincipal("user1@domain", encrypted);
+ assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false));
+
+ princ = new ConfigPrincipal("user1@localized", "badpass");
+ assertThat(lur.fish(princ, lur.createPerm("groupB")), is(false));
+
+ assertThat(lur.handles(null), is(false));
+
+ lur.fishAll(null, null);
+
+ List<Permission> perms = new ArrayList<>();
+ perms.add(lur.createPerm("groupB"));
+ perms.add(lur.createPerm("groupA"));
+ princ = new ConfigPrincipal("user1@localized", encrypted);
+ lur.fishAll(princ, perms);
+ princ = new ConfigPrincipal("user1@localized", "badpass");
+ lur.fishAll(princ, perms);
+ assertThat(lur.validate(null, null, null, null), is(false));
+ assertThat(lur.validate("user", null, "badpass".getBytes(), null), is(false));
+ assertThat(lur.validate("user1@localized", null, encrypted.getBytes(), null), is(false));
+
+ lur = new LocalLur(access, "user1@localized%" + password + ":groupA", null);
+ assertThat(lur.validate("user1@localized", Type.PASSWORD, encrypted.getBytes(), null), is(true));
+
+ lur = new LocalLur(access, null, "admin");
+ lur = new LocalLur(access, null, "admin:user1");
+ lur = new LocalLur(access, null, "admin:user1@localized");
+ lur = new LocalLur(access, null, "admin:user1@localized,user2@localized%" + password + ";user:user1@localized");
}
-
- // Simplistic Principal for testing purposes
- private static class JUPrincipal implements Principal {
- private String name;
- public JUPrincipal(String name) {
- this.name = name;
- }
-// @Override
- public String getName() {
- return name;
+
+ public static String rot13(String input) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < input.length(); i++) {
+ char c = input.charAt(i);
+ if (c >= 'a' && c <= 'm') {
+ c += 13;
+ } else if (c >= 'A' && c <= 'M') {
+ c += 13;
+ } else if (c >= 'n' && c <= 'z') {
+ c -= 13;
+ } else if (c >= 'N' && c <= 'Z') {
+ c -= 13;
+ }
+ sb.append(c);
}
+ return sb.toString();
}
-
-
-
-
}
+
package org.onap.aaf.cadi.principal.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.mockito.Mockito.*;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.mock;
import org.junit.*;
import java.io.IOException;
import org.onap.aaf.cadi.BasicCred;
import org.onap.aaf.cadi.Symm;
import org.onap.aaf.cadi.principal.BasicPrincipal;
-import org.onap.aaf.cadi.principal.StringTagLookup;
-import org.onap.aaf.cadi.principal.TaggedPrincipal;
-import org.onap.aaf.cadi.principal.TaggedPrincipal.TagLookup;
public class JU_BasicPrincipal {
assertTrue(Math.abs(bp.created() - created) < 10);
assertThat(bp.toString(), is(expected));
assertThat(bp.tag(), is("BAth"));
- assertThat(bp.personalName(), is(nullValue()));
+ assertThat(bp.personalName(), is(bp.getName()));
// This test hits the abstract class BearerPrincipal
assertThat(bp.getBearer(), is(bearer));
package org.onap.aaf.cadi.principal.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.mockito.Mockito.*;
-import org.junit.*;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.mock;
+
+import org.junit.Before;
+import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.lang.reflect.Field;
-import java.util.Date;
import org.onap.aaf.cadi.BasicCred;
import org.onap.aaf.cadi.CachedPrincipal;
-import org.onap.aaf.cadi.CachedPrincipal.Resp;
-import org.onap.aaf.cadi.Symm;
import org.onap.aaf.cadi.principal.CachedBasicPrincipal;
-import org.onap.aaf.cadi.principal.StringTagLookup;
-import org.onap.aaf.cadi.principal.TaggedPrincipal;
-import org.onap.aaf.cadi.principal.TaggedPrincipal.TagLookup;
import org.onap.aaf.cadi.taf.HttpTaf;
public class JU_CachedBasicPrincipal {
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.taf.basic.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.security.Principal;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.servlet.AsyncContext;
+import javax.servlet.DispatcherType;
+import javax.servlet.RequestDispatcher;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletInputStream;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.Part;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.BasicCred;
+import org.onap.aaf.cadi.CachedPrincipal;
+import org.onap.aaf.cadi.CachedPrincipal.Resp;
+import org.onap.aaf.cadi.CredVal;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.Symm;
+import org.onap.aaf.cadi.Taf.LifeForm;
+import org.onap.aaf.cadi.taf.basic.BasicHttpTaf;
+
+public class JU_BasicHttpTaf {
+
+ private final static String realm = "realm";
+ private final static String id = "id";
+ private final static String addr = "addr";
+
+ private final static String name = "User";
+ private final static String password = "password";
+ private final static String content = name + ":" + password;
+ private static String encrypted;
+
+ private final static long timeToLive = 10000L;
+
+ private PropAccess access;
+
+ @Mock private HttpServletResponse respMock;
+ @Mock private HttpServletRequest reqMock;
+ @Mock private CredVal rbacMock;
+ @Mock private CachedPrincipal princMock;
+
+ @Before
+ public void setup() throws IOException {
+ MockitoAnnotations.initMocks(this);
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ encrypted = new String(Symm.base64.encode(content.getBytes()));
+ }
+
+ @Test
+ public void test() {
+ BasicHttpTaf taf = new BasicHttpTaf(access, rbacMock, realm, timeToLive, true);
+ BasicCredStub bcstub = new BasicCredStub();
+ assertThat(taf.validate(LifeForm.SBLF, bcstub, respMock), is(not(nullValue())));
+
+ assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue())));
+
+ when(reqMock.getHeader("Authorization")).thenReturn("test");
+ assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue())));
+
+ when(reqMock.getHeader("Authorization")).thenReturn("Basic " + encrypted);
+ assertThat(taf.validate(LifeForm.SBLF, reqMock, respMock), is(not(nullValue())));
+
+ assertThat(taf.revalidate(princMock, "state"), is(Resp.NOT_MINE));
+
+ assertThat(taf.toString(), is("Basic Auth enabled on realm: " + realm));
+ }
+
+ private class BasicCredStub implements HttpServletRequest, BasicCred {
+ @Override public String getUser() { return id; }
+ @Override public String getRemoteAddr() { return addr; }
+
+ @Override public AsyncContext getAsyncContext() { return null; }
+ @Override public Object getAttribute(String arg0) { return null; }
+ @Override public Enumeration<String> getAttributeNames() { return null; }
+ @Override public String getCharacterEncoding() { return null; }
+ @Override public int getContentLength() { return 0; }
+ @Override public String getContentType() { return null; }
+ @Override public DispatcherType getDispatcherType() { return null; }
+ @Override public ServletInputStream getInputStream() throws IOException { return null; }
+ @Override public String getLocalAddr() { return null; }
+ @Override public String getLocalName() { return null; }
+ @Override public int getLocalPort() { return 0; }
+ @Override public Locale getLocale() { return null; }
+ @Override public Enumeration<Locale> getLocales() { return null; }
+ @Override public String getParameter(String arg0) { return null; }
+ @Override public Map<String, String[]> getParameterMap() { return null; }
+ @Override public Enumeration<String> getParameterNames() { return null; }
+ @Override public String[] getParameterValues(String arg0) { return null; }
+ @Override public String getProtocol() { return null; }
+ @Override public BufferedReader getReader() throws IOException { return null; }
+ @Override public String getRealPath(String arg0) { return null; }
+ @Override public String getRemoteHost() { return null; }
+ @Override public int getRemotePort() { return 0; }
+ @Override public RequestDispatcher getRequestDispatcher(String arg0) { return null; }
+ @Override public String getScheme() { return null; }
+ @Override public String getServerName() { return null; }
+ @Override public int getServerPort() { return 0; }
+ @Override public ServletContext getServletContext() { return null; }
+ @Override public boolean isAsyncStarted() { return false; }
+ @Override public boolean isAsyncSupported() { return false; }
+ @Override public boolean isSecure() { return false; }
+ @Override public void removeAttribute(String arg0) { }
+ @Override public void setAttribute(String arg0, Object arg1) { }
+ @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { }
+ @Override public AsyncContext startAsync() throws IllegalStateException { return null; }
+ @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) throws IllegalStateException { return null; }
+ @Override public byte[] getCred() { return null; }
+ @Override public void setUser(String user) { }
+ @Override public void setCred(byte[] passwd) { }
+ @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return false; }
+ @Override public String getAuthType() { return null; }
+ @Override public String getContextPath() { return null; }
+ @Override public Cookie[] getCookies() { return null; }
+ @Override public long getDateHeader(String arg0) { return 0; }
+ @Override public String getHeader(String arg0) { return null; }
+ @Override public Enumeration<String> getHeaderNames() { return null; }
+ @Override public Enumeration<String> getHeaders(String arg0) { return null; }
+ @Override public int getIntHeader(String arg0) { return 0; }
+ @Override public String getMethod() { return null; }
+ @Override public Part getPart(String arg0) throws IOException, ServletException { return null; }
+ @Override public Collection<Part> getParts() throws IOException, ServletException { return null; }
+ @Override public String getPathInfo() { return null; }
+ @Override public String getPathTranslated() { return null; }
+ @Override public String getQueryString() { return null; }
+ @Override public String getRemoteUser() { return null; }
+ @Override public String getRequestURI() { return null; }
+ @Override public StringBuffer getRequestURL() { return null; }
+ @Override public String getRequestedSessionId() { return null; }
+ @Override public String getServletPath() { return null; }
+ @Override public HttpSession getSession() { return null; }
+ @Override public HttpSession getSession(boolean arg0) { return null; }
+ @Override public Principal getUserPrincipal() { return null; }
+ @Override public boolean isRequestedSessionIdFromCookie() { return false; }
+ @Override public boolean isRequestedSessionIdFromURL() { return false; }
+ @Override public boolean isRequestedSessionIdFromUrl() { return false; }
+ @Override public boolean isRequestedSessionIdValid() { return false; }
+ @Override public boolean isUserInRole(String arg0) { return false; }
+ @Override public void login(String arg0, String arg1) throws ServletException { }
+ @Override public void logout() throws ServletException { }
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.taf.basic.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.principal.TaggedPrincipal;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+import org.onap.aaf.cadi.taf.basic.BasicHttpTafResp;
+
+public class JU_BasicHttpTafResp {
+
+ private final static String realm = "realm";
+ private final static String description = "description";
+
+ private PropAccess access;
+
+ @Mock private HttpServletResponse respMock;
+ @Mock private TaggedPrincipal princMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() throws IOException {
+ BasicHttpTafResp tafResp = new BasicHttpTafResp(access, princMock, description, RESP.IS_AUTHENTICATED, respMock, realm, false);
+
+ assertThat(tafResp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED));
+ assertThat(tafResp.isAuthenticated(), is (RESP.IS_AUTHENTICATED));
+ assertThat(tafResp.isFailedAttempt(), is(false));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.taf.cert.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.principal.TaggedPrincipal;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+import org.onap.aaf.cadi.taf.cert.X509HttpTafResp;
+
+public class JU_X509HttpTafResp {
+
+ private final static String description = "description";
+ private final static RESP status = RESP.IS_AUTHENTICATED;
+
+ private PropAccess access;
+
+ @Mock private TaggedPrincipal princMock;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() throws IOException {
+ X509HttpTafResp resp = new X509HttpTafResp(access, princMock, description, status);
+ assertThat(resp.authenticate(), is(RESP.TRY_ANOTHER_TAF));
+ assertThat(resp.isAuthenticated(), is(status));
+ assertThat(resp.toString(), is(status.name()));
+ }
+
+}
--- /dev/null
+/**
+ *
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.taf.dos.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+import org.onap.aaf.cadi.taf.dos.DenialOfServiceTafResp;
+
+public class JU_DenialOfServiceTafResp {
+
+ private final static String description = "description";
+ private final static RESP status = RESP.IS_AUTHENTICATED;
+
+ private PropAccess access;
+
+ @Before
+ public void setup() {
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() throws IOException {
+ DenialOfServiceTafResp resp = new DenialOfServiceTafResp(access, status, description);
+ assertThat(resp.isAuthenticated(), is(status));
+ assertThat(resp.authenticate(), is(status));
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+* ============LICENSE_START====================================================
+* * org.onap.aaf
+* * ===========================================================================
+* * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+* * ===========================================================================
+* * Licensed 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.
+* * ============LICENSE_END====================================================
+* *
+* *
+******************************************************************************/
+
+package org.onap.aaf.cadi.taf.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.principal.TaggedPrincipal;
+import org.onap.aaf.cadi.taf.AbsTafResp;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+
+public class JU_AbsTafResp {
+
+ private static final String name = "name";
+ private static final String tag = "tag";
+ private static final String description = "description";
+
+ private Access access;
+ private TaggedPrincipal taggedPrinc;
+
+ @Before
+ public void setup() {
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ taggedPrinc = new TaggedPrincipal() {
+ @Override public String getName() { return name; }
+ @Override public String tag() { return tag; }
+ };
+ }
+
+ @Test
+ public void test() {
+ AbsTafResp tafResp = new AbsTafResp(access, taggedPrinc, description) {
+ @Override public RESP authenticate() throws IOException {
+ return null;
+ }
+ };
+
+ assertThat(tafResp.isValid(), is(true));
+ assertThat(tafResp.desc(), is(description));
+ assertThat(tafResp.isAuthenticated(), is(RESP.IS_AUTHENTICATED));
+ assertThat(tafResp.getPrincipal(), is(taggedPrinc));
+ assertThat(tafResp.getAccess(), is(access));
+ assertThat(tafResp.isFailedAttempt(), is(false));
+
+ tafResp = new AbsTafResp(null, null, null) {
+ @Override public RESP authenticate() throws IOException {
+ return null;
+ }
+ };
+
+ assertThat(tafResp.isValid(), is(false));
+ assertThat(tafResp.isAuthenticated(), is(RESP.TRY_ANOTHER_TAF));
+ assertThat(tafResp.getPrincipal(), is(nullValue()));
+ assertThat(tafResp.getAccess(), is(nullValue()));
+ assertThat(tafResp.isFailedAttempt(), is(false));
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.taf.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.Access.Level;
+import org.onap.aaf.cadi.CachedPrincipal.Resp;
+import org.onap.aaf.cadi.CadiException;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.Taf.LifeForm;
+import org.onap.aaf.cadi.TrustChecker;
+import org.onap.aaf.cadi.taf.HttpEpiTaf;
+import org.onap.aaf.cadi.taf.HttpTaf;
+import org.onap.aaf.cadi.taf.NullTaf;
+import org.onap.aaf.cadi.taf.Redirectable;
+import org.onap.aaf.cadi.taf.TafResp;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+
+public class JU_HttpEpiTaf {
+
+ private PropAccess access;
+
+ @Mock private Locator<URI> locMock;
+ @Mock private TrustChecker trustCheckerMock;
+ @Mock private HttpServletRequest reqMock;
+ @Mock private HttpServletResponse respMock;
+ @Mock private HttpTaf tafMock;
+ @Mock private TafResp trespMock;
+ @Mock private Redirectable redirMock;
+
+ @Before
+ public void setup() throws URISyntaxException {
+ MockitoAnnotations.initMocks(this);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+ }
+
+ @Test
+ public void test() throws Exception {
+ HttpEpiTaf taf;
+ try {
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock);
+ fail("Should've thrown an exception");
+ } catch (CadiException e) {
+ assertThat(e.getMessage(), is("Need at least one HttpTaf implementation in constructor"));
+ }
+
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock, new NullTaf());
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ // Coverage of tricorderScan
+ taf.validate(LifeForm.LFN, reqMock, respMock);
+ when(reqMock.getHeader("User-Agent")).thenReturn("Non-mozilla-header");
+ taf.validate(LifeForm.LFN, reqMock, respMock);
+ when(reqMock.getHeader("User-Agent")).thenReturn("Mozilla-header");
+ taf.validate(LifeForm.LFN, reqMock, respMock);
+
+ access.setLogLevel(Level.DEBUG);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(trespMock);
+ when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_ANOTHER_TAF);
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ when(trespMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ when(trespMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ when(tafMock.validate(LifeForm.CBLF, reqMock, respMock)).thenReturn(redirMock);
+ when(redirMock.isAuthenticated()).thenReturn(RESP.TRY_AUTHENTICATING);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock);
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+
+ taf = new HttpEpiTaf(access, locMock, null, tafMock);
+ when(redirMock.isAuthenticated()).thenReturn(RESP.IS_AUTHENTICATED);
+ try {
+ taf.validate(LifeForm.CBLF, reqMock, respMock);
+ fail("Should've thrown an exception");
+ } catch (Exception e) {
+ }
+
+ assertThat(taf.revalidate(null), is(false));
+ assertThat(taf.revalidate(null), is(false));
+
+ when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE);
+ assertThat(taf.revalidate(null, null), is(Resp.NOT_MINE));
+ when(tafMock.revalidate(null, null)).thenReturn(Resp.REVALIDATED);
+ assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED));
+
+ when(tafMock.revalidate(null, null)).thenReturn(Resp.NOT_MINE).thenReturn(Resp.NOT_MINE).thenReturn(Resp.REVALIDATED);
+ taf = new HttpEpiTaf(access, locMock, trustCheckerMock, tafMock, tafMock, tafMock);
+ assertThat(taf.revalidate(null, null), is(Resp.REVALIDATED));
+
+ taf.toString();
+
+ }
+
+}
--- /dev/null
+/**
+ * ============LICENSE_START====================================================
+ * org.onap.aaf
+ * ===========================================================================
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
+ * ===========================================================================
+ * Licensed 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.
+ * ============LICENSE_END====================================================
+ *
+ */
+
+package org.onap.aaf.cadi.taf.test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.Locator.Item;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.taf.LoginPageTafResp;
+import org.onap.aaf.cadi.taf.Redirectable;
+import org.onap.aaf.cadi.taf.TafResp;
+import org.onap.aaf.cadi.taf.TafResp.RESP;
+
+public class JU_LoginPageTafResp {
+
+ private static final String uriString = "example.com";
+
+ private URI uri;
+ private Access access;
+ private List<Redirectable> redirectables;
+
+ @Mock private HttpServletResponse respMock;
+ @Mock private Locator<URI> locatorMock;
+ @Mock private Redirectable redirMock;
+
+ @Before
+ public void setup() throws URISyntaxException {
+ MockitoAnnotations.initMocks(this);
+
+ access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]);
+
+ redirectables = new ArrayList<>();
+ uri = new URI(uriString);
+ }
+
+ @Test
+ public void test() throws LocatorException, IOException {
+ TafResp resp;
+ resp = LoginPageTafResp.create(access, null, respMock, redirectables);
+ assertThat(resp.desc(), is("All Authentication denied"));
+
+ redirectables.add(redirMock);
+ redirectables.add(redirMock);
+ resp = LoginPageTafResp.create(access, null, respMock, redirectables);
+ assertThat((Redirectable)resp, is(redirMock));
+
+ resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables);
+ assertThat(resp.desc(), is("All Authentication denied"));
+
+ when(locatorMock.get((Item)any())).thenReturn(uri);
+ resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables);
+ assertThat(resp.desc(), is("Multiple Possible HTTP Logins available. Redirecting to Login Choice Page"));
+ assertThat(resp.authenticate(), is(RESP.HTTP_REDIRECT_INVOKED));
+ assertThat(resp.isAuthenticated(), is(RESP.TRY_AUTHENTICATING));
+
+ redirectables = new ArrayList<>();
+ resp = LoginPageTafResp.create(access, locatorMock, respMock, redirectables);
+ assertThat(resp.desc(), is("All Authentication denied"));
+
+ }
+
+}
package org.onap.aaf.cadi.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.mockito.Mockito.*;
-import org.junit.*;
-import org.mockito.*;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.onap.aaf.cadi.AbsUserCache;
-import org.onap.aaf.cadi.AbsUserCache.*;
import org.onap.aaf.cadi.Access;
import org.onap.aaf.cadi.CachedPrincipal.Resp;
import org.onap.aaf.cadi.CachingLur;
import org.onap.aaf.cadi.GetCred;
-import org.onap.aaf.cadi.Hash;
import org.onap.aaf.cadi.Permission;
import org.onap.aaf.cadi.PropAccess;
import org.onap.aaf.cadi.User;
public class JU_AbsUserCache {
@Mock private CachingLur<Permission> cl;
-
@Mock private Principal principal;
-
@Mock private CachedBasicPrincipal cbp;
-
@Mock private LocalPermission permission1;
@Mock private LocalPermission permission2;
-
private Access access;
private String name1 = "name1";
private String name2 = "name2";
private byte[] password = "password".getBytes();
-
+
private static Field timerField;
@BeforeClass
@Test
public void handlesExclusivelyTest() {
- AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE);
+ AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE);
assertFalse(aucs.handlesExclusively(permission1));
assertFalse(aucs.handlesExclusively(permission2));
}
@Test
public void destroyTest() {
- AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE);
+ AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE);
aucs.destroy();
- aucs = new AbsUserCacheStub<Permission>(access, 1, 1, Integer.MAX_VALUE);
+ aucs = new AbsUserCacheStub<Permission>(access, 1, 1, Integer.MAX_VALUE);
aucs.destroy();
}
@Test
public void missTest() throws IOException {
- AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE);
+ AbsUserCacheStub<Permission> aucs = new AbsUserCacheStub<Permission>(access, 0, 0, Integer.MAX_VALUE);
// Add the Miss to the missmap
assertTrue(aucs.addMiss("key", password)); // This one actually adds it
assertTrue(aucs.addMiss("key", password)); // this one doesn't really do anything
}
class AbsUserCacheStub<PERM extends Permission> extends AbsUserCache<PERM> {
- public AbsUserCacheStub(Access access, long cleanInterval, int highCount, int usageCount) { super(access, cleanInterval, highCount, usageCount); }
- public AbsUserCacheStub(AbsUserCache<PERM> cache) { super(cache); }
- @Override public void setLur(CachingLur<PERM> lur) { super.setLur(lur); }
- @Override public void addUser(User<PERM> user) { super.addUser(user); }
- @Override public void addUser(String key, User<PERM> user) { super.addUser(key, user); }
- @Override public User<PERM> getUser(Principal p) { return super.getUser(p); }
- @Override public User<PERM> getUser(CachedBasicPrincipal p) { return super.getUser(p); }
- @Override public User<PERM> getUser(String user, byte[] cred) { return super.getUser(user, cred); }
+ public AbsUserCacheStub(Access access, long cleanInterval, int highCount, int usageCount) { super(access, cleanInterval, highCount, usageCount); }
+ public AbsUserCacheStub(AbsUserCache<PERM> cache) { super(cache); }
+ @Override public void setLur(CachingLur<PERM> lur) { super.setLur(lur); }
+ @Override public void addUser(User<PERM> user) { super.addUser(user); }
+ @Override public void addUser(String key, User<PERM> user) { super.addUser(key, user); }
+ @Override public User<PERM> getUser(Principal p) { return super.getUser(p); }
+ @Override public User<PERM> getUser(CachedBasicPrincipal p) { return super.getUser(p); }
+ @Override public User<PERM> getUser(String user, byte[] cred) { return super.getUser(user, cred); }
@Override public void remove(User<PERM> user) { super.remove(user); }
@Override public boolean addMiss(String key, byte[] bs) { return super.addMiss(key, bs); }
@Override public Miss missed(String key, byte[] bs) throws IOException { return super.missed(key, bs); }
}
class AbsUserCacheCLStub<PERM extends Permission> extends AbsUserCache<PERM> implements CachingLur<PERM> {
- public AbsUserCacheCLStub(AbsUserCache<PERM> cache) { super(cache); }
- @Override public Permission createPerm(String p) { return null; }
- @Override public boolean fish(Principal bait, Permission pond) { return false; }
- @Override public void fishAll(Principal bait, List<Permission> permissions) { }
- @Override public boolean handles(Principal principal) { return false; }
- @Override public Resp reload(User<PERM> user) { return null; }
+ public AbsUserCacheCLStub(AbsUserCache<PERM> cache) { super(cache); }
+ @Override public Permission createPerm(String p) { return null; }
+ @Override public boolean fish(Principal bait, Permission pond) { return false; }
+ @Override public void fishAll(Principal bait, List<Permission> permissions) { }
+ @Override public boolean handles(Principal principal) { return false; }
+ @Override public Resp reload(User<PERM> user) { return null; }
@Override public void setDebug(String commaDelimIDsOrNull) { }
}
******************************************************************************/
package org.onap.aaf.cadi.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import org.junit.*;
-import org.mockito.*;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.file.Paths;
import java.util.Properties;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.onap.aaf.cadi.CmdLine;
-import org.onap.aaf.cadi.PropAccess;
import org.onap.aaf.cadi.Symm;
public class JU_CmdLine {
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
- System.setOut(new PrintStream(outContent));
+ System.setOut(new PrintStream(outContent));
Properties p = new Properties();
p.setProperty("force_exit", "false");
- CmdLine.access = new PropAccess(p);
+ CmdLine.setSystemExit(false);
keyfile = "src/test/resources/keyfile";
password = "password";
@After
public void restoreStreams() throws IOException {
- System.setOut(System.out);
- System.setIn(System.in);
+ System.setOut(System.out);
+ System.setIn(System.in);
}
@Test
assertThat(decrypted, is(password));
}
- // @Test
- // public void regurgitateTest() {
- // // TODO: We may still want to remove the regurgitate functionality
- // // from the CmdLine - Ian
- // fail("Tests not yet implemented");
- // }
-
@Test
public void encode64Test() throws Exception {
CmdLine.main(new String[]{"encode64", password});
@Test
public void convertTest1() {
- String test = "te%t";
List<String> list = new ArrayList<String>();
list.add("method");
assertEquals(Vars.convert("test", list), "test");
@Test
public void convertTest2() {
- String test = "te%s%t";
List<String> list = new ArrayList<String>();
list.add("method");
assertEquals(Vars.convert("test", list), "test");
--- /dev/null
+/*******************************************************************************
+* ============LICENSE_START====================================================
+* * org.onap.aaf
+* * ===========================================================================
+* * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+* * ===========================================================================
+* * Licensed 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.
+* * ============LICENSE_END====================================================
+* *
+* *
+******************************************************************************/
+package org.onap.aaf.cadi.wsse.test;
+
+import org.junit.Test;
+import org.onap.aaf.cadi.wsse.WSSEParser;
+
+public class JU_WSSEParser {
+
+ @Test
+ public void test() {
+ @SuppressWarnings("unused")
+ WSSEParser wp = new WSSEParser();
+
+ // TODO: test the rest of this class
+// final BasicCred bc = new BasicCred() {
+// private String user;
+// private byte[] password;
+//
+// public void setUser(String user) { this.user = user; }
+// public void setCred(byte[] passwd) { this.password = passwd; }
+// public String getUser() { return user; }
+// public byte[] getCred() { return password; }
+// };
+
+// FileInputStream fis;
+// fis = new FileInputStream("test/example.xml");
+// BufferedServletInputStream is = new BufferedServletInputStream(fis);
+// try {
+// is.mark(1536);
+// try {
+// assertNull(wp.parse(bc, is));
+// } finally {
+// is.reset();
+// assertEquals(814,is.buffered());
+// }
+// String password = new String(bc.getCred());
+// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password);
+// assertEquals("some_user", bc.getUser());
+// assertEquals("some_password", password);
+//
+// } finally {
+// fis.close();
+// }
+//
+// // CBUS (larger)
+// fis = new FileInputStream("test/CBUSevent.xml");
+// is = new BufferedServletInputStream(fis);
+// try {
+// is.mark(1536);
+// try {
+// assertNull(wp.parse(bc, is));
+// } finally {
+// is.reset();
+// assertEquals(667,is.buffered());
+// }
+// String password = new String(bc.getCred());
+// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password);
+// assertEquals("none", bc.getUser());
+// assertEquals("none", password);
+//
+// } finally {
+// fis.close();
+// }
+//
+// // Closed Stream
+// fis = new FileInputStream("test/example.xml");
+// fis.close();
+// bc.setCred(null);
+// bc.setUser(null);
+// XMLStreamException ex = wp.parse(bc, fis);
+// assertNotNull(ex);
+// assertNull(bc.getUser());
+// assertNull(bc.getCred());
+//
+//
+// fis = new FileInputStream("test/exampleNoSecurity.xml");
+// try {
+// bc.setCred(null);
+// bc.setUser(null);
+// assertNull(wp.parse(bc, fis));
+// assertNull(bc.getUser());
+// assertNull(bc.getCred());
+// } finally {
+// fis.close();
+// }
+//
+// fis = new FileInputStream("test/exampleBad1.xml");
+// try {
+// bc.setCred(null);
+// bc.setUser(null);
+// assertNull(wp.parse(bc, fis));
+// assertNull(bc.getUser());
+// assertNull(bc.getCred());
+// } finally {
+// fis.close();
+// }
+//
+// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty
+// assertNotNull(e);
+//
+// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty
+// assertNotNull(e);
+//
+//
+// long start, count = 0L;
+// int iter = 30000;
+// File f = new File("test/CBUSevent.xml");
+// fis = new FileInputStream(f);
+// is = new BufferedServletInputStream(fis);
+// is.mark(0);
+// try {
+// while(is.read()>=0);
+// } finally {
+// fis.close();
+// }
+//
+// for(int i=0;i<iter;++i) {
+// start = System.nanoTime();
+// is.reset();
+// try {
+// assertNull(wp.parse(bc, is));
+// } finally {
+// count += System.nanoTime()-start;
+// }
+// }
+// float ms = count/1000000f;
+// System.out.println("Executed " + iter + " WSSE reads from Memory Stream in " + ms + "ms. " + ms/iter + "ms per trans");
+//
+// // SPECIFIC ISSUES
+//
+// fis = new FileInputStream("test/error2013_04_23.xml");
+// try {
+// bc.setCred(null);
+// bc.setUser(null);
+// assertNull(wp.parse(bc, fis));
+// assertNull(bc.getUser());
+// assertNull(bc.getCred());
+// } finally {
+// fis.close();
+// }
+ }
+
+}
+++ /dev/null
-/*******************************************************************************
- * ============LICENSE_START====================================================
- * * org.onap.aaf
- * * ===========================================================================
- * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * * ===========================================================================
- * * Licensed 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.
- * * ============LICENSE_END====================================================
- * *
- * *
- ******************************************************************************/
-package org.onap.aaf.cadi.wsse.test;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertNull;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-
-import javax.xml.stream.XMLStreamException;
-
-import org.junit.Test;
-import org.onap.aaf.cadi.BasicCred;
-import org.onap.aaf.cadi.BufferedServletInputStream;
-import org.onap.aaf.cadi.wsse.WSSEParser;
-
-public class JU_WSSE_Read {
-
-// @Test
-// public void test() {
-// try {
-// final BasicCred bc = new BasicCred() {
-
-// private String user;
-// private byte[] password;
-
-// public void setUser(String user) {
-// this.user = user;
-// }
-
-// public void setCred(byte[] passwd) {
-// this.password = passwd;
-// }
-
-// public String getUser() {
-// return user;
-// }
-
-// public byte[] getCred() {
-// return password;
-// }
-// };
-
-// WSSEParser wp = new WSSEParser();
-
-// FileInputStream fis;
-// fis = new FileInputStream("test/example.xml");
-// BufferedServletInputStream is = new BufferedServletInputStream(fis);
-// try {
-// is.mark(1536);
-// try {
-// assertNull(wp.parse(bc, is));
-// } finally {
-// is.reset();
-// assertEquals(814,is.buffered());
-// }
-// String password = new String(bc.getCred());
-// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password);
-// assertEquals("some_user", bc.getUser());
-// assertEquals("some_password", password);
-
-// } finally {
-// fis.close();
-// }
-
-// // CBUS (larger)
-// fis = new FileInputStream("test/CBUSevent.xml");
-// is = new BufferedServletInputStream(fis);
-// try {
-// is.mark(1536);
-// try {
-// assertNull(wp.parse(bc, is));
-// } finally {
-// is.reset();
-// assertEquals(667,is.buffered());
-// }
-// String password = new String(bc.getCred());
-// System.out.println("CadiWrap credentials are: " + bc.getUser() + ", " + password);
-// assertEquals("none", bc.getUser());
-// assertEquals("none", password);
-
-// } finally {
-// fis.close();
-// }
-
-// // Closed Stream
-// fis = new FileInputStream("test/example.xml");
-// fis.close();
-// bc.setCred(null);
-// bc.setUser(null);
-// XMLStreamException ex = wp.parse(bc, fis);
-// assertNotNull(ex);
-// assertNull(bc.getUser());
-// assertNull(bc.getCred());
-
-
-// fis = new FileInputStream("test/exampleNoSecurity.xml");
-// try {
-// bc.setCred(null);
-// bc.setUser(null);
-// assertNull(wp.parse(bc, fis));
-// assertNull(bc.getUser());
-// assertNull(bc.getCred());
-// } finally {
-// fis.close();
-// }
-
-// fis = new FileInputStream("test/exampleBad1.xml");
-// try {
-// bc.setCred(null);
-// bc.setUser(null);
-// assertNull(wp.parse(bc, fis));
-// assertNull(bc.getUser());
-// assertNull(bc.getCred());
-// } finally {
-// fis.close();
-// }
-
-// XMLStreamException e = wp.parse(bc, new ByteArrayInputStream("Not XML".getBytes())); // empty
-// assertNotNull(e);
-
-// e = wp.parse(bc, new ByteArrayInputStream("".getBytes())); // empty
-// assertNotNull(e);
-
-
-// long start, count = 0L;
-// int iter = 30000;
-// File f = new File("test/CBUSevent.xml");
-// fis = new FileInputStream(f);
-// is = new BufferedServletInputStream(fis);
-// is.mark(0);
-// try {
-// while(is.read()>=0);
-// } finally {
-// fis.close();
-// }
-
-// for(int i=0;i<iter;++i) {
-// start = System.nanoTime();
-// is.reset();
-// try {
-// assertNull(wp.parse(bc, is));
-// } finally {
-// count += System.nanoTime()-start;
-// }
-// }
-// float ms = count/1000000f;
-// System.out.println("Executed " + iter + " WSSE reads from Memory Stream in " + ms + "ms. " + ms/iter + "ms per trans");
-
-// // SPECIFIC ISSUES
-
-// fis = new FileInputStream("test/error2013_04_23.xml");
-// try {
-// bc.setCred(null);
-// bc.setUser(null);
-// assertNull(wp.parse(bc, fis));
-// assertNull(bc.getUser());
-// assertNull(bc.getCred());
-// } finally {
-// fis.close();
-// }
-// } catch(Exception e) {
-// e.printStackTrace(System.err);
-// }
-// }
-
-}
******************************************************************************/
package org.onap.aaf.cadi.wsse.test;
-import static org.junit.Assert.*;
-import static org.hamcrest.CoreMatchers.*;
-import org.junit.*;
+import static org.junit.Assert.assertThat;
+import static org.hamcrest.CoreMatchers.is;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
import org.onap.aaf.cadi.wsse.XEvent;
import org.onap.aaf.cadi.wsse.XReader;
}
}
- // @Test
- // public void tagTest() {
- // String prefix = "prefix";
- // String name = "name";
- // String value = "value";
- // XReader.Tag tag = new Tag(prefix, name, value);
-
- // assertThat(tag.toString(), is(prefix + ':' + name + "=\'" + value + "'"));
- // }
-
-
private static XEvent getNextEvent(XReader xr) throws XMLStreamException {
if (xr.hasNext()) {
return xr.nextEvent();
<properties>
<!-- SONAR -->
- <!-- <sonar.skip>true</sonar.skip> -->
+ <sonar.skip>true</sonar.skip>
<jacoco.version>0.7.7.201606060606</jacoco.version>
<sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<properties>
<!-- SONAR -->
- <!-- <sonar.skip>true</sonar.skip> -->
+ <sonar.skip>true</sonar.skip>
<jacoco.version>0.7.7.201606060606</jacoco.version>
<sonar-jacoco-listeners.version>3.2</sonar-jacoco-listeners.version>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
import org.onap.aaf.cadi.Access.Level;
/**
- * We treate "roles" and "permissions" in a similar way for first pass.
+ * We treat "roles" and "permissions" in a similar way for first pass.
*
- * @author jg1555
+ * @author JonathanGathman
*
*/
public class AAFAuthorizationInfo implements AuthorizationInfo {
if [ "$1" = "" -o "$1" = "-local" ]; then
echo "Personal Certificate"
SUBJECT="/CN=$FQI/OU=V1`cat subject.aaf`"
+ NAME=$FQI
else
echo "Application Certificate"
SUBJECT="/CN=$1/OU=$FQI`cat subject.aaf`"
- FQI=$1
+ FQDN=$1
+ NAME=$FQDN
shift
+
+ echo "Enter any SANS, delimited by spaces: "
+ read SANS
+fi
+
+# Do SANs
+if [ "$SANS" = "" ]; then
+ echo no SANS
+ if [ -e $NAME.san ]; then
+ rm $NAME.san
+ fi
+ else
+ echo some SANS
+ cp ../san.conf $NAME.san
+ NUM=1
+ for D in $SANS; do
+ echo "DNS.$NUM = $D" >> $NAME.san
+ NUM=$((NUM+1))
+ done
fi
+
echo $SUBJECT
-if [ -e $FQI.csr ]; then
+if [ -e $NAME.csr ]; then
SIGN_IT=true
else
if [ "$1" = "-local" ]; then
`stty echo`
# remove any previous Private key
- rm private/$FQI.key
+ rm private/$NAME.key
# Create j regaular rsa encrypted key
- openssl req -new -newkey rsa:2048 -sha256 -keyout private/$FQI.key \
- -out $FQI.csr -outform PEM -subj "$SUBJECT" \
+ openssl req -new -newkey rsa:2048 -sha256 -keyout private/$NAME.key \
+ -out $NAME.csr -outform PEM -subj "$SUBJECT" \
-passout stdin << EOF
$PASSPHRASE
EOF
- chmod 400 private/$FQI.key
+ chmod 400 private/$NAME.key
SIGN_IT=true
else
- echo openssl req -newkey rsa:2048 -sha256 -keyout $FQI.key -out $FQI.csr -outform PEM -subj '"'$SUBJECT'"'
- echo chmod 400 $FQI.key
+ echo openssl req -newkey rsa:2048 -sha256 -keyout $NAME.key -out $NAME.csr -outform PEM -subj '"'$SUBJECT'"'
+ echo chmod 400 $NAME.key
echo "# All done, print result"
- echo openssl req -verify -text -noout -in $FQI.csr
+ echo openssl req -verify -text -noout -in $NAME.csr
fi
fi
if [ "$SIGN_IT" = "true" ]; then
# Sign it
- openssl ca -config ../openssl.conf -extensions server_cert -out $FQI.crt \
+ if [ -e $NAME.san ]; then
+ openssl ca -config ../openssl.conf -extensions server_cert -out $NAME.crt \
+ -cert certs/ca.crt -keyfile private/ca.key \
+ -policy policy_loose \
+ -days 360 \
+ -extfile $NAME.san \
+ -infiles $NAME.csr
+ else
+ openssl ca -config ../openssl.conf -extensions server_cert -out $NAME.crt \
-cert certs/ca.crt -keyfile private/ca.key \
-policy policy_loose \
-days 360 \
- -infiles $FQI.csr
+ -infiles $NAME.csr
+ fi
fi
-
-
-
--- /dev/null
+# SAN Extension
+# Copy, then add DNS.1 = name, etc
+#
+[ server_cert ]
+# Extensions for server certificates (`man x509v3_config`).
+basicConstraints = CA:FALSE
+nsCertType = server, client
+nsComment = "OpenSSL Generated Server Certificate"
+subjectKeyIdentifier = hash
+authorityKeyIdentifier = keyid,issuer:always
+keyUsage = critical, digitalSignature, keyEncipherment, nonRepudiation
+extendedKeyUsage = serverAuth, clientAuth
+subjectAltName = @alt_names
+
+[ alt_names ]
echo "FYI, by convention, truststore passwords are 'changeit', but you may add something more sophisticated"
-openssl pkcs12 -export -name AAF_Root_CA -in certs/ca.crt -inkey private/ca.key -out truststore.p12
+openssl pkcs12 -export -name AAF_Root_CA -in certs/ca.crt -nokeys -out truststore.p12
--- /dev/null
+# Property file to test property loading\r
+prop1 = New Property\r
+single prop
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-/**
- * An Exception with the ability to hold a payload.<p>
- *
- * This is important, because sometimes, the output of a Framework
- * may be a descriptive object which doesn't inherit from Throwable
- * and thus cannot be attached in "initCause".<p>
- *
- * Examples may be a SOAP Fault.
- *
- * @author Jonathan
- *
- */
-public class APIException extends Exception {
-
- private Object payload = null;
-
- /**
- * @param t
- */
- public APIException(Throwable t) {
- super(t);
- }
-
- /**
- * @param string
- */
- public APIException(String string) {
- super(string);
- }
-
- /**
- * @param errorMessage
- * @param t
- */
- public APIException(String errorMessage, Throwable t) {
- super(errorMessage,t);
- }
-
- /**
- * Return payload, or null if none was set. Type is up to the calling
- * System.
- *
- * @return Object
- */
- public Object getPayload() {
- return payload;
- }
-
- /**
- * Set a specific payload into this Exception, which doesn't necessarily
- * inherit from Throwable.
- *
- * @param payload
- * @return APIException
- */
- public APIException setPayload(Object payload) {
- this.payload = payload;
- return this;
- }
-
- /**
- * Java expected serial ID
- */
- private static final long serialVersionUID = 3505343458251445169L;
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+/**\r
+ * An Exception with the ability to hold a payload.<p>\r
+ * \r
+ * This is important, because sometimes, the output of a Framework\r
+ * may be a descriptive object which doesn't inherit from Throwable\r
+ * and thus cannot be attached in "initCause".<p>\r
+ * \r
+ * Examples may be a SOAP Fault.\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public class APIException extends Exception {\r
+ \r
+ private Object payload = null;\r
+ \r
+ /**\r
+ * @param t\r
+ */\r
+ public APIException(Throwable t) {\r
+ super(t);\r
+ }\r
+ \r
+ /**\r
+ * @param string\r
+ */\r
+ public APIException(String string) {\r
+ super(string);\r
+ }\r
+\r
+ /**\r
+ * @param errorMessage\r
+ * @param t\r
+ */\r
+ public APIException(String errorMessage, Throwable t) {\r
+ super(errorMessage,t);\r
+ }\r
+\r
+ /**\r
+ * Return payload, or null if none was set. Type is up to the calling\r
+ * System.\r
+ * \r
+ * @return Object\r
+ */\r
+ public Object getPayload() {\r
+ return payload;\r
+ }\r
+\r
+ /**\r
+ * Set a specific payload into this Exception, which doesn't necessarily\r
+ * inherit from Throwable.\r
+ * \r
+ * @param payload\r
+ * @return APIException\r
+ */\r
+ public APIException setPayload(Object payload) {\r
+ this.payload = payload;\r
+ return this;\r
+ }\r
+\r
+ /**\r
+ * Java expected serial ID\r
+ */\r
+ private static final long serialVersionUID = 3505343458251445169L;\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-import javax.xml.XMLConstants;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlSchema;
-import javax.xml.namespace.QName;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-
-import org.onap.aaf.misc.env.impl.EnvFactory;
-import org.xml.sax.SAXException;
-
-
-
-/**
- * DataFactory Constructor will create the Stringifiers and Objectifiers necessary
- * by Type and store the Class of the Type for quick creation of Data Objects
- * with reused (and thread safe) components
- * s
- * Native Types are included.
- * Those types covered by Env Implementation are covered dynamically.
- * Types outside of Env mechanism can be added with "add" function
- *
- * @author Jonathan
- *
- * @param <T>
- */
-public class BaseDataFactory {
- private static final Object LOCK = new Object();
- /**
- * Generate a Schema Object for use in validation based on FileNames.
- *
- * WARNING: The java.xml.binding code requires YOU to figure out what order the
- * files go in. If there is an import from A in B, then you must list A first.
- *
- * @param err
- * @param filenames
- * @return
- * @throws APIException
- */
- public static Schema genSchema(Store env, String ... filenames) throws APIException {
- String schemaDir = env.get(
- env.staticSlot(EnvFactory.SCHEMA_DIR),
- EnvFactory.DEFAULT_SCHEMA_DIR);
- File dir = new File(schemaDir);
- if(!dir.exists())throw new APIException("Schema Directory " + schemaDir + " does not exist. You can set this with " + EnvFactory.SCHEMA_DIR + " property");
- FileInputStream[] fis = new FileInputStream[filenames.length];
- Source[] sources = new Source[filenames.length];
- File f;
- for(int i=0; i<filenames.length; ++i) {
- if(!(f=new File(schemaDir + File.separatorChar + filenames[i])).exists()) {
- if(!f.exists()) throw new APIException("Cannot find " + f.getName() + " for schema validation");
- }
- try {
- fis[i]=new FileInputStream(f);
- } catch (FileNotFoundException e) {
- throw new APIException(e);
- }
- sources[i]= new StreamSource(fis[i]);
- }
- try {
- //Note: SchemaFactory is not reentrant or very thread safe either... see docs
- synchronized(LOCK) { // SchemaFactory is not reentrant
- return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
- .newSchema(sources);
- }
- } catch (SAXException e) {
- throw new APIException(e);
- } finally {
- for(FileInputStream d : fis) {
- try {
- d.close();
- } catch (IOException e) {
- // Never mind... we did our best
- }
- }
- }
-
- }
-
- public static QName getQName(Class<?> clss) throws APIException {
- // Obtain the Necessary info for QName from Requirement
- XmlRootElement xre = clss.getAnnotation(XmlRootElement.class);
- if(xre==null)throw new APIException(clss.getName() + " does not have an XmlRootElement annotation");
- Package pkg = clss.getPackage();
- XmlSchema xs = pkg.getAnnotation(XmlSchema.class);
- if(xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation");
- return new QName(xs.namespace(),xre.name());
- }
-
- /////////////////////////////////////////////
- // Native Type Converters
- /////////////////////////////////////////////
-// /**
-// * StringStringifier
-// *
-// * Support the Native Type String.. just return it back
-// *
-// * @author Jonathan
-// *
-// */
-// public static class StringStringifier extends NullLifeCycle implements Stringifier<String> {
-// /* (non-Javadoc)
-// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)
-// */
-// public String stringify(Env env, String input) throws APIException {
-// return input;
-// }
-// };
-//
-// /**
-// * StringObjectifier
-// *
-// * Support the Native Type String.. just return it back
-// *
-// * @author Jonathan
-// *
-// */
-// public static class StringObjectifier extends NullLifeCycle implements Objectifier<String> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public String objectify(Env env, String input) throws APIException {
-// return input;
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public String newInstance() throws APIException {
-// return "";
-// }
-// };
-//
-// /**
-// * LongStringifier
-// *
-// * Support the Native Type Long.. use Long parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class LongStringifier extends NullLifeCycle implements Stringifier<Long> {
-// public String stringify(Env env, Long input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * LongObjectifier
-// *
-// * Support the Native Type Long.. use Long parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class LongObjectifier extends NullLifeCycle implements Objectifier<Long> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public Long objectify(Env env, String input) throws APIException {
-// try {
-// return new Long(input);
-// } catch (Exception e) {
-// APIException ae = new APIException("Cannot create a \"Long\" from [" + input + ']');
-// ae.initCause(e);
-// throw ae;
-// }
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public Long newInstance() throws APIException {
-// return 0L;
-// }
-// }
-//
-// /**
-// * IntegerStringifier
-// *
-// * Support the Native Integer.. use Integer parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class IntegerStringifier extends NullLifeCycle implements Stringifier<Integer> {
-// /* (non-Javadoc)
-// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)
-// */
-// public String stringify(Env env, Integer input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * IntegerObjectifier
-// *
-// * Support the Native Integer.. use Integer parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class IntegerObjectifier extends NullLifeCycle implements Objectifier<Integer> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public Integer objectify(Env env, String input) throws APIException {
-// try {
-// return new Integer(input);
-// } catch (Exception e) {
-// APIException ae = new APIException("Cannot create a \"Integer\" from [" + input + ']');
-// ae.initCause(e);
-// throw ae;
-// }
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public Integer newInstance() throws APIException {
-// return 0;
-// }
-// }
-//
-// /**
-// * ShortStringifier
-// *
-// * Support the Native Short.. use Short parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class ShortStringifier extends NullLifeCycle implements Stringifier<Short> {
-// public String stringify(Env env, Short input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * ShortObjectifier
-// *
-// * Support the Native Short.. use Short parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class ShortObjectifier extends NullLifeCycle implements Objectifier<Short> {
-// public Short objectify(Env env, String input) throws APIException {
-// try {
-// return new Short(input);
-// } catch (Exception e) {
-// APIException ae = new APIException("Cannot create a \"Short\" from [" + input + ']');
-// ae.initCause(e);
-// throw ae;
-// }
-// }
-//
-// public Short newInstance() throws APIException {
-// return 0;
-// }
-// }
-//
-// /**
-// * ByteStringifier
-// *
-// * Support the Native Byte.. use Byte parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class ByteStringifier extends NullLifeCycle implements Stringifier<Byte> {
-// /* (non-Javadoc)
-// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)
-// */
-// public String stringify(Env env, Byte input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * ByteObjectifier
-// *
-// * Support the Native Byte.. use Byte parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class ByteObjectifier extends NullLifeCycle implements Objectifier<Byte> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public Byte objectify(Env env, String input) throws APIException {
-// try {
-// return new Byte(input);
-// } catch (Exception e) {
-// APIException ae = new APIException("Cannot create a \"Byte\" from [" + input + ']');
-// ae.initCause(e);
-// throw ae;
-// }
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public Byte newInstance() throws APIException {
-// return 0;
-// }
-// }
-//
-// /**
-// * CharacterStringifier
-// *
-// * Support the Native Character.. use Character parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class CharacterStringifier extends NullLifeCycle implements Stringifier<Character> {
-// /* (non-Javadoc)
-// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)
-// */
-// public String stringify(Env env, Character input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * CharacterObjectifier
-// *
-// * Support the Native Character.. use Character parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class CharacterObjectifier extends NullLifeCycle implements Objectifier<Character> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public Character objectify(Env env, String input) throws APIException {
-// int length = input.length();
-// if(length<1 || length>1) {
-// throw new APIException("String [" + input + "] does not represent a single Character");
-// }
-// return input.charAt(0);
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public Character newInstance() throws APIException {
-// return 0;
-// }
-// }
-//
-// /**
-// * FloatStringifier
-// *
-// * Support the Native Float.. use Float parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class FloatStringifier extends NullLifeCycle implements Stringifier<Float> {
-// /* (non-Javadoc)
-// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)
-// */
-// public String stringify(Env env, Float input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * FloatObjectifier
-// *
-// * Support the Native Float.. use Float parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class FloatObjectifier extends NullLifeCycle implements Objectifier<Float> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public Float objectify(Env env, String input) throws APIException {
-// try {
-// return new Float(input);
-// } catch (Exception e) {
-// APIException ae = new APIException("Cannot create a \"Float\" from [" + input + ']');
-// ae.initCause(e);
-// throw ae;
-// }
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public Float newInstance() throws APIException {
-// return 0.0f;
-// }
-// }
-//
-// /**
-// * DoubleStringifier
-// *
-// * Support the Native Double.. use Double parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class DoubleStringifier extends NullLifeCycle implements Stringifier<Double> {
-// /* (non-Javadoc)
-// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)
-// */
-// public String stringify(Env env, Double input) throws APIException {
-// return input.toString();
-// }
-// }
-//
-// /**
-// * DoubleObjectifier
-// *
-// * Support the Native Double.. use Double parse functions
-// *
-// * @author Jonathan
-// *
-// */
-// public static class DoubleObjectifier extends NullLifeCycle implements Objectifier<Double> {
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)
-// */
-// public Double objectify(Env env, String input) throws APIException {
-// try {
-// return new Double(input);
-// } catch (Exception e) {
-// APIException ae = new APIException("Cannot create a \"Double\" from [" + input + ']');
-// ae.initCause(e);
-// throw ae;
-// }
-// }
-//
-// /* (non-Javadoc)
-// * @see com.att.env.Objectifier#newObject()
-// */
-// public Double newInstance() throws APIException {
-// return 0.0;
-// }
-// }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+\r
+import javax.xml.XMLConstants;\r
+import javax.xml.bind.annotation.XmlRootElement;\r
+import javax.xml.bind.annotation.XmlSchema;\r
+import javax.xml.namespace.QName;\r
+import javax.xml.transform.Source;\r
+import javax.xml.transform.stream.StreamSource;\r
+import javax.xml.validation.Schema;\r
+import javax.xml.validation.SchemaFactory;\r
+\r
+import org.onap.aaf.misc.env.impl.EnvFactory;\r
+import org.xml.sax.SAXException;\r
+\r
+\r
+\r
+/**\r
+ * DataFactory Constructor will create the Stringifiers and Objectifiers necessary \r
+ * by Type and store the Class of the Type for quick creation of Data Objects\r
+ * with reused (and thread safe) components\r
+ * s\r
+ * Native Types are included.\r
+ * Those types covered by Env Implementation are covered dynamically.\r
+ * Types outside of Env mechanism can be added with "add" function\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ * @param <T>\r
+ */\r
+public class BaseDataFactory {\r
+ private static final Object LOCK = new Object();\r
+ /**\r
+ * Generate a Schema Object for use in validation based on FileNames.\r
+ * \r
+ * WARNING: The java.xml.binding code requires YOU to figure out what order the\r
+ * files go in. If there is an import from A in B, then you must list A first.\r
+ * \r
+ * @param err\r
+ * @param filenames\r
+ * @return\r
+ * @throws APIException\r
+ */\r
+ public static Schema genSchema(Store env, String ... filenames) throws APIException {\r
+ String schemaDir = env.get(\r
+ env.staticSlot(EnvFactory.SCHEMA_DIR),\r
+ EnvFactory.DEFAULT_SCHEMA_DIR);\r
+ File dir = new File(schemaDir);\r
+ if(!dir.exists())throw new APIException("Schema Directory " + schemaDir + " does not exist. You can set this with " + EnvFactory.SCHEMA_DIR + " property");\r
+ FileInputStream[] fis = new FileInputStream[filenames.length];\r
+ Source[] sources = new Source[filenames.length];\r
+ File f; \r
+ for(int i=0; i<filenames.length; ++i) {\r
+ if(!(f=new File(schemaDir + File.separatorChar + filenames[i])).exists()) {\r
+ if(!f.exists()) throw new APIException("Cannot find " + f.getName() + " for schema validation");\r
+ }\r
+ try {\r
+ fis[i]=new FileInputStream(f);\r
+ } catch (FileNotFoundException e) {\r
+ throw new APIException(e);\r
+ }\r
+ sources[i]= new StreamSource(fis[i]);\r
+ }\r
+ try {\r
+ //Note: SchemaFactory is not reentrant or very thread safe either... see docs\r
+ synchronized(LOCK) { // SchemaFactory is not reentrant\r
+ return SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)\r
+ .newSchema(sources);\r
+ }\r
+ } catch (SAXException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ for(FileInputStream d : fis) {\r
+ try {\r
+ d.close();\r
+ } catch (IOException e) {\r
+ // Never mind... we did our best\r
+ }\r
+ }\r
+ }\r
+\r
+ }\r
+\r
+ public static QName getQName(Class<?> clss) throws APIException {\r
+ // Obtain the Necessary info for QName from Requirement\r
+ XmlRootElement xre = clss.getAnnotation(XmlRootElement.class);\r
+ if(xre==null)throw new APIException(clss.getName() + " does not have an XmlRootElement annotation");\r
+ Package pkg = clss.getPackage();\r
+ XmlSchema xs = pkg.getAnnotation(XmlSchema.class);\r
+ if(xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation");\r
+ return new QName(xs.namespace(),xre.name());\r
+ }\r
+\r
+ /////////////////////////////////////////////\r
+ // Native Type Converters\r
+ /////////////////////////////////////////////\r
+// /**\r
+// * StringStringifier\r
+// * \r
+// * Support the Native Type String.. just return it back\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class StringStringifier extends NullLifeCycle implements Stringifier<String> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)\r
+// */\r
+// public String stringify(Env env, String input) throws APIException {\r
+// return input;\r
+// }\r
+// }; \r
+//\r
+// /**\r
+// * StringObjectifier\r
+// * \r
+// * Support the Native Type String.. just return it back\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class StringObjectifier extends NullLifeCycle implements Objectifier<String> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public String objectify(Env env, String input) throws APIException {\r
+// return input;\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public String newInstance() throws APIException {\r
+// return "";\r
+// }\r
+// };\r
+// \r
+// /**\r
+// * LongStringifier\r
+// * \r
+// * Support the Native Type Long.. use Long parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class LongStringifier extends NullLifeCycle implements Stringifier<Long> {\r
+// public String stringify(Env env, Long input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * LongObjectifier\r
+// * \r
+// * Support the Native Type Long.. use Long parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class LongObjectifier extends NullLifeCycle implements Objectifier<Long> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public Long objectify(Env env, String input) throws APIException {\r
+// try {\r
+// return new Long(input);\r
+// } catch (Exception e) {\r
+// APIException ae = new APIException("Cannot create a \"Long\" from [" + input + ']');\r
+// ae.initCause(e);\r
+// throw ae;\r
+// }\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public Long newInstance() throws APIException {\r
+// return 0L;\r
+// }\r
+// }\r
+//\r
+// /**\r
+// * IntegerStringifier\r
+// * \r
+// * Support the Native Integer.. use Integer parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class IntegerStringifier extends NullLifeCycle implements Stringifier<Integer> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)\r
+// */\r
+// public String stringify(Env env, Integer input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * IntegerObjectifier\r
+// * \r
+// * Support the Native Integer.. use Integer parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class IntegerObjectifier extends NullLifeCycle implements Objectifier<Integer> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public Integer objectify(Env env, String input) throws APIException {\r
+// try {\r
+// return new Integer(input);\r
+// } catch (Exception e) {\r
+// APIException ae = new APIException("Cannot create a \"Integer\" from [" + input + ']');\r
+// ae.initCause(e);\r
+// throw ae;\r
+// }\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public Integer newInstance() throws APIException {\r
+// return 0;\r
+// }\r
+// }\r
+//\r
+// /**\r
+// * ShortStringifier\r
+// * \r
+// * Support the Native Short.. use Short parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class ShortStringifier extends NullLifeCycle implements Stringifier<Short> {\r
+// public String stringify(Env env, Short input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * ShortObjectifier\r
+// * \r
+// * Support the Native Short.. use Short parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class ShortObjectifier extends NullLifeCycle implements Objectifier<Short> {\r
+// public Short objectify(Env env, String input) throws APIException {\r
+// try {\r
+// return new Short(input);\r
+// } catch (Exception e) {\r
+// APIException ae = new APIException("Cannot create a \"Short\" from [" + input + ']');\r
+// ae.initCause(e);\r
+// throw ae;\r
+// }\r
+// }\r
+//\r
+// public Short newInstance() throws APIException {\r
+// return 0;\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * ByteStringifier\r
+// * \r
+// * Support the Native Byte.. use Byte parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class ByteStringifier extends NullLifeCycle implements Stringifier<Byte> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)\r
+// */\r
+// public String stringify(Env env, Byte input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * ByteObjectifier\r
+// * \r
+// * Support the Native Byte.. use Byte parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class ByteObjectifier extends NullLifeCycle implements Objectifier<Byte> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public Byte objectify(Env env, String input) throws APIException {\r
+// try {\r
+// return new Byte(input);\r
+// } catch (Exception e) {\r
+// APIException ae = new APIException("Cannot create a \"Byte\" from [" + input + ']');\r
+// ae.initCause(e);\r
+// throw ae;\r
+// }\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public Byte newInstance() throws APIException {\r
+// return 0;\r
+// }\r
+// }\r
+//\r
+// /**\r
+// * CharacterStringifier\r
+// * \r
+// * Support the Native Character.. use Character parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class CharacterStringifier extends NullLifeCycle implements Stringifier<Character> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)\r
+// */\r
+// public String stringify(Env env, Character input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * CharacterObjectifier\r
+// * \r
+// * Support the Native Character.. use Character parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class CharacterObjectifier extends NullLifeCycle implements Objectifier<Character> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public Character objectify(Env env, String input) throws APIException {\r
+// int length = input.length();\r
+// if(length<1 || length>1) {\r
+// throw new APIException("String [" + input + "] does not represent a single Character");\r
+// }\r
+// return input.charAt(0);\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public Character newInstance() throws APIException {\r
+// return 0;\r
+// }\r
+// }\r
+//\r
+// /**\r
+// * FloatStringifier\r
+// * \r
+// * Support the Native Float.. use Float parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class FloatStringifier extends NullLifeCycle implements Stringifier<Float> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)\r
+// */\r
+// public String stringify(Env env, Float input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * FloatObjectifier\r
+// * \r
+// * Support the Native Float.. use Float parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class FloatObjectifier extends NullLifeCycle implements Objectifier<Float> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public Float objectify(Env env, String input) throws APIException {\r
+// try {\r
+// return new Float(input);\r
+// } catch (Exception e) {\r
+// APIException ae = new APIException("Cannot create a \"Float\" from [" + input + ']');\r
+// ae.initCause(e);\r
+// throw ae;\r
+// }\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public Float newInstance() throws APIException {\r
+// return 0.0f;\r
+// }\r
+// }\r
+//\r
+// /**\r
+// * DoubleStringifier\r
+// * \r
+// * Support the Native Double.. use Double parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class DoubleStringifier extends NullLifeCycle implements Stringifier<Double> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Stringifier#stringify(com.att.env.Env, java.lang.Object)\r
+// */\r
+// public String stringify(Env env, Double input) throws APIException {\r
+// return input.toString();\r
+// }\r
+// }\r
+// \r
+// /**\r
+// * DoubleObjectifier\r
+// * \r
+// * Support the Native Double.. use Double parse functions\r
+// * \r
+// * @author Jonathan\r
+// *\r
+// */\r
+// public static class DoubleObjectifier extends NullLifeCycle implements Objectifier<Double> {\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#objectify(com.att.env.Env, java.lang.String)\r
+// */\r
+// public Double objectify(Env env, String input) throws APIException {\r
+// try {\r
+// return new Double(input);\r
+// } catch (Exception e) {\r
+// APIException ae = new APIException("Cannot create a \"Double\" from [" + input + ']');\r
+// ae.initCause(e);\r
+// throw ae;\r
+// }\r
+// }\r
+//\r
+// /* (non-Javadoc)\r
+// * @see com.att.env.Objectifier#newObject()\r
+// */\r
+// public Double newInstance() throws APIException {\r
+// return 0.0;\r
+// }\r
+// }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-/**
- * <h1>Creatable</h1>
- * <b>**Must implement constructor T(ENV env, long currentTimeMillis);**</b><p>
- *
- * This interface exists to cover basic LifeCycle semantics so that Objects
- * can be created dynamically and managed at a basic level (destroy(env)).
- *
- * @author Jonathan
- *
- * @param <T>
- */
-public interface Creatable<T> {
- /**
- * Return the timestamp (Unix long) when this object was created.<p>
- * This can be used to see if the object is out of date in certain
- * circumstances, or perhaps has already been notified in others.
- *
- * @return long
- */
- public abstract long created();
-
- /**
- * Allow LifeCycle aware process to signal this element as destroyed.
- *
- * @param env
- */
- public abstract void destroy(Env env);
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+/**\r
+ * <h1>Creatable</h1>\r
+ * <b>**Must implement constructor T(ENV env, long currentTimeMillis);**</b><p>\r
+ *\r
+ * This interface exists to cover basic LifeCycle semantics so that Objects\r
+ * can be created dynamically and managed at a basic level (destroy(env)).\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ * @param <T>\r
+ */\r
+public interface Creatable<T> {\r
+ /**\r
+ * Return the timestamp (Unix long) when this object was created.<p>\r
+ * This can be used to see if the object is out of date in certain\r
+ * circumstances, or perhaps has already been notified in others.\r
+ * \r
+ * @return long\r
+ */\r
+ public abstract long created();\r
+ \r
+ /**\r
+ * Allow LifeCycle aware process to signal this element as destroyed.\r
+ * \r
+ * @param env\r
+ */\r
+ public abstract void destroy(Env env);\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-/**
- * <H1>Data</H1>
- * <i>Data</i> facilitates lazy marshaling of data with a pre-determined
- * marshaling mechanism.<p>
- *
- * It stores either Object (defined by Generic {@literal <T>}) or String.<p>
- *
- * On asking for Object of type {@literal <T>}, it will respond with the object
- * if it exists, or unmarshal the string and pass the result back.<p>
- *
- * On asking for String, it will respond with the String
- * if it exists, or marshal the String and pass the result back.<p>
- *
- * the "options" available on several functions control the output of this particular call. When
- * blank, they will default to the DataFactory defaults. When present, they override this
- * particular call.
- * The available options are "pretty" (for XML and JSON) and "fragment" (XML only concept), which drops
- * the "<?xml ...?>" header so you can create larger XML documents from the output.
- *
- * @author Jonathan
- *
- * @param <T>
- */
-public interface Data<T> {
- static enum TYPE {XML,JSON,JAXB,RAW,DEFAULT};
- // can & with 0xFFFF;
-// public static final int XML = 0x1;
-// public static final int JSON = 0x2;
-// public static final int JAXB = 0x4;
-// public static final int RAW = 0x1000;
-
- // can & with 0xF00000;
- public static final int PRETTY = 0x100000;
- public static final int FRAGMENT = 0x200000;
-
- /**
- * Respond with the String if it exists, or marshal the String and pass the result back.
- *
- * However, use the Env the Data Object was created with.
- *
- * @return String
- * @throws APIException
- */
- public String asString() throws APIException;
-
- /**
- * Respond with the Object of type {@literal <T>} if it exists, or unmarshal from String
- * and pass the result back.<p>
- *
- * However, use the Env the Data Object was created with.
- *
- * @return T
- * @throws APIException
- */
- public T asObject() throws APIException;
-
- /**
- * Set a particular option on an existing Out
- *
- * if int is negative, it should remove the option
- * @param option
- */
- public Data<T> option(int option);
-
- public Data<T> to(OutputStream os) throws APIException, IOException;
- public Data<T> to(Writer writer) throws APIException, IOException;
-
- public Data<T> load(T t) throws APIException;
- public Data<T> load(String str) throws APIException;
- public Data<T> load(InputStream is) throws APIException;
- public Data<T> load(Reader rdr) throws APIException;
-
- public Data<T> in(TYPE type);
- public Data<T> out(TYPE type);
- /**
- * Return the Class Type supported by this DataObject
- *
- * @return {@literal Class<T>}
- */
- public Class<T> getTypeClass();
-
- public void direct(InputStream input, OutputStream output) throws APIException, IOException;
-
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.io.Reader;\r
+import java.io.Writer;\r
+/**\r
+ * <H1>Data</H1>\r
+ * <i>Data</i> facilitates lazy marshaling of data with a pre-determined\r
+ * marshaling mechanism.<p>\r
+ * \r
+ * It stores either Object (defined by Generic {@literal <T>}) or String.<p> \r
+ * \r
+ * On asking for Object of type {@literal <T>}, it will respond with the object\r
+ * if it exists, or unmarshal the string and pass the result back.<p>\r
+ * \r
+ * On asking for String, it will respond with the String\r
+ * if it exists, or marshal the String and pass the result back.<p>\r
+ *\r
+ * the "options" available on several functions control the output of this particular call. When \r
+ * blank, they will default to the DataFactory defaults. When present, they override this\r
+ * particular call.\r
+ * The available options are "pretty" (for XML and JSON) and "fragment" (XML only concept), which drops\r
+ * the "<?xml ...?>" header so you can create larger XML documents from the output. \r
+ * \r
+ * @author Jonathan\r
+ *\r
+ * @param <T>\r
+ */\r
+public interface Data<T> {\r
+ static enum TYPE {XML,JSON,JAXB,RAW,DEFAULT};\r
+ // can & with 0xFFFF;\r
+// public static final int XML = 0x1;\r
+// public static final int JSON = 0x2;\r
+// public static final int JAXB = 0x4;\r
+// public static final int RAW = 0x1000;\r
+ \r
+ // can & with 0xF00000;\r
+ public static final int PRETTY = 0x100000;\r
+ public static final int FRAGMENT = 0x200000;\r
+\r
+ /**\r
+ * Respond with the String if it exists, or marshal the String and pass the result back.\r
+ * \r
+ * However, use the Env the Data Object was created with.\r
+ * \r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public String asString() throws APIException;\r
+\r
+ /**\r
+ * Respond with the Object of type {@literal <T>} if it exists, or unmarshal from String \r
+ * and pass the result back.<p>\r
+ *\r
+ * However, use the Env the Data Object was created with.\r
+ * \r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public T asObject() throws APIException;\r
+\r
+ /**\r
+ * Set a particular option on an existing Out \r
+ * \r
+ * if int is negative, it should remove the option\r
+ * @param option\r
+ */\r
+ public Data<T> option(int option);\r
+\r
+ public Data<T> to(OutputStream os) throws APIException, IOException;\r
+ public Data<T> to(Writer writer) throws APIException, IOException;\r
+ \r
+ public Data<T> load(T t) throws APIException;\r
+ public Data<T> load(String str) throws APIException;\r
+ public Data<T> load(InputStream is) throws APIException;\r
+ public Data<T> load(Reader rdr) throws APIException;\r
+ \r
+ public Data<T> in(TYPE type);\r
+ public Data<T> out(TYPE type);\r
+ /**\r
+ * Return the Class Type supported by this DataObject\r
+ * \r
+ * @return {@literal Class<T>}\r
+ */\r
+ public Class<T> getTypeClass();\r
+\r
+ public void direct(InputStream input, OutputStream output) throws APIException, IOException;\r
+\r
+\r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-public interface DataFactory<T> {
- public abstract Data<T> newData();
- public abstract Data<T> newData(Env trans); // and Env or Trans object
- public abstract Class<T> getTypeClass();
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+public interface DataFactory<T> {\r
+ public abstract Data<T> newData();\r
+ public abstract Data<T> newData(Env trans); // and Env or Trans object\r
+ public abstract Class<T> getTypeClass();\r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-public interface Decryptor {
- public String decrypt(String tag);
-
- public static final Decryptor NULL = new Decryptor() {
- @Override
- public String decrypt(String tag) {
- return tag;
- }
- };
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+public interface Decryptor {\r
+ public String decrypt(String tag);\r
+ \r
+ public static final Decryptor NULL = new Decryptor() {\r
+ @Override\r
+ public String decrypt(String tag) {\r
+ return tag;\r
+ }\r
+ };\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-public interface Encryptor {
- public String encrypt(String data);
-
- public static final Encryptor NULL = new Encryptor() {
- @Override
- public String encrypt(String data) {
- return data;
- }
- };
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+public interface Encryptor {\r
+ public String encrypt(String data);\r
+\r
+ public static final Encryptor NULL = new Encryptor() {\r
+ @Override\r
+ public String encrypt(String data) {\r
+ return data;\r
+ }\r
+ };\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-/**
- * <H1>Env</H1>
- * <i>Env</i> is the basic representation of what can be obtained from the
- * Environment. Environments also need the ability to Log and Track Time, so
- * to keep the interfaces clean, Env Interface inherits from Trans. This does NOT
- * mean that all Environments are Transactions... It only means Environments need
- * to Log and Track Times.
- * .<p>
- *
- * Using this abstraction, Components can be built on a modular basis,
- * and still have the essentials of functioning within the service mechanism.<p>
- *
- * Thus, for instance, an Module could be made to work in two separate
- * service types, with substantial differences in choices of logging, or auditing,
- * and still have reasonably deep insight, such as the exact time a
- * remote service was invoked.<p>
- *
- * There is a bit of an assumption corresponding to the reality of the 2000s that
- * XML plays a part in most service work.
- *
- * @author Jonathan
- *
- */
-public interface Env {
- /**
- * Very Severe Error may cause program to abort
- */
- public LogTarget fatal();
-
- /**
- * Severe Error, but program might continue running
- */
- public LogTarget error();
-
- /**
- * Required Audit statements
- * @return
- */
- public LogTarget audit();
-
- /**
- * Initialization steps... Allows a Logger to separate startup info
- * @return
- */
- public LogTarget init();
-
- /**
- * Potentially harmful situations
- * @return
- */
- public LogTarget warn();
-
- /**
- * Course Grained highlights of program progress
- * @return
- */
- public LogTarget info();
-
- /**
- * Fine-grained informational events useful for debugging
- * @return
- */
- public LogTarget debug();
-
- /**
- * Finest grained Informational events... more detailed than Debug
- * @return
- */
- public LogTarget trace();
-
-
- /**
- * Basic and Common Audit info...
- *
- * Note Apps can define, but should use Integers after 0x1F. They can combine with "&"
- */
- public static final int REMOTE = 0x01;
- public static final int XML = 0x02;
- public static final int JSON = 0x04;
- public static final int SUB = 0x08;
- public static final int CHECKPOINT = 0x10;
- public static final int ALWAYS = 0x20; // Mark as a line to print, even in WARN+ mode
-
-
-
- /**
- * Start a Time Trail with differentiation by flag. This can be Defined By above flags or combined with
- * app flag definitions
- *
- * @param string
- * @param flag
- * @return
- */
- public TimeTaken start(String name, int flag);
-
- public String setProperty(String tag, String value);
- public String getProperty(String tag);
- public String getProperty(String tag, String deflt);
-
- /**
- * Passwords should be encrypted on the disk. Use this method to apply decryption before
- * using. The Implementation should give ways to decrypt
- *
- * @param tag
- * @return
- */
- public Decryptor decryptor();
-
- public Encryptor encryptor();
-
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+/**\r
+ * <H1>Env</H1>\r
+ * <i>Env</i> is the basic representation of what can be obtained from the\r
+ * Environment. Environments also need the ability to Log and Track Time, so\r
+ * to keep the interfaces clean, Env Interface inherits from Trans. This does NOT\r
+ * mean that all Environments are Transactions... It only means Environments need \r
+ * to Log and Track Times. \r
+ * .<p>\r
+ * \r
+ * Using this abstraction, Components can be built on a modular basis,\r
+ * and still have the essentials of functioning within the service mechanism.<p>\r
+ * \r
+ * Thus, for instance, an Module could be made to work in two separate\r
+ * service types, with substantial differences in choices of logging, or auditing,\r
+ * and still have reasonably deep insight, such as the exact time a\r
+ * remote service was invoked.<p>\r
+ * \r
+ * There is a bit of an assumption corresponding to the reality of the 2000s that\r
+ * XML plays a part in most service work.\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public interface Env {\r
+ /**\r
+ * Very Severe Error may cause program to abort\r
+ */\r
+ public LogTarget fatal();\r
+ \r
+ /**\r
+ * Severe Error, but program might continue running\r
+ */\r
+ public LogTarget error();\r
+\r
+ /**\r
+ * Required Audit statements\r
+ * @return\r
+ */\r
+ public LogTarget audit();\r
+\r
+ /**\r
+ * Initialization steps... Allows a Logger to separate startup info\r
+ * @return\r
+ */\r
+ public LogTarget init();\r
+\r
+ /**\r
+ * Potentially harmful situations\r
+ * @return\r
+ */\r
+ public LogTarget warn();\r
+ \r
+ /**\r
+ * Course Grained highlights of program progress\r
+ * @return\r
+ */\r
+ public LogTarget info();\r
+ \r
+ /**\r
+ * Fine-grained informational events useful for debugging\r
+ * @return\r
+ */\r
+ public LogTarget debug();\r
+ \r
+ /**\r
+ * Finest grained Informational events... more detailed than Debug\r
+ * @return\r
+ */\r
+ public LogTarget trace();\r
+\r
+\r
+ /**\r
+ * Basic and Common Audit info... \r
+ * \r
+ * Note Apps can define, but should use Integers after 0x1F. They can combine with "&"\r
+ */\r
+ public static final int REMOTE = 0x01;\r
+ public static final int XML = 0x02;\r
+ public static final int JSON = 0x04;\r
+ public static final int SUB = 0x08;\r
+ public static final int CHECKPOINT = 0x10;\r
+ public static final int ALWAYS = 0x20; // Mark as a line to print, even in WARN+ mode\r
+\r
+\r
+ \r
+ /**\r
+ * Start a Time Trail with differentiation by flag. This can be Defined By above flags or combined with\r
+ * app flag definitions\r
+ * \r
+ * @param string\r
+ * @param flag\r
+ * @return\r
+ */\r
+ public TimeTaken start(String name, int flag);\r
+ \r
+ public String setProperty(String tag, String value);\r
+ public String getProperty(String tag);\r
+ public String getProperty(String tag, String deflt);\r
+ \r
+ /**\r
+ * Passwords should be encrypted on the disk. Use this method to apply decryption before\r
+ * using. The Implementation should give ways to decrypt\r
+ * \r
+ * @param tag\r
+ * @return\r
+ */\r
+ public Decryptor decryptor();\r
+ \r
+ public Encryptor encryptor();\r
+\r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import javax.xml.namespace.QName;
-import javax.xml.validation.Schema;
-
-public interface EnvJAXB extends EnvStore<TransJAXB> {
- /**
- * Obtain a DataInterface from this Environment
- *
- * @param <T>
- * @param classes
- * @return
- * @throws APIException
- */
- public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException;
-
- /**
- * Obtain a DataInterface from this Environment, with Validating Schema
- *
- * @param <T>
- * @param classes
- * @return
- * @throws APIException
- */
- public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException;
-
- public<T> DataFactory<T> newDataFactory(QName qName, Class<?> ... classes) throws APIException;
-
- public<T> DataFactory<T> newDataFactory(Schema schema, QName qName, Class<?> ... classes) throws APIException;
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import javax.xml.namespace.QName;\r
+import javax.xml.validation.Schema;\r
+\r
+public interface EnvJAXB extends EnvStore<TransJAXB> {\r
+ /**\r
+ * Obtain a DataInterface from this Environment\r
+ * \r
+ * @param <T>\r
+ * @param classes\r
+ * @return\r
+ * @throws APIException\r
+ */\r
+ public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException;\r
+\r
+ /**\r
+ * Obtain a DataInterface from this Environment, with Validating Schema\r
+ * \r
+ * @param <T>\r
+ * @param classes\r
+ * @return\r
+ * @throws APIException\r
+ */\r
+ public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException;\r
+\r
+ public<T> DataFactory<T> newDataFactory(QName qName, Class<?> ... classes) throws APIException;\r
+\r
+ public<T> DataFactory<T> newDataFactory(Schema schema, QName qName, Class<?> ... classes) throws APIException;\r
+ \r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-/**
- * An interface to express both JAXB and Property elements of Env
- * @author Jonathan
- *
- */
-public interface EnvJAXBProps extends EnvJAXB, EnvProps {
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+/**\r
+ * An interface to express both JAXB and Property elements of Env\r
+ * @author Jonathan\r
+ *\r
+ */\r
+public interface EnvJAXBProps extends EnvJAXB, EnvProps {\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.util.Map;
-
-public interface EnvProps extends Env {
- public interface EnvProperty {
- public String getProperty(String input);
- };
-
- /**
- * Obtain a Property (String) based on a Key. Implementor decides how
- * that works, i.e. from a complex set of Configurations, or just
- * "System" (Java standard)
- *
- * @param key
- * @return APIException
- */
- public String getProperty(String key);
-
- /**
- * Obtain a Property (String) based on a Key. Implementor decides how
- * that works, i.e. from a complex set of Configurations, or just
- * "System" (Java standard)
- *
- * If Property Value is null, then default will be used.
- * @param key
- * @return APIException
- */
- public String getProperty(String tag, String defaultValue);
-
- /**
- * Set a Property (String) based on a Key accessible to all in Env. Implementor decides how
- * that works, i.e. from a complex set of Configurations, or just
- * "System" (Java standard)
- *
- * @param key
- * @return APIException
- */
- public String setProperty(String key, String value);
-
- /**
- * Get the SubProperties based on key.
- *
- * use "false" to remove prefix, "true" to leave prefix in.
- *
- * @param key
- * @return APIException
- * Given a known property set (or in this case, properties starting with key),
- * return map of all properties with appropriate key names
- */
- public Map<String, String> getSubProperties(String key, boolean includePrefix);
-
- /**
- * Get all of the properties in the Environment
- * @return
- */
- public Map<String, String> getProperties();
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.util.Map;\r
+\r
+public interface EnvProps extends Env {\r
+ public interface EnvProperty {\r
+ public String getProperty(String input);\r
+ };\r
+\r
+ /**\r
+ * Obtain a Property (String) based on a Key. Implementor decides how\r
+ * that works, i.e. from a complex set of Configurations, or just \r
+ * "System" (Java standard)\r
+ * \r
+ * @param key\r
+ * @return APIException\r
+ */\r
+ public String getProperty(String key);\r
+\r
+ /**\r
+ * Obtain a Property (String) based on a Key. Implementor decides how\r
+ * that works, i.e. from a complex set of Configurations, or just \r
+ * "System" (Java standard)\r
+ * \r
+ * If Property Value is null, then default will be used.\r
+ * @param key\r
+ * @return APIException\r
+ */\r
+ public String getProperty(String tag, String defaultValue);\r
+\r
+ /**\r
+ * Set a Property (String) based on a Key accessible to all in Env. Implementor decides how\r
+ * that works, i.e. from a complex set of Configurations, or just \r
+ * "System" (Java standard)\r
+ * \r
+ * @param key\r
+ * @return APIException\r
+ */\r
+ public String setProperty(String key, String value);\r
+ \r
+ /**\r
+ * Get the SubProperties based on key.\r
+ * \r
+ * use "false" to remove prefix, "true" to leave prefix in.\r
+ * \r
+ * @param key\r
+ * @return APIException\r
+ * Given a known property set (or in this case, properties starting with key), \r
+ * return map of all properties with appropriate key names\r
+ */\r
+ public Map<String, String> getSubProperties(String key, boolean includePrefix);\r
+\r
+ /**\r
+ * Get all of the properties in the Environment\r
+ * @return\r
+ */\r
+ public Map<String, String> getProperties();\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-public interface EnvStore<TRANS extends Trans> extends Env, Store, TransCreate<TRANS>{
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+public interface EnvStore<TRANS extends Trans> extends Env, Store, TransCreate<TRANS>{\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.io.InputStream;
-import java.io.Reader;
-
-public interface IOObjectifier<T> extends Objectifier<T> {
- /**
- * Marshal to Object T from a Reader, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return T
- * @throws APIException
- */
- public abstract T objectify(Env env, Reader rdr) throws APIException;
-
- /**
- * Marshal to Object T from an InputStream, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return T
- * @throws APIException
- */
- public abstract T objectify(Env env, InputStream is) throws APIException;
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.io.InputStream;\r
+import java.io.Reader;\r
+\r
+public interface IOObjectifier<T> extends Objectifier<T> {\r
+ /**\r
+ * Marshal to Object T from a Reader, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T objectify(Env env, Reader rdr) throws APIException;\r
+ \r
+ /**\r
+ * Marshal to Object T from an InputStream, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T objectify(Env env, InputStream is) throws APIException;\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.io.OutputStream;
-import java.io.Writer;
-
-/**
- * Allow Extended IO interface usage without muddying up the Stringifier Interface
- */
-public interface IOStringifier<T> extends Stringifier<T> {
- /**
- * Marshal from an Object T onto a Writer, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startTime(<string>, Env.XML)" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return String
- * @throws APIException
- */
- public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException;
-
- /**
- * Marshal from a String to an Object T, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return String
- * @throws APIException
- */
- public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException;
-
- /**
- * Set Pretty XML, where possible
- *
- * @param pretty
- * @throws APIException
- */
- public abstract IOStringifier<T> pretty(boolean pretty);
-
- /**
- * Set Generate Fragment
- *
- * @param fragment
- * @throws APIException
- */
- public abstract IOStringifier<T> asFragment(boolean fragment);
-
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.io.OutputStream;\r
+import java.io.Writer;\r
+\r
+/**\r
+ * Allow Extended IO interface usage without muddying up the Stringifier Interface\r
+ */\r
+public interface IOStringifier<T> extends Stringifier<T> {\r
+ /**\r
+ * Marshal from an Object T onto a Writer, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startTime(<string>, Env.XML)" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException;\r
+ \r
+ /**\r
+ * Marshal from a String to an Object T, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException;\r
+\r
+ /**\r
+ * Set Pretty XML, where possible\r
+ * \r
+ * @param pretty\r
+ * @throws APIException\r
+ */\r
+ public abstract IOStringifier<T> pretty(boolean pretty);\r
+\r
+ /**\r
+ * Set Generate Fragment\r
+ * \r
+ * @param fragment\r
+ * @throws APIException\r
+ */\r
+ public abstract IOStringifier<T> asFragment(boolean fragment);\r
+\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- *
- * Created on: Aug 19, 2009
- * Created by: Jonathan
- *
- * (c) 2009 SBC Knowledge Ventures, L.P. All rights reserved.
- *******************************************************************
- * RESTRICTED - PROPRIETARY INFORMATION The Information contained
- * herein is for use only by authorized employees of AT&T Services,
- * Inc., and authorized Affiliates of AT&T Services, Inc., and is
- * not for general distribution within or outside the respective
- * companies.
- *******************************************************************
- */
-package org.onap.aaf.misc.env;
-
-import org.onap.aaf.misc.env.util.RefreshableThreadObject;
-
-
-/**
- * @author Jonathan
- *
- */
-public interface LifeCycle {
- /**
- * The Service using LifeCycle Elements is required to call this method at
- * the appropriate startup time. This is better for services than a simple
- * static call, because the exact moment of starting can be determined
- * programatically.
- * <p>
- *
- * An excellent use is to establish security credentials with a backend
- * after appropriate configurations have been read and available as part of
- * the {@link Env} Object.
- *
- * @param env
- * @throws APIException
- */
- public abstract void servicePrestart(Env env) throws APIException;
-
- /**
- * Many cases of implementations are not thread safe, and mechanisms must be
- * derived to accomodate them by holding per Thread.
- * <p>
- *
- * {@link ThreadLocal} is a valuable resource, but start up times within the
- * thread, depending on what it is, can be substantial.
- * <p>
- *
- * Use ThreadPrestart to do all that is possible before actually performing
- * work, i.e. inside of a client transaction.
- *
- * @param env
- * @throws APIException
- */
- public abstract void threadPrestart(Env env) throws APIException;
-
- /**
- * The Service will call this when (service-defined) configurations change.
- * <p>
- *
- * This mechanism allows the Service to recognize events, such as file
- * changes, and pass on the event to all LifeCycle implementors.
- * <p>
- *
- * The code should take the opportunity to evaluate configuration and change
- * as necessary.
- * <p>
- *
- * <h2>IMPORTANT:</h2>
- * The LifeCycle implementor cannot guarantee it will not be in the middle
- * of a transaction, so it would behoove the implementor to construct
- * content that does not affect anything until finished, then apply to an
- * appropriate atomic action (i.e. setting an Object to a field), or even
- * synchronizing.
- *
- * If you are using Java's "ThreadLocal", consider
- * {@link RefreshableThreadObject}, because it implements LifeCycle, and
- * responds to the refresh command.
- *
- * @param env
- * @throws APIException
- */
- public abstract void refresh(Env env) throws APIException;
-
- /**
- * Parallel to threadPrestart, threadDestroy tells the implementor that the
- * service is ending this particular thread, and to take this opportunity to
- * close out any content specific to this thread that can be closed.
- *
- * @param env
- * @throws APIException
- */
- public abstract void threadDestroy(Env env) throws APIException;
-
- /**
- * Parallel to servicePrestart, serviceDestroy tells the implementor that
- * the service is ending, and to take this opportunity to close out any
- * content under it's control that can or should be closed explicitly.
- */
- public abstract void serviceDestroy(Env env) throws APIException;
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ *\r
+ * Created on: Aug 19, 2009\r
+ * Created by: Jonathan\r
+ *\r
+ * (c) 2009 SBC Knowledge Ventures, L.P. All rights reserved.\r
+ ******************************************************************* \r
+ * RESTRICTED - PROPRIETARY INFORMATION The Information contained \r
+ * herein is for use only by authorized employees of AT&T Services, \r
+ * Inc., and authorized Affiliates of AT&T Services, Inc., and is \r
+ * not for general distribution within or outside the respective \r
+ * companies. \r
+ *******************************************************************\r
+ */\r
+package org.onap.aaf.misc.env;\r
+\r
+import org.onap.aaf.misc.env.util.RefreshableThreadObject;\r
+\r
+\r
+/**\r
+ * @author Jonathan\r
+ * \r
+ */\r
+public interface LifeCycle {\r
+ /**\r
+ * The Service using LifeCycle Elements is required to call this method at\r
+ * the appropriate startup time. This is better for services than a simple\r
+ * static call, because the exact moment of starting can be determined\r
+ * programatically.\r
+ * <p>\r
+ * \r
+ * An excellent use is to establish security credentials with a backend\r
+ * after appropriate configurations have been read and available as part of\r
+ * the {@link Env} Object.\r
+ * \r
+ * @param env\r
+ * @throws APIException\r
+ */\r
+ public abstract void servicePrestart(Env env) throws APIException;\r
+\r
+ /**\r
+ * Many cases of implementations are not thread safe, and mechanisms must be\r
+ * derived to accomodate them by holding per Thread.\r
+ * <p>\r
+ * \r
+ * {@link ThreadLocal} is a valuable resource, but start up times within the\r
+ * thread, depending on what it is, can be substantial.\r
+ * <p>\r
+ * \r
+ * Use ThreadPrestart to do all that is possible before actually performing\r
+ * work, i.e. inside of a client transaction.\r
+ * \r
+ * @param env\r
+ * @throws APIException\r
+ */\r
+ public abstract void threadPrestart(Env env) throws APIException;\r
+\r
+ /**\r
+ * The Service will call this when (service-defined) configurations change.\r
+ * <p>\r
+ * \r
+ * This mechanism allows the Service to recognize events, such as file\r
+ * changes, and pass on the event to all LifeCycle implementors.\r
+ * <p>\r
+ * \r
+ * The code should take the opportunity to evaluate configuration and change\r
+ * as necessary.\r
+ * <p>\r
+ * \r
+ * <h2>IMPORTANT:</h2>\r
+ * The LifeCycle implementor cannot guarantee it will not be in the middle\r
+ * of a transaction, so it would behoove the implementor to construct\r
+ * content that does not affect anything until finished, then apply to an\r
+ * appropriate atomic action (i.e. setting an Object to a field), or even\r
+ * synchronizing.\r
+ * \r
+ * If you are using Java's "ThreadLocal", consider\r
+ * {@link RefreshableThreadObject}, because it implements LifeCycle, and\r
+ * responds to the refresh command.\r
+ * \r
+ * @param env\r
+ * @throws APIException\r
+ */\r
+ public abstract void refresh(Env env) throws APIException;\r
+\r
+ /**\r
+ * Parallel to threadPrestart, threadDestroy tells the implementor that the\r
+ * service is ending this particular thread, and to take this opportunity to\r
+ * close out any content specific to this thread that can be closed.\r
+ * \r
+ * @param env\r
+ * @throws APIException\r
+ */\r
+ public abstract void threadDestroy(Env env) throws APIException;\r
+\r
+ /**\r
+ * Parallel to servicePrestart, serviceDestroy tells the implementor that\r
+ * the service is ending, and to take this opportunity to close out any\r
+ * content under it's control that can or should be closed explicitly.\r
+ */\r
+ public abstract void serviceDestroy(Env env) throws APIException;\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.io.PrintStream;
-import java.util.Date;
-
-import org.onap.aaf.misc.env.util.Chrono;
-
-/**
- * LogTarget is the interface with which to assign any kind of Logging Implementations.
- *
- * Implement for any Logging Library of your choice, and for any logging string Format desired.
- *
- * Included are several Static Implementations for various uses:
- * NULL: Does nothing with Logging Messages
- * SYSOUT: Writes messages in general form to System Out
- * SYSERR: Writes messages in general form to System Err
- *
- * @author Jonathan
- *
- */
-public interface LogTarget {
- public abstract void log(Object... msgs);
- public abstract void log(Throwable e, Object ... msgs);
- public abstract boolean isLoggable();
- public abstract void printf(String fmt, Object ... vars);
-
- // A Convenient LogTarget to insert when a NO-OP is desired.
- public static final LogTarget NULL = new LogTarget() {
- public void log(Object ... msgs) {
- }
-
- public void log(Throwable t, Object ... msgs) {
- }
-
- public boolean isLoggable() {
- return false;
- }
-
- @Override
- public void printf(String fmt, Object ... vars) {
- }
- };
-
- // A Convenient LogTarget to write to the Console
- public static final LogTarget SYSOUT = new LogTarget() {
- public void log(Object ... msgs) {
- PrintStream out = System.out;
- out.print(org.onap.aaf.misc.env.util.Chrono.dateFmt.format(new Date()));
- out.print(": ");
- for(Object str : msgs) {
- if(str!=null) {
- out.print(str.toString());
- out.print(' ');
- } else {
- out.print("null ");
- }
- }
- out.println();
- }
-
- public void log(Throwable t, Object ... msgs) {
- PrintStream out = System.out;
- out.print(Chrono.dateFmt.format(new Date()));
- out.print(": ");
- for(Object str : msgs) {
- out.print(str.toString());
- out.print(' ');
- }
- out.println();
- t.printStackTrace(out);
- out.println();
- }
-
- public boolean isLoggable() {
- return true;
- }
-
- @Override
- public void printf(String fmt, Object ... vars) {
- log(String.format(fmt,vars));
- }
- };
-
- // A Convenient LogTarget to write to the Console
- public static final LogTarget SYSERR = new LogTarget() {
- public void log(Object ... msgs) {
- PrintStream out = System.err;
- out.print(Chrono.dateFmt.format(new Date()));
- out.print(": ");
- for(Object str : msgs) {
- out.print(str.toString());
- out.print(' ');
- }
- out.println();
- out.flush();
- }
-
- public void log(Throwable t, Object ... msgs) {
- PrintStream out = System.err;
- out.print(Chrono.dateFmt.format(new Date()));
- out.print(": ");
- for(Object str : msgs) {
- out.print(str.toString());
- out.print(' ');
- }
- out.println();
- t.printStackTrace(out);
- }
-
- public boolean isLoggable() {
- return true;
- }
- @Override
- public void printf(String fmt, Object ... vars) {
- log(String.format(fmt,vars));
- }
-
- };
-
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.io.PrintStream;\r
+import java.util.Date;\r
+\r
+import org.onap.aaf.misc.env.util.Chrono;\r
+\r
+/**\r
+ * LogTarget is the interface with which to assign any kind of Logging Implementations.\r
+ * \r
+ * Implement for any Logging Library of your choice, and for any logging string Format desired.\r
+ * \r
+ * Included are several Static Implementations for various uses:\r
+ * NULL: Does nothing with Logging Messages\r
+ * SYSOUT: Writes messages in general form to System Out\r
+ * SYSERR: Writes messages in general form to System Err\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public interface LogTarget {\r
+ public abstract void log(Object... msgs);\r
+ public abstract void log(Throwable e, Object ... msgs);\r
+ public abstract boolean isLoggable();\r
+ public abstract void printf(String fmt, Object ... vars);\r
+\r
+ // A Convenient LogTarget to insert when a NO-OP is desired.\r
+ public static final LogTarget NULL = new LogTarget() {\r
+ public void log(Object ... msgs) {\r
+ }\r
+\r
+ public void log(Throwable t, Object ... msgs) {\r
+ }\r
+\r
+ public boolean isLoggable() {\r
+ return false;\r
+ }\r
+\r
+ @Override\r
+ public void printf(String fmt, Object ... vars) {\r
+ }\r
+ };\r
+\r
+ // A Convenient LogTarget to write to the Console\r
+ public static final LogTarget SYSOUT = new LogTarget() {\r
+ public void log(Object ... msgs) {\r
+ PrintStream out = System.out;\r
+ out.print(org.onap.aaf.misc.env.util.Chrono.dateFmt.format(new Date()));\r
+ out.print(": ");\r
+ for(Object str : msgs) {\r
+ if(str!=null) {\r
+ out.print(str.toString());\r
+ out.print(' ');\r
+ } else {\r
+ out.print("null ");\r
+ }\r
+ }\r
+ out.println();\r
+ }\r
+\r
+ public void log(Throwable t, Object ... msgs) {\r
+ PrintStream out = System.out;\r
+ out.print(Chrono.dateFmt.format(new Date()));\r
+ out.print(": ");\r
+ for(Object str : msgs) {\r
+ out.print(str.toString());\r
+ out.print(' ');\r
+ }\r
+ out.println();\r
+ t.printStackTrace(out);\r
+ out.println();\r
+ }\r
+\r
+ public boolean isLoggable() {\r
+ return true;\r
+ }\r
+\r
+ @Override\r
+ public void printf(String fmt, Object ... vars) {\r
+ log(String.format(fmt,vars));\r
+ }\r
+ };\r
+ \r
+ // A Convenient LogTarget to write to the Console\r
+ public static final LogTarget SYSERR = new LogTarget() {\r
+ public void log(Object ... msgs) {\r
+ PrintStream out = System.err;\r
+ out.print(Chrono.dateFmt.format(new Date()));\r
+ out.print(": ");\r
+ for(Object str : msgs) {\r
+ out.print(str.toString());\r
+ out.print(' ');\r
+ }\r
+ out.println();\r
+ out.flush();\r
+ }\r
+\r
+ public void log(Throwable t, Object ... msgs) {\r
+ PrintStream out = System.err;\r
+ out.print(Chrono.dateFmt.format(new Date()));\r
+ out.print(": ");\r
+ for(Object str : msgs) {\r
+ out.print(str.toString());\r
+ out.print(' ');\r
+ }\r
+ out.println();\r
+ t.printStackTrace(out);\r
+ }\r
+\r
+ public boolean isLoggable() {\r
+ return true;\r
+ }\r
+ @Override\r
+ public void printf(String fmt, Object ... vars) {\r
+ log(String.format(fmt,vars));\r
+ }\r
+\r
+ };\r
+\r
+\r
};
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- *
- */
-package org.onap.aaf.misc.env;
-
-
-
-/**
- * <h1>Objectifier</h1>
- * <i>Objectifier</i> abstracts the unmarshaling of an Object from a String, and
- * the creation of an uninitialized object.
- */
-public interface Objectifier<T> extends LifeCycle {
- /**
- * Marshal to Object T from a String, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return T
- * @throws APIException
- */
- public abstract T objectify(Env env, String input) throws APIException;
-
- /**
- * Create a new object of type T. This is often more efficiently done with
- * the underlying XML (or other) Library.
- * @return T
- * @throws APIException
- */
- public abstract T newInstance() throws APIException;
-
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * \r
+ */\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+\r
+/**\r
+ * <h1>Objectifier</h1>\r
+ * <i>Objectifier</i> abstracts the unmarshaling of an Object from a String, and \r
+ * the creation of an uninitialized object. \r
+ */\r
+public interface Objectifier<T> extends LifeCycle {\r
+ /**\r
+ * Marshal to Object T from a String, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T objectify(Env env, String input) throws APIException;\r
+\r
+ /**\r
+ * Create a new object of type T. This is often more efficiently done with\r
+ * the underlying XML (or other) Library.\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T newInstance() throws APIException;\r
+\r
+ \r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- * Slot.java
- *
- * Created on: Dec 5, 2008
- * Created by: Jonathan
- *
- * (c) 2008 SBC Knowledge Ventures, L.P. All rights reserved.
- *******************************************************************
- * RESTRICTED - PROPRIETARY INFORMATION The Information contained
- * herein is for use only by authorized employees of AT&T Services,
- * Inc., and authorized Affiliates of AT&T Services, Inc., and is
- * not for general distribution within or outside the respective
- * companies.
- *******************************************************************
- */
-package org.onap.aaf.misc.env;
-
-/**
- * Slot's are used to store and retrieve data in the transaction's State object.
- */
-public final class Slot {
-
- /*
- * The name of the Slot.
- */
- private final String key;
-
- /*
- * The index of the State's local map associated with this Slot.
- */
- final int slot;
-
- /**
- * Constructs a new Slot.
- *
- * @param index
- * The index of State's local map this Slot is associated with.
- * @param name
- * The name of the Slot's key.
- */
- Slot(int index, String name) {
- slot = index;
- key = name;
- }
-
- /**
- * Debug method only to print key=slot pairs.
- */
- public String toString() {
- return key + '=' + slot;
- }
-
- /**
- * Returns the name of this Slot's key.
- *
- * @return
- * The name of this Slot's key.
- */
- public String getKey() {
- return key;
- }
-
- /**
- * Put an Object into the slot on the State
- * @param state
- * @param obj
- */
- public void put(Object[] state, Object obj) {
- state[slot]=obj;
- }
-
- /**
- * Get an Object from the slot on the State
- * @param state
- * @param obj
- */
- public Object get(Object[] state) {
- return state[slot];
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * Slot.java\r
+ *\r
+ * Created on: Dec 5, 2008\r
+ * Created by: Jonathan\r
+ *\r
+ * (c) 2008 SBC Knowledge Ventures, L.P. All rights reserved.\r
+ ******************************************************************* \r
+ * RESTRICTED - PROPRIETARY INFORMATION The Information contained \r
+ * herein is for use only by authorized employees of AT&T Services, \r
+ * Inc., and authorized Affiliates of AT&T Services, Inc., and is \r
+ * not for general distribution within or outside the respective \r
+ * companies. \r
+ *******************************************************************\r
+ */\r
+package org.onap.aaf.misc.env;\r
+\r
+/**\r
+ * Slot's are used to store and retrieve data in the transaction's State object.\r
+ */\r
+public final class Slot {\r
+ \r
+ /*\r
+ * The name of the Slot.\r
+ */\r
+ private final String key;\r
+ \r
+ /*\r
+ * The index of the State's local map associated with this Slot.\r
+ */\r
+ final int slot; \r
+ \r
+ /**\r
+ * Constructs a new Slot.\r
+ * \r
+ * @param index\r
+ * The index of State's local map this Slot is associated with.\r
+ * @param name\r
+ * The name of the Slot's key.\r
+ */\r
+ Slot(int index, String name) {\r
+ slot = index;\r
+ key = name;\r
+ }\r
+ \r
+ /**\r
+ * Debug method only to print key=slot pairs.\r
+ */\r
+ public String toString() {\r
+ return key + '=' + slot;\r
+ }\r
+ \r
+ /**\r
+ * Returns the name of this Slot's key.\r
+ * \r
+ * @return\r
+ * The name of this Slot's key.\r
+ */\r
+ public String getKey() {\r
+ return key;\r
+ }\r
+ \r
+ /**\r
+ * Put an Object into the slot on the State\r
+ * @param state\r
+ * @param obj\r
+ */\r
+ public void put(Object[] state, Object obj) {\r
+ state[slot]=obj;\r
+ }\r
+\r
+ /**\r
+ * Get an Object from the slot on the State\r
+ * @param state\r
+ * @param obj\r
+ */\r
+ public Object get(Object[] state) {\r
+ return state[slot];\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- * Slot.java
- *
- * Created on: Dec 5, 2008
- * Created by: Jonathan
- *
- * (c)2008 SBC Knowledge Ventures, L.P. All rights reserved.
- *******************************************************************
- * RESTRICTED - PROPRIETARY INFORMATION The Information contained
- * herein is for use only by authorized employees of AT&T Services,
- * Inc., and authorized Affiliates of AT&T Services, Inc., and is
- * not for general distribution within or outside the respective
- * companies.
- *******************************************************************
- */
-package org.onap.aaf.misc.env;
-
-/**
- * StaticSlot's are used to store and retrieve data from the Organizer that does not change.
- */
-public final class StaticSlot {
-
- /*
- * The name of the StaticSlot.
- */
- private final String key;
-
- /*
- * The index of the Organizer's static map associated with this StaticSlot.
- */
- final int slot;
-
- /**
- * Constructs a new StaticSlot.
- *
- * @param index
- * The index of Organizer's static map this StaticSlot is associated with.
- * @param name
- * The name of the StaticSlot's key.
- */
- StaticSlot(int index, String name) {
- slot = index;
- key = name;
- }
-
- /**
- * Debug method only to print key=slot pairs.
- */
- public String toString() {
- return key + '=' + slot;
- }
-
- /**
- * Returns the name of this StaticSlot's key.
- *
- * @return
- * The name of this StaticSlot's key.
- */
- public String getKey() {
- return key;
- }
-
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * Slot.java\r
+ *\r
+ * Created on: Dec 5, 2008\r
+ * Created by: Jonathan\r
+ *\r
+ * (c)2008 SBC Knowledge Ventures, L.P. All rights reserved.\r
+ ******************************************************************* \r
+ * RESTRICTED - PROPRIETARY INFORMATION The Information contained \r
+ * herein is for use only by authorized employees of AT&T Services, \r
+ * Inc., and authorized Affiliates of AT&T Services, Inc., and is \r
+ * not for general distribution within or outside the respective \r
+ * companies. \r
+ *******************************************************************\r
+ */\r
+package org.onap.aaf.misc.env;\r
+\r
+/**\r
+ * StaticSlot's are used to store and retrieve data from the Organizer that does not change.\r
+ */\r
+public final class StaticSlot {\r
+\r
+ /*\r
+ * The name of the StaticSlot.\r
+ */\r
+ private final String key;\r
+ \r
+ /*\r
+ * The index of the Organizer's static map associated with this StaticSlot.\r
+ */\r
+ final int slot; \r
+ \r
+ /**\r
+ * Constructs a new StaticSlot.\r
+ * \r
+ * @param index\r
+ * The index of Organizer's static map this StaticSlot is associated with.\r
+ * @param name\r
+ * The name of the StaticSlot's key.\r
+ */\r
+ StaticSlot(int index, String name) {\r
+ slot = index;\r
+ key = name;\r
+ }\r
+ \r
+ /**\r
+ * Debug method only to print key=slot pairs.\r
+ */\r
+ public String toString() {\r
+ return key + '=' + slot;\r
+ }\r
+ \r
+ /**\r
+ * Returns the name of this StaticSlot's key.\r
+ * \r
+ * @return\r
+ * The name of this StaticSlot's key.\r
+ */\r
+ public String getKey() {\r
+ return key;\r
+ }\r
+\r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.util.List;
-
-public interface Store {
- /**
- * Returns the Slot assigned to the supplied name.
- *
- * @param name
- * The name of the Slot to acquire.
- * @return
- * The Slot associated with the supplied name.
- */
- public abstract Slot slot(String name);
-
- /**
- * Returns the existing Slot associated with the supplied name, or null if it doesn't exist.
- *
- * @param name
- * The name of the Slot to get.
- * @return
- * The Slot assigned to the supplied name, or null if it doesn't exist.
- *
- */
- public abstract Slot existingSlot(String name);
-
- /**
- * Returns the names used while creating Slots in a List
- *
- * @return
- */
- public abstract List<String> existingSlotNames();
-
- /**
- * Returns the StaticSlot assigned to the supplied name.
- *
- * @param name
- * The name of the StaticSlot to acquire.
- * @return
- * The StaticSlot associated with the supplied name.
- */
- public abstract StaticSlot staticSlot(String name);
-
- /**
- * Returns the names used while creating Static Slots in a List
- *
- * @return
- */
- public abstract List<String> existingStaticSlotNames();
-
- /**
- * Store the supplied value in the StaticSlot of the Organizer's static state.
- *
- * @param slot
- * The StaticSlot used to store the object.
- * @param value
- * The object to store.
- */
- public abstract void put(StaticSlot slot, Object value);
-
- /**
- * Returns an Object from the Organizer's static state, or the Default if null
- *
- * @param slot
- * The StaticSlot to retrieve the data from.
- * @return
- * The Object located in the supplied StaticSlot of the Organizer's static state.
- */
- public abstract<T> T get(StaticSlot slot, T dflt);
-
- /**
- * Returns an Object from the Organizer's static state
- *
- * @param slot
- * The StaticSlot to retrieve the data from.
- * @return
- * The Object located in the supplied StaticSlot of the Organizer's static state.
- */
- public abstract<T> T get(StaticSlot slot);
-
-// /**
-// * Transfer (targeted) Args to Slots
-// *
-// * Transfer Strings with format "tag=value" into Static Slots
-// */
-// public abstract void transfer(String args[], String ... tagss);
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.util.List;\r
+\r
+public interface Store {\r
+ /**\r
+ * Returns the Slot assigned to the supplied name.\r
+ * \r
+ * @param name\r
+ * The name of the Slot to acquire.\r
+ * @return\r
+ * The Slot associated with the supplied name.\r
+ */\r
+ public abstract Slot slot(String name);\r
+\r
+ /**\r
+ * Returns the existing Slot associated with the supplied name, or null if it doesn't exist.\r
+ * \r
+ * @param name\r
+ * The name of the Slot to get.\r
+ * @return\r
+ * The Slot assigned to the supplied name, or null if it doesn't exist.\r
+ * \r
+ */\r
+ public abstract Slot existingSlot(String name);\r
+\r
+ /**\r
+ * Returns the names used while creating Slots in a List\r
+ * \r
+ * @return\r
+ */\r
+ public abstract List<String> existingSlotNames();\r
+\r
+ /**\r
+ * Returns the StaticSlot assigned to the supplied name.\r
+ * \r
+ * @param name\r
+ * The name of the StaticSlot to acquire.\r
+ * @return\r
+ * The StaticSlot associated with the supplied name.\r
+ */\r
+ public abstract StaticSlot staticSlot(String name);\r
+\r
+ /**\r
+ * Returns the names used while creating Static Slots in a List\r
+ * \r
+ * @return\r
+ */\r
+ public abstract List<String> existingStaticSlotNames();\r
+ \r
+ /**\r
+ * Store the supplied value in the StaticSlot of the Organizer's static state.\r
+ * \r
+ * @param slot\r
+ * The StaticSlot used to store the object.\r
+ * @param value\r
+ * The object to store.\r
+ */\r
+ public abstract void put(StaticSlot slot, Object value);\r
+\r
+ /**\r
+ * Returns an Object from the Organizer's static state, or the Default if null\r
+ * \r
+ * @param slot\r
+ * The StaticSlot to retrieve the data from.\r
+ * @return\r
+ * The Object located in the supplied StaticSlot of the Organizer's static state.\r
+ */\r
+ public abstract<T> T get(StaticSlot slot, T dflt);\r
+\r
+ /**\r
+ * Returns an Object from the Organizer's static state \r
+ * \r
+ * @param slot\r
+ * The StaticSlot to retrieve the data from.\r
+ * @return\r
+ * The Object located in the supplied StaticSlot of the Organizer's static state.\r
+ */\r
+ public abstract<T> T get(StaticSlot slot);\r
+\r
+// /** \r
+// * Transfer (targeted) Args to Slots\r
+// * \r
+// * Transfer Strings with format "tag=value" into Static Slots\r
+// */\r
+// public abstract void transfer(String args[], String ... tagss);\r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.lang.reflect.GenericArrayType;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map.Entry;
-
-import org.onap.aaf.misc.env.util.Split;
-
-import java.util.Properties;
-
-
-public class StoreImpl implements Store {
- /*
- * The re-adjustment factor for growing the Static State array.
- */
- private static final int growSize = 10;
-
- /*
- * The index reference for Slot assignment.
- */
- private int local;
-
- /*
- * The index reference for StaticSlot assignment.
- */
- private int stat;
-
- /*
- * The name/slot map for local (transaction specific) State.
- */
- private HashMap<String, Slot> localMap;
-
- /*
- * The name/slot map for Static State.
- */
- private HashMap<String, StaticSlot> staticMap;
-
- private Object[] staticState;
-
- public StoreImpl() {
- staticState = new Object[growSize];
- staticMap = new HashMap<String,StaticSlot>();
- localMap = new HashMap<String,Slot>();
- }
-
- public StoreImpl(String tag) {
- staticState = new Object[growSize];
- staticMap = new HashMap<String,StaticSlot>();
- localMap = new HashMap<String,Slot>();
- }
-
-
- public StoreImpl(String tag, String[] args) {
- staticState = new Object[growSize];
- staticMap = new HashMap<String,StaticSlot>();
- localMap = new HashMap<String,Slot>();
-
- if(tag!=null) {
- String tequals = tag + '=';
- for(String arg : args) {
- if(arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after =
- Properties props = new Properties();
- for(String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) {
- moreProps(new File(f),props);
- }
- for(Entry<Object, Object> es : props.entrySet()) {
- put(staticSlot(es.getKey().toString()),es.getValue());
- }
- }
- }
- }
-
- // Make sure properties on command line override those in Props
- propsFromArgs(tag,args);
- }
-
- public StoreImpl(String tag, Properties props) {
- staticState = new Object[growSize];
- staticMap = new HashMap<String,StaticSlot>();
- localMap = new HashMap<String,Slot>();
-
- if(tag!=null) {
- String fname = props.getProperty(tag);
- if(fname!=null) {
- for(String f : Split.split(File.pathSeparatorChar,fname)) {
- if(!moreProps(new File(f),props)) {
- System.err.println("Unable to load Properties from " + f);
- }
- }
- }
- }
-
- for(Entry<Object, Object> es : props.entrySet()) {
- put(staticSlot(es.getKey().toString()),es.getValue());
- }
- }
-
- public void propsFromArgs(String tag, String[] args) {
- if(tag!=null) {
- for(String arg : args) {
- String sarg[] = Split.split('=',arg);
- if(sarg.length==2) {
- if(tag.equals(sarg[0])) {
- for(String fname : Split.split(File.pathSeparatorChar,sarg[1])) {
- moreProps(new File(fname),null /* no target */);
- }
- }
- put(staticSlot(sarg[0]),sarg[1]);
- }
- }
- }
- }
-
- private boolean moreProps(File f, Properties target) {
- if(f.exists()) {
- Properties props = new Properties();
- try {
- FileInputStream fis = new FileInputStream(f);
- try {
- props.load(fis);
- if(target!=null) {
- target.load(fis);
- }
- } finally {
- fis.close();
- }
- } catch(IOException e) {
- System.err.println(e);
- }
- for(Entry<Object, Object> es : props.entrySet()) {
- put(staticSlot(es.getKey().toString()),es.getValue());
- }
- return true;
- } else {
- return false;
- }
- }
-
- public Object[] newTransState() {
- return new Object[local];
- }
-
- /* (non-Javadoc)
- * @see com.att.env.Store#slot(java.lang.String)
- */
- public synchronized Slot slot(String name) {
- name = name == null ? "" : name.trim();
- Slot slot = localMap.get(name);
- if (slot == null) {
- slot = new Slot(local++, name);
- localMap.put(name, slot);
- }
- return slot;
- }
-
-
- /* (non-Javadoc)
- * @see com.att.env.Store#existingSlot(java.lang.String)
- */
- public Slot existingSlot(String name) {
- return localMap.get(name);
- }
-
- /* (non-Javadoc)
- * @see com.att.env.Store#existingSlotNames()
- */
- public List<String> existingSlotNames() {
- return new ArrayList<String>(localMap.keySet());
- }
-
- /* (non-Javadoc)
- * @see com.att.env.Store#staticSlot(java.lang.String)
- */
- public synchronized StaticSlot staticSlot(String name) {
- name = name == null ? "" : name.trim();
- StaticSlot slot = staticMap.get(name);
- if (slot == null) {
- if (stat%growSize == 0) {
- Object[] temp = staticState;
- staticState = new Object[temp.length+growSize];
- System.arraycopy(temp, 0, staticState, 0, temp.length);
- }
- slot = new StaticSlot(stat++, name);
- staticMap.put(name, slot);
- }
- return slot;
- }
-
- /* (non-Javadoc)
- * @see com.att.env.Store#put(com.att.env.StaticSlot, java.lang.Object)
- */
- public void put(StaticSlot slot, Object value) {
- staticState[slot.slot] = value;
- }
-
- /* (non-Javadoc)
- * @see com.att.env.Store#get(com.att.env.StaticSlot T defaultObject)
- */
- @SuppressWarnings("unchecked")
- public<T> T get(StaticSlot sslot,T dflt) {
- T t = (T)staticState[sslot.slot];
- return t==null?dflt:t;
- }
-
- @SuppressWarnings("unchecked")
- public <T> T get(StaticSlot sslot) {
- return (T)staticState[sslot.slot];
- }
-
- public List<String> existingStaticSlotNames() {
- return new ArrayList<String>(staticMap.keySet());
- }
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.IOException;\r
+import java.lang.reflect.GenericArrayType;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map.Entry;\r
+\r
+import org.onap.aaf.misc.env.util.Split;\r
+\r
+import java.util.Properties;\r
+\r
+\r
+public class StoreImpl implements Store {\r
+ /*\r
+ * The re-adjustment factor for growing the Static State array. \r
+ */\r
+ private static final int growSize = 10;\r
+ \r
+ /*\r
+ * The index reference for Slot assignment.\r
+ */\r
+ private int local;\r
+ \r
+ /*\r
+ * The index reference for StaticSlot assignment. \r
+ */\r
+ private int stat;\r
+ \r
+ /*\r
+ * The name/slot map for local (transaction specific) State.\r
+ */\r
+ private HashMap<String, Slot> localMap;\r
+ \r
+ /*\r
+ * The name/slot map for Static State.\r
+ */\r
+ private HashMap<String, StaticSlot> staticMap;\r
+\r
+ private Object[] staticState;\r
+ \r
+ public StoreImpl() {\r
+ staticState = new Object[growSize];\r
+ staticMap = new HashMap<String,StaticSlot>();\r
+ localMap = new HashMap<String,Slot>();\r
+ }\r
+ \r
+ public StoreImpl(String tag) {\r
+ staticState = new Object[growSize];\r
+ staticMap = new HashMap<String,StaticSlot>();\r
+ localMap = new HashMap<String,Slot>();\r
+ }\r
+\r
+ \r
+ public StoreImpl(String tag, String[] args) {\r
+ staticState = new Object[growSize];\r
+ staticMap = new HashMap<String,StaticSlot>();\r
+ localMap = new HashMap<String,Slot>();\r
+\r
+ if(tag!=null) {\r
+ String tequals = tag + '=';\r
+ for(String arg : args) {\r
+ if(arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after =\r
+ Properties props = new Properties();\r
+ for(String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) {\r
+ moreProps(new File(f),props);\r
+ }\r
+ for(Entry<Object, Object> es : props.entrySet()) {\r
+ put(staticSlot(es.getKey().toString()),es.getValue());\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ // Make sure properties on command line override those in Props\r
+ propsFromArgs(tag,args);\r
+ }\r
+ \r
+ public StoreImpl(String tag, Properties props) {\r
+ staticState = new Object[growSize];\r
+ staticMap = new HashMap<String,StaticSlot>();\r
+ localMap = new HashMap<String,Slot>();\r
+ \r
+ if(tag!=null) {\r
+ String fname = props.getProperty(tag);\r
+ if(fname!=null) {\r
+ for(String f : Split.split(File.pathSeparatorChar,fname)) {\r
+ if(!moreProps(new File(f),props)) {\r
+ System.err.println("Unable to load Properties from " + f); \r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ for(Entry<Object, Object> es : props.entrySet()) {\r
+ put(staticSlot(es.getKey().toString()),es.getValue());\r
+ }\r
+ }\r
+\r
+ public void propsFromArgs(String tag, String[] args) {\r
+ if(tag!=null) {\r
+ for(String arg : args) {\r
+ String sarg[] = Split.split('=',arg);\r
+ if(sarg.length==2) {\r
+ if(tag.equals(sarg[0])) {\r
+ for(String fname : Split.split(File.pathSeparatorChar,sarg[1])) {\r
+ moreProps(new File(fname),null /* no target */);\r
+ }\r
+ }\r
+ put(staticSlot(sarg[0]),sarg[1]);\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ private boolean moreProps(File f, Properties target) {\r
+ if(f.exists()) {\r
+ Properties props = new Properties();\r
+ try {\r
+ FileInputStream fis = new FileInputStream(f);\r
+ try {\r
+ props.load(fis);\r
+ if(target!=null) {\r
+ target.load(fis);\r
+ }\r
+ } finally {\r
+ fis.close();\r
+ }\r
+ } catch(IOException e) {\r
+ System.err.println(e);\r
+ }\r
+ for(Entry<Object, Object> es : props.entrySet()) {\r
+ put(staticSlot(es.getKey().toString()),es.getValue());\r
+ }\r
+ return true;\r
+ } else {\r
+ return false;\r
+ }\r
+ }\r
+\r
+ public Object[] newTransState() {\r
+ return new Object[local];\r
+ }\r
+\r
+ /* (non-Javadoc)\r
+ * @see com.att.env.Store#slot(java.lang.String)\r
+ */\r
+ public synchronized Slot slot(String name) {\r
+ name = name == null ? "" : name.trim();\r
+ Slot slot = localMap.get(name);\r
+ if (slot == null) {\r
+ slot = new Slot(local++, name);\r
+ localMap.put(name, slot);\r
+ }\r
+ return slot;\r
+ }\r
+ \r
+ \r
+ /* (non-Javadoc)\r
+ * @see com.att.env.Store#existingSlot(java.lang.String)\r
+ */\r
+ public Slot existingSlot(String name) {\r
+ return localMap.get(name);\r
+ }\r
+ \r
+ /* (non-Javadoc)\r
+ * @see com.att.env.Store#existingSlotNames()\r
+ */\r
+ public List<String> existingSlotNames() {\r
+ return new ArrayList<String>(localMap.keySet());\r
+ }\r
+\r
+ /* (non-Javadoc)\r
+ * @see com.att.env.Store#staticSlot(java.lang.String)\r
+ */\r
+ public synchronized StaticSlot staticSlot(String name) {\r
+ name = name == null ? "" : name.trim();\r
+ StaticSlot slot = staticMap.get(name);\r
+ if (slot == null) {\r
+ if (stat%growSize == 0) {\r
+ Object[] temp = staticState;\r
+ staticState = new Object[temp.length+growSize];\r
+ System.arraycopy(temp, 0, staticState, 0, temp.length);\r
+ }\r
+ slot = new StaticSlot(stat++, name);\r
+ staticMap.put(name, slot);\r
+ }\r
+ return slot;\r
+ }\r
+ \r
+ /* (non-Javadoc)\r
+ * @see com.att.env.Store#put(com.att.env.StaticSlot, java.lang.Object)\r
+ */\r
+ public void put(StaticSlot slot, Object value) {\r
+ staticState[slot.slot] = value;\r
+ }\r
+ \r
+ /* (non-Javadoc)\r
+ * @see com.att.env.Store#get(com.att.env.StaticSlot T defaultObject)\r
+ */\r
+ @SuppressWarnings("unchecked")\r
+ public<T> T get(StaticSlot sslot,T dflt) {\r
+ T t = (T)staticState[sslot.slot];\r
+ return t==null?dflt:t;\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public <T> T get(StaticSlot sslot) {\r
+ return (T)staticState[sslot.slot];\r
+ }\r
+\r
+ public List<String> existingStaticSlotNames() {\r
+ return new ArrayList<String>(staticMap.keySet());\r
+ }\r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-
-/**
- * <h1>Stringifier</h1>
- * <i>Stringifier</i> abstracts the marshaling of a String to an Object
- */
-public interface Stringifier<T> extends LifeCycle {
-
- /**
- * Marshal from a String to an Object T, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return String
- * @throws APIException
- */
- public abstract String stringify(Env env, T input, boolean ... options) throws APIException;
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+\r
+/**\r
+ * <h1>Stringifier</h1>\r
+ * <i>Stringifier</i> abstracts the marshaling of a String to an Object\r
+ */\r
+public interface Stringifier<T> extends LifeCycle {\r
+ \r
+ /**\r
+ * Marshal from a String to an Object T, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public abstract String stringify(Env env, T input, boolean ... options) throws APIException;\r
+ \r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-/**
- * <h1>TimeTaken</h1>
- * This simple interface allows for many different kinds of
- * Audit Logs to be accomplished, by assuming that the creation
- * of this object indicates "start", and the calling of "done"
- * ends.
- *
- * The implementor of this class can easily be stored in efficient
- * mechanisms to minimize impact of Auditing on performance.
- *
- * @author Jonathan
- *
- */
-public abstract class TimeTaken {
- public final long start;
- protected long end, size;
- public final int flag;
- public final String name;
-
- /**
- * The name is as it will appear when written to output (abstract method)
- *
- * The flag is an integer which can be System type (XML, REMOTE, etc), or End User defined for reporting purposes
- *
- * @param name
- * @param flag
- */
- public TimeTaken(String name, int flag) {
- start = System.nanoTime();
- this.flag = flag;
- this.name = name;
- size = -1;
- }
-
-
- /**
- * Call this when process is done to state ending time.<p>
- *
- * It is <i>exceedingly prudent</i> to wrap the process called with a try-finally:<p>
- *
- * <pre>
- * TimeTaken tt = env.startSubTime();
- * try {
- * process.me(); // code to be timed.
- * } finally {
- * tt.done();
- * }
- * </pre>
- */
- public void done() {
- end = System.nanoTime();
- }
-
-
- /**
- * For sizable contents, set the size. Implementations can simply write a no-op if they don't wish to
- * store the size.
- *
- * @param size
- */
- public void size(long theSize) {
- size = theSize;
- }
-
- /**
- * Give readonly access to End, which isn't final
- * @return
- */
- public long end() {
- return end;
- }
-
- /**
- * Time is taken in NanoSeconds. This method converts to decimals of Milliseconds
- * @return
- */
- public float millis() {
- return (end-start)/1000000f;
- }
- /**
- * Write self to a String Builder (for making Audits)
- * @param sb
- */
- public abstract void output(StringBuilder sb);
-
- /**
- * For Debugging
- */
- public String toString() {
- return name + ' ' + millis() + "ms " + (size>0?Long.toString(size):"");
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+/**\r
+ * <h1>TimeTaken</h1>\r
+ * This simple interface allows for many different kinds of \r
+ * Audit Logs to be accomplished, by assuming that the creation\r
+ * of this object indicates "start", and the calling of "done" \r
+ * ends.\r
+ * \r
+ * The implementor of this class can easily be stored in efficient\r
+ * mechanisms to minimize impact of Auditing on performance.\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public abstract class TimeTaken {\r
+ public final long start;\r
+ protected long end, size;\r
+ public final int flag;\r
+ public final String name;\r
+ \r
+ /**\r
+ * The name is as it will appear when written to output (abstract method)\r
+ * \r
+ * The flag is an integer which can be System type (XML, REMOTE, etc), or End User defined for reporting purposes \r
+ * \r
+ * @param name\r
+ * @param flag\r
+ */\r
+ public TimeTaken(String name, int flag) {\r
+ start = System.nanoTime();\r
+ this.flag = flag;\r
+ this.name = name;\r
+ size = -1;\r
+ }\r
+\r
+\r
+ /**\r
+ * Call this when process is done to state ending time.<p>\r
+ * \r
+ * It is <i>exceedingly prudent</i> to wrap the process called with a try-finally:<p>\r
+ * \r
+ * <pre>\r
+ * TimeTaken tt = env.startSubTime();\r
+ * try {\r
+ * process.me(); // code to be timed.\r
+ * } finally {\r
+ * tt.done();\r
+ * }\r
+ * </pre>\r
+ */\r
+ public void done() {\r
+ end = System.nanoTime();\r
+ }\r
+ \r
+ \r
+ /**\r
+ * For sizable contents, set the size. Implementations can simply write a no-op if they don't wish to \r
+ * store the size. \r
+ * \r
+ * @param size\r
+ */\r
+ public void size(long theSize) {\r
+ size = theSize;\r
+ }\r
+ \r
+ /**\r
+ * Give readonly access to End, which isn't final\r
+ * @return\r
+ */\r
+ public long end() {\r
+ return end;\r
+ }\r
+ \r
+ /**\r
+ * Time is taken in NanoSeconds. This method converts to decimals of Milliseconds\r
+ * @return\r
+ */\r
+ public float millis() {\r
+ return (end-start)/1000000f;\r
+ }\r
+ /**\r
+ * Write self to a String Builder (for making Audits)\r
+ * @param sb\r
+ */\r
+ public abstract void output(StringBuilder sb);\r
+ \r
+ /**\r
+ * For Debugging\r
+ */\r
+ public String toString() {\r
+ return name + ' ' + millis() + "ms " + (size>0?Long.toString(size):"");\r
+ }\r
+ \r
+} \r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-
-
-
-/**
- * A Trans is like an Env, however, it's purpose it to track the Transient
- * Data associated with Transactions, or other short term elements.
- *
- * Any Object implementing Trans should expect to go in an out of scope quickly
- *
- * Implementations should also overload the concepts of "Start", etc and build up
- * and Audit Log, so it can implement "metric" below
- *
- * All Transactions (i.e. a call to a service) will need these items.
- *
- * @author Jonathan
- *
- */
-public interface Trans extends Env {
- /**
- * Add a completed entry in the Audit Trail for tracking purposes.
- *
- * @param text
- */
- public void checkpoint(String text);
-
- /**
- * Add a completed entry in the Audit Trail for tracking purposes, and combine flag with "CHECKPOINT"
- *
- * @param text
- */
- public void checkpoint(String text, int additionalFlag);
-
- /**
- * Output an Audit Trail onto the StringBuilder
- *
- * Load metrics into an array of floats from passed in Flags
- *
- * @param flag
- * @param sb
- * @return
- */
- public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flag);
-
- public Metric auditTrail(int indent, StringBuilder sb, int ... flag);
-
- public class Metric {
- public float[] buckets;
- public float total;
- public int entries;
- }
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+\r
+\r
+\r
+/**\r
+ * A Trans is like an Env, however, it's purpose it to track the Transient \r
+ * Data associated with Transactions, or other short term elements.\r
+ * \r
+ * Any Object implementing Trans should expect to go in an out of scope quickly\r
+ * \r
+ * Implementations should also overload the concepts of "Start", etc and build up\r
+ * and Audit Log, so it can implement "metric" below\r
+ * \r
+ * All Transactions (i.e. a call to a service) will need these items.\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public interface Trans extends Env {\r
+ /**\r
+ * Add a completed entry in the Audit Trail for tracking purposes.\r
+ * \r
+ * @param text\r
+ */\r
+ public void checkpoint(String text);\r
+\r
+ /**\r
+ * Add a completed entry in the Audit Trail for tracking purposes, and combine flag with "CHECKPOINT" \r
+ * \r
+ * @param text\r
+ */\r
+ public void checkpoint(String text, int additionalFlag);\r
+\r
+ /**\r
+ * Output an Audit Trail onto the StringBuilder\r
+ *\r
+ * Load metrics into an array of floats from passed in Flags\r
+ * \r
+ * @param flag\r
+ * @param sb\r
+ * @return \r
+ */\r
+ public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flag);\r
+\r
+ public Metric auditTrail(int indent, StringBuilder sb, int ... flag);\r
+\r
+ public class Metric {\r
+ public float[] buckets;\r
+ public float total;\r
+ public int entries;\r
+ }\r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-public interface TransCreate<TRANS> {
- public TRANS newTrans();
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+public interface TransCreate<TRANS> {\r
+ public TRANS newTrans();\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-public interface TransJAXB extends Trans, TransStore {
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+public interface TransJAXB extends Trans, TransStore {\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env;
-
-public interface TransStore extends Trans {
- /**
- * Returns the Slot assigned to the supplied name.
- *
- * @param name
- * The name of the Slot to acquire.
- * @return
- * The Slot associated with the supplied name.
- */
- public abstract Slot slot(String name);
-
- /**
- * Put data into the right slot
- */
- public void put(Slot slot, Object value);
-
- /**
- * Get data from the right slot
- *
- * This will do a cast to the expected type derived from Default
- */
- public<T> T get(Slot slot, T deflt);
-
- /**
- * Returns an Object from the Organizer's static state, or the Default if null
- *
- * @param slot
- * The StaticSlot to retrieve the data from.
- * @return
- * The Object located in the supplied StaticSlot of the Organizer's static state.
- */
- public abstract<T> T get(StaticSlot slot, T dflt);
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env;\r
+\r
+public interface TransStore extends Trans {\r
+ /**\r
+ * Returns the Slot assigned to the supplied name.\r
+ * \r
+ * @param name\r
+ * The name of the Slot to acquire.\r
+ * @return\r
+ * The Slot associated with the supplied name.\r
+ */\r
+ public abstract Slot slot(String name);\r
+ \r
+ /**\r
+ * Put data into the right slot \r
+ */\r
+ public void put(Slot slot, Object value);\r
+\r
+ /**\r
+ * Get data from the right slot\r
+ * \r
+ * This will do a cast to the expected type derived from Default\r
+ */\r
+ public<T> T get(Slot slot, T deflt);\r
+\r
+ /**\r
+ * Returns an Object from the Organizer's static state, or the Default if null\r
+ * \r
+ * @param slot\r
+ * The StaticSlot to retrieve the data from.\r
+ * @return\r
+ * The Object located in the supplied StaticSlot of the Organizer's static state.\r
+ */\r
+ public abstract<T> T get(StaticSlot slot, T dflt);\r
+ \r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Stack;
-
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.LogTarget;
-import org.onap.aaf.misc.env.Slot;
-import org.onap.aaf.misc.env.StoreImpl;
-import org.onap.aaf.misc.env.TimeTaken;
-import org.onap.aaf.misc.env.TransStore;
-
-public abstract class AbsTrans<ENV extends Env> implements TransStore {
- private static final float[] EMPTYF = new float[0];
- private static final Object[] EMPTYO = new Object[0];
-
- protected ENV delegate;
- protected List<TimeTaken> trail = new ArrayList<TimeTaken>(30);
- private Object[] state;
-
-
- public AbsTrans(ENV delegate) {
- this.delegate = delegate;
- state = delegate instanceof StoreImpl?((StoreImpl) delegate).newTransState():EMPTYO;
- }
-
- // @Override
- public LogTarget fatal() {
- return delegate.fatal();
- }
-
-// @Override
- public LogTarget error() {
- return delegate.error();
- }
-
-// @Override
- public LogTarget audit() {
- return delegate.audit();
- }
-
-// @Override
- public LogTarget init() {
- return delegate.init();
- }
-
-// @Override
- public LogTarget warn() {
- return delegate.warn();
- }
-
-// @Override
- public LogTarget info() {
- return delegate.info();
- }
-
-// @Override
- public LogTarget debug() {
- return delegate.debug();
- }
-
-// @Override
- public LogTarget trace() {
- return delegate.trace();
- }
-
- /**
- * Let the final Trans Implementation choose the exact kind of TimeTaken to use
- * @param name
- * @param flag
- * @return
- */
- protected abstract TimeTaken newTimeTaken(String name, int flag);
-
-// @Override
- public final TimeTaken start(String name, int flag) {
- TimeTaken tt = newTimeTaken(name,flag);
- trail.add(tt);
- return tt;
- }
-
-// @Override
- public final void checkpoint(String name) {
- TimeTaken tt = newTimeTaken(name,CHECKPOINT);
- tt.done();
- trail.add(tt);
- }
-
- public final void checkpoint(String name, int additionalFlag) {
- TimeTaken tt = newTimeTaken(name,CHECKPOINT|additionalFlag);
- trail.add(tt);
- tt.done();
- }
-
- @Override
- public Metric auditTrail(int indent, StringBuilder sb, int ... flags) {
- return auditTrail(info(),indent,sb,flags);
- }
-
- @Override
- public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flags) {
- Metric metric = new Metric();
- int last = (metric.entries = trail.size()) -1;
- metric.buckets = flags.length==0?EMPTYF:new float[flags.length];
- if(last>=0) {
- TimeTaken first = trail.get(0);
- // If first entry is sub, then it's actually the last "end" as well
- // otherwise, check end
- //long end = (first.flag&SUB)==SUB?first.end():trail.get(last).end();
- long end = trail.get(last).end();
- metric.total = (end - first.start) / 1000000f;
- }
-
- if(sb==null) {
- for(TimeTaken tt : trail) {
- float ms = tt.millis();
- for(int i=0;i<flags.length;++i) {
- if(tt.flag == flags[i]) metric.buckets[i]+=ms;
- }
- }
- } else if(!lt.isLoggable()) {
- boolean first = true;
- for(TimeTaken tt : trail) {
- float ms = tt.millis();
- for(int i=0;i<flags.length;++i) {
- if(tt.flag == flags[i]) metric.buckets[i]+=ms;
- }
- if((tt.flag&ALWAYS)==ALWAYS) {
- if(first) first = false;
- else sb.append('/');
- sb.append(tt.name);
- }
- }
- } else {
- Stack<Long> stack = new Stack<Long>();
- for(TimeTaken tt : trail) {
- // Create Indentation based on SUB
- while(!stack.isEmpty() && tt.end()>stack.peek()) {
- --indent;
- stack.pop();
- }
- for(int i=0;i<indent;++i) {
- sb.append(" ");
- }
- tt.output(sb);
- sb.append('\n');
- if((tt.flag&SUB)==SUB) {
- stack.push(tt.end());
- ++indent;
- }
-
- // Add time values to Metric
- float ms = tt.millis();
- for(int i=0;i<flags.length;++i) {
- if(tt.flag == flags[i]) metric.buckets[i]+=ms;
- }
- }
- }
- return metric;
- }
-
- /**
- * Put data into the Trans State at the right slot
- */
-// @Override
- public void put(Slot slot, Object value) {
- slot.put(state, value);
- }
-
- /**
- * Get data from the Trans State from the right slot
- *
- * This will do a cast to the expected type derived from Default
- */
-// @Override
- @SuppressWarnings("unchecked")
- public<T> T get(Slot slot, T deflt) {
- Object o;
- try {
- o = slot.get(state);
- } catch(ArrayIndexOutOfBoundsException e) {
- // Env State Size has changed because of dynamic Object creation... Rare event, but needs to be covered
- Object[] temp = ((StoreImpl) delegate).newTransState();
- System.arraycopy(state, 0, temp, 0, state.length);
- state = temp;
- o=null;
- }
- return o==null?deflt:(T)o;
- }
-
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Stack;\r
+\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+import org.onap.aaf.misc.env.Slot;\r
+import org.onap.aaf.misc.env.StoreImpl;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+import org.onap.aaf.misc.env.TransStore;\r
+\r
+public abstract class AbsTrans<ENV extends Env> implements TransStore {\r
+ private static final float[] EMPTYF = new float[0];\r
+ private static final Object[] EMPTYO = new Object[0];\r
+ \r
+ protected ENV delegate;\r
+ protected List<TimeTaken> trail = new ArrayList<TimeTaken>(30);\r
+ private Object[] state;\r
+ \r
+ \r
+ public AbsTrans(ENV delegate) {\r
+ this.delegate = delegate;\r
+ state = delegate instanceof StoreImpl?((StoreImpl) delegate).newTransState():EMPTYO;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget fatal() {\r
+ return delegate.fatal();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget error() {\r
+ return delegate.error();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget audit() {\r
+ return delegate.audit();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget init() {\r
+ return delegate.init();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget warn() {\r
+ return delegate.warn();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget info() {\r
+ return delegate.info();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget debug() {\r
+ return delegate.debug();\r
+ }\r
+\r
+// @Override\r
+ public LogTarget trace() {\r
+ return delegate.trace();\r
+ }\r
+\r
+ /**\r
+ * Let the final Trans Implementation choose the exact kind of TimeTaken to use\r
+ * @param name\r
+ * @param flag\r
+ * @return\r
+ */\r
+ protected abstract TimeTaken newTimeTaken(String name, int flag);\r
+ \r
+// @Override\r
+ public final TimeTaken start(String name, int flag) {\r
+ TimeTaken tt = newTimeTaken(name,flag);\r
+ trail.add(tt);\r
+ return tt;\r
+ }\r
+ \r
+// @Override\r
+ public final void checkpoint(String name) {\r
+ TimeTaken tt = newTimeTaken(name,CHECKPOINT);\r
+ tt.done();\r
+ trail.add(tt);\r
+ }\r
+\r
+ public final void checkpoint(String name, int additionalFlag) {\r
+ TimeTaken tt = newTimeTaken(name,CHECKPOINT|additionalFlag);\r
+ trail.add(tt);\r
+ tt.done();\r
+ }\r
+\r
+ @Override\r
+ public Metric auditTrail(int indent, StringBuilder sb, int ... flags) {\r
+ return auditTrail(info(),indent,sb,flags);\r
+ }\r
+ \r
+ @Override\r
+ public Metric auditTrail(LogTarget lt, int indent, StringBuilder sb, int ... flags) {\r
+ Metric metric = new Metric();\r
+ int last = (metric.entries = trail.size()) -1;\r
+ metric.buckets = flags.length==0?EMPTYF:new float[flags.length];\r
+ if(last>=0) {\r
+ TimeTaken first = trail.get(0);\r
+ // If first entry is sub, then it's actually the last "end" as well\r
+ // otherwise, check end\r
+ //long end = (first.flag&SUB)==SUB?first.end():trail.get(last).end();\r
+ long end = trail.get(last).end();\r
+ metric.total = (end - first.start) / 1000000f;\r
+ }\r
+ \r
+ if(sb==null) {\r
+ for(TimeTaken tt : trail) {\r
+ float ms = tt.millis();\r
+ for(int i=0;i<flags.length;++i) {\r
+ if(tt.flag == flags[i]) metric.buckets[i]+=ms;\r
+ }\r
+ }\r
+ } else if(!lt.isLoggable()) {\r
+ boolean first = true;\r
+ for(TimeTaken tt : trail) {\r
+ float ms = tt.millis();\r
+ for(int i=0;i<flags.length;++i) {\r
+ if(tt.flag == flags[i]) metric.buckets[i]+=ms;\r
+ }\r
+ if((tt.flag&ALWAYS)==ALWAYS) {\r
+ if(first) first = false;\r
+ else sb.append('/');\r
+ sb.append(tt.name);\r
+ }\r
+ } \r
+ } else {\r
+ Stack<Long> stack = new Stack<Long>();\r
+ for(TimeTaken tt : trail) {\r
+ // Create Indentation based on SUB\r
+ while(!stack.isEmpty() && tt.end()>stack.peek()) {\r
+ --indent;\r
+ stack.pop();\r
+ }\r
+ for(int i=0;i<indent;++i) {\r
+ sb.append(" ");\r
+ }\r
+ tt.output(sb);\r
+ sb.append('\n');\r
+ if((tt.flag&SUB)==SUB) {\r
+ stack.push(tt.end());\r
+ ++indent;\r
+ }\r
+ \r
+ // Add time values to Metric\r
+ float ms = tt.millis();\r
+ for(int i=0;i<flags.length;++i) {\r
+ if(tt.flag == flags[i]) metric.buckets[i]+=ms;\r
+ }\r
+ }\r
+ }\r
+ return metric;\r
+ }\r
+\r
+ /**\r
+ * Put data into the Trans State at the right slot \r
+ */\r
+// @Override\r
+ public void put(Slot slot, Object value) {\r
+ slot.put(state, value);\r
+ }\r
+\r
+ /**\r
+ * Get data from the Trans State from the right slot\r
+ * \r
+ * This will do a cast to the expected type derived from Default\r
+ */\r
+// @Override\r
+ @SuppressWarnings("unchecked")\r
+ public<T> T get(Slot slot, T deflt) {\r
+ Object o;\r
+ try {\r
+ o = slot.get(state);\r
+ } catch(ArrayIndexOutOfBoundsException e) {\r
+ // Env State Size has changed because of dynamic Object creation... Rare event, but needs to be covered\r
+ Object[] temp = ((StoreImpl) delegate).newTransState();\r
+ System.arraycopy(state, 0, temp, 0, state.length);\r
+ state = temp;\r
+ o=null;\r
+ }\r
+ return o==null?deflt:(T)o;\r
+ }\r
+\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import javax.xml.namespace.QName;
-import javax.xml.validation.Schema;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.DataFactory;
-import org.onap.aaf.misc.env.EnvJAXB;
-import org.onap.aaf.misc.env.TransJAXB;
-
-public abstract class AbsTransJAXB extends AbsTrans<EnvJAXB> implements TransJAXB {
- public AbsTransJAXB(EnvJAXB env) {
- super(env);
- }
-
-// @Override
- public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException {
- return delegate.newDataFactory(classes);
- }
-
-// @Override
- public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException {
- return delegate.newDataFactory(schema, classes);
- }
-
-// @Override
- public <T> DataFactory<T> newDataFactory(QName qName, Class<?>... classes) throws APIException {
- return delegate.newDataFactory(qName, classes);
- }
-
-// @Override
- public <T> DataFactory<T> newDataFactory(Schema schema, QName qName, Class<?>... classes) throws APIException {
- return delegate.newDataFactory(schema, qName, classes);
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import javax.xml.namespace.QName;\r
+import javax.xml.validation.Schema;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.DataFactory;\r
+import org.onap.aaf.misc.env.EnvJAXB;\r
+import org.onap.aaf.misc.env.TransJAXB;\r
+\r
+public abstract class AbsTransJAXB extends AbsTrans<EnvJAXB> implements TransJAXB {\r
+ public AbsTransJAXB(EnvJAXB env) {\r
+ super(env);\r
+ }\r
+ \r
+// @Override\r
+ public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException {\r
+ return delegate.newDataFactory(classes);\r
+ }\r
+\r
+// @Override\r
+ public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException {\r
+ return delegate.newDataFactory(schema, classes);\r
+ }\r
+\r
+// @Override\r
+ public <T> DataFactory<T> newDataFactory(QName qName, Class<?>... classes) throws APIException {\r
+ return delegate.newDataFactory(qName, classes);\r
+ }\r
+\r
+// @Override\r
+ public <T> DataFactory<T> newDataFactory(Schema schema, QName qName, Class<?>... classes) throws APIException {\r
+ return delegate.newDataFactory(schema, qName, classes);\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import java.applet.Applet;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.Properties;
-
-import javax.xml.namespace.QName;
-import javax.xml.validation.Schema;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.DataFactory;
-import org.onap.aaf.misc.env.Decryptor;
-import org.onap.aaf.misc.env.Encryptor;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.EnvJAXB;
-import org.onap.aaf.misc.env.LogTarget;
-import org.onap.aaf.misc.env.StaticSlot;
-import org.onap.aaf.misc.env.StoreImpl;
-import org.onap.aaf.misc.env.TimeTaken;
-import org.onap.aaf.misc.env.TransCreate;
-import org.onap.aaf.misc.env.TransJAXB;
-import org.onap.aaf.misc.env.jaxb.JAXBDF;
-import org.onap.aaf.misc.env.util.Split;
-
-/**
- * An essential Implementation of Env, which will fully function, without any sort
- * of configuration.
- *
- * Use as a basis for Group level Env, just overriding where needed.
- * @author Jonathan
- *
- */
-public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAXB>{
- protected LogTarget fatal=LogTarget.SYSERR;
- protected LogTarget error=LogTarget.SYSERR;
- protected LogTarget audit=LogTarget.SYSOUT;
- protected LogTarget init=LogTarget.SYSOUT;
- protected LogTarget warn=LogTarget.SYSERR;
- protected LogTarget info=LogTarget.SYSOUT;
- protected LogTarget debug=LogTarget.NULL;
- protected LogTarget trace=LogTarget.NULL;
-// protected Map<String, String> props;
-
-// private boolean sysprops;
-
- public BasicEnv(String ... args) {
- super(null,args);
- }
-
- public BasicEnv(String tag, String[] args) {
- super(tag, args);
- }
-
-
- /**
- * Suitable for use in Applets... obtain all the values
- * listed for the variable String arg "tags"
- */
- public BasicEnv(Applet applet, String ... tags) {
- super(null, tags);
-// props = new HashMap<String, String>();
-// String value;
-// for(int i=0;i<tags.length;++i) {
-// value = applet.getParameter(tags[i]);
-// if(value!=null) {
-// props.put(tags[i], value);
-// }
-// }
- }
-
- public BasicEnv(Properties props) {
- super(null, props);
- }
-
- public BasicEnv(String tag, Properties props) {
- super(tag, props);
- }
-
-
-
- // @Override
- public LogTarget fatal() {
- return fatal;
- }
-
- // @Override
- public LogTarget error() {
- return error;
- }
-
-
- // @Override
- public LogTarget audit() {
- return audit;
- }
-
- // @Override
- public LogTarget init() {
- return init;
- }
-
- // @Override
- public LogTarget warn() {
- return warn;
- }
-
- // @Override
- public LogTarget info() {
- return info;
- }
-
- // @Override
- public LogTarget debug() {
- return debug;
- }
-
- public void debug(LogTarget lt) {
- debug = lt;
- }
-
- // @Override
- public LogTarget trace() {
- return trace;
- }
-
- // @Override
- public TimeTaken start(String name, int flag) {
- return new TimeTaken(name, flag) {
- /**
- * Format to be printed when called upon
- */
- // @Override
- public void output(StringBuilder sb) {
-
- switch(flag) {
- case Env.XML: sb.append("XML "); break;
- case Env.JSON: sb.append("JSON "); break;
- case Env.REMOTE: sb.append("REMOTE "); break;
- }
- sb.append(name);
- if(flag != Env.CHECKPOINT) {
- sb.append(' ');
- sb.append((end-start)/1000000f);
- sb.append("ms");
- if(size>=0) {
- sb.append(" size: ");
- sb.append(Long.toString(size));
- }
- }
- }
- };
- }
-
- // @Override
- public String getProperty(String key) {
- return get(staticSlot(key),null);
- }
-
- public Properties getProperties(String ... filter) {
- Properties props = new Properties();
- boolean yes;
- for(String key : existingStaticSlotNames()) {
- if(filter.length>0) {
- yes = false;
- for(String f : filter) {
- if(key.startsWith(f)) {
- yes = true;
- break;
- }
- }
- } else {
- yes = true;
- }
- if(yes) {
- String value = getProperty(key);
- if(value!=null) {
- props.put(key, value);
- }
- }
- }
- return props;
- }
-
- // @Override
- public String getProperty(String key, String defaultValue) {
- return get(staticSlot(key),defaultValue);
- }
-
- // @Override
- public String setProperty(String key, String value) {
- put(staticSlot(key),value==null?null:value.trim());
- return value;
- }
-
- protected Decryptor decryptor = Decryptor.NULL;
- protected Encryptor encryptor = Encryptor.NULL;
-
-
- public Decryptor decryptor() {
- return decryptor;
- }
-
- public void set(Decryptor newDecryptor) {
- decryptor = newDecryptor;
- }
-
- public Encryptor encryptor() {
- return encryptor;
- }
-
- public void set(Encryptor newEncryptor) {
- encryptor = newEncryptor;
- }
-
-
-// @SuppressWarnings("unchecked")
- // @Override
- public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException {
-// if(String.class.isAssignableFrom(classes[0]))
-// return (DataFactory<T>) new StringDF(this);
- return new JAXBDF<T>(this,classes);
- }
-
-// @SuppressWarnings("unchecked")
- // @Override
- public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException {
-// if(String.class.isAssignableFrom(classes[0]))
-// return (DataFactory<T>) new StringDF(this);
- return new JAXBDF<T>(this, schema, classes);
- }
-
-// @SuppressWarnings("unchecked")
- // @Override
- public<T> DataFactory<T> newDataFactory(QName qName, Class<?> ... classes) throws APIException {
-// if(String.class.isAssignableFrom(classes[0]))
-// return (DataFactory<T>) new StringDF(this);
- return new JAXBDF<T>(this, qName, classes);
- }
-
- // @Override
- public<T> DataFactory<T> newDataFactory(Schema schema, QName qName, Class<?> ... classes) throws APIException {
- return new JAXBDF<T>(this, schema, qName, classes);
- }
-
- // @Override
- public BasicTrans newTrans() {
- return new BasicTrans(this);
- }
-
- public void loadFromSystemPropsStartsWith(String ... str) {
- for(String name : System.getProperties().stringPropertyNames()) {
- for(String s : str) {
- if(name.startsWith(s)) {
- setProperty(name, System.getProperty(name));
- }
- }
- }
- }
-
- /**
- *
- *
- */
- public void loadToSystemPropsStartsWith(String ... str) {
- String value;
- for(String name : existingStaticSlotNames()) {
- for(String s : str) {
- if(name.startsWith(s)) {
- if((value = getProperty(name))!=null)
- System.setProperty(name,value);
- }
- }
- }
- }
-
- public void loadPropFiles(String tag, ClassLoader classloader) throws IOException {
- String propfiles = getProperty(tag);
- if(propfiles!=null) {
- for(String pf : Split.splitTrim(File.pathSeparatorChar, propfiles)) {
- InputStream is = classloader==null?null:classloader.getResourceAsStream(pf);
- if(is==null) {
- File f = new File(pf);
- if(f.exists()) {
- is = new FileInputStream(f);
- }
- }
- if(is!=null) {
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- try {
- String line;
- while((line=br.readLine())!=null) {
- line = line.trim();
- if(!line.startsWith("#")) {
- String[] tv = Split.splitTrim('=', line);
- if(tv.length==2) {
- setProperty(tv[0],tv[1]);
- }
- }
- }
- } finally {
- try {
- br.close();
- } catch (IOException e) {
- error().log(e);
- }
- }
- }
- }
- }
- }
-
- /**
- * Create a StaticSlot, and load it from existing Properties
- *
- * @param name
- * @param propName
- * @return
- */
- public synchronized StaticSlot staticSlot(String name, final String propName) {
- StaticSlot ss = staticSlot(name);
- put(ss,getProperty(propName));
- return ss;
- }
-
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import java.applet.Applet;\r
+import java.io.BufferedReader;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.InputStreamReader;\r
+import java.util.Properties;\r
+\r
+import javax.xml.namespace.QName;\r
+import javax.xml.validation.Schema;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.DataFactory;\r
+import org.onap.aaf.misc.env.Decryptor;\r
+import org.onap.aaf.misc.env.Encryptor;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.EnvJAXB;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+import org.onap.aaf.misc.env.StaticSlot;\r
+import org.onap.aaf.misc.env.StoreImpl;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+import org.onap.aaf.misc.env.TransCreate;\r
+import org.onap.aaf.misc.env.TransJAXB;\r
+import org.onap.aaf.misc.env.jaxb.JAXBDF;\r
+import org.onap.aaf.misc.env.util.Split;\r
+\r
+/**\r
+ * An essential Implementation of Env, which will fully function, without any sort\r
+ * of configuration.\r
+ * \r
+ * Use as a basis for Group level Env, just overriding where needed.\r
+ * @author Jonathan\r
+ *\r
+ */\r
+public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAXB>{\r
+ protected LogTarget fatal=LogTarget.SYSERR;\r
+ protected LogTarget error=LogTarget.SYSERR;\r
+ protected LogTarget audit=LogTarget.SYSOUT;\r
+ protected LogTarget init=LogTarget.SYSOUT;\r
+ protected LogTarget warn=LogTarget.SYSERR;\r
+ protected LogTarget info=LogTarget.SYSOUT;\r
+ protected LogTarget debug=LogTarget.NULL;\r
+ protected LogTarget trace=LogTarget.NULL;\r
+// protected Map<String, String> props;\r
+ \r
+// private boolean sysprops;\r
+\r
+ public BasicEnv(String ... args) {\r
+ super(null,args);\r
+ }\r
+\r
+ public BasicEnv(String tag, String[] args) {\r
+ super(tag, args);\r
+ }\r
+ \r
+\r
+ /**\r
+ * Suitable for use in Applets... obtain all the values \r
+ * listed for the variable String arg "tags"\r
+ */\r
+ public BasicEnv(Applet applet, String ... tags) {\r
+ super(null, tags);\r
+// props = new HashMap<String, String>();\r
+// String value;\r
+// for(int i=0;i<tags.length;++i) {\r
+// value = applet.getParameter(tags[i]);\r
+// if(value!=null) {\r
+// props.put(tags[i], value);\r
+// }\r
+// }\r
+ }\r
+\r
+ public BasicEnv(Properties props) {\r
+ super(null, props);\r
+ }\r
+\r
+ public BasicEnv(String tag, Properties props) {\r
+ super(tag, props);\r
+ }\r
+\r
+\r
+\r
+ // @Override\r
+ public LogTarget fatal() {\r
+ return fatal;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget error() {\r
+ return error;\r
+ }\r
+\r
+ \r
+ // @Override\r
+ public LogTarget audit() {\r
+ return audit;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget init() {\r
+ return init;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget warn() {\r
+ return warn;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget info() {\r
+ return info;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget debug() {\r
+ return debug;\r
+ }\r
+\r
+ public void debug(LogTarget lt) {\r
+ debug = lt;\r
+ }\r
+\r
+ // @Override\r
+ public LogTarget trace() {\r
+ return trace;\r
+ }\r
+\r
+ // @Override\r
+ public TimeTaken start(String name, int flag) {\r
+ return new TimeTaken(name, flag) {\r
+ /**\r
+ * Format to be printed when called upon\r
+ */\r
+ // @Override\r
+ public void output(StringBuilder sb) {\r
+ \r
+ switch(flag) {\r
+ case Env.XML: sb.append("XML "); break;\r
+ case Env.JSON: sb.append("JSON "); break;\r
+ case Env.REMOTE: sb.append("REMOTE "); break;\r
+ }\r
+ sb.append(name);\r
+ if(flag != Env.CHECKPOINT) {\r
+ sb.append(' ');\r
+ sb.append((end-start)/1000000f);\r
+ sb.append("ms");\r
+ if(size>=0) {\r
+ sb.append(" size: ");\r
+ sb.append(Long.toString(size));\r
+ }\r
+ }\r
+ }\r
+ };\r
+ }\r
+\r
+ // @Override\r
+ public String getProperty(String key) {\r
+ return get(staticSlot(key),null);\r
+ }\r
+ \r
+ public Properties getProperties(String ... filter) {\r
+ Properties props = new Properties();\r
+ boolean yes;\r
+ for(String key : existingStaticSlotNames()) {\r
+ if(filter.length>0) {\r
+ yes = false;\r
+ for(String f : filter) {\r
+ if(key.startsWith(f)) {\r
+ yes = true;\r
+ break;\r
+ }\r
+ }\r
+ } else {\r
+ yes = true;\r
+ }\r
+ if(yes) {\r
+ String value = getProperty(key);\r
+ if(value!=null) {\r
+ props.put(key, value);\r
+ }\r
+ }\r
+ }\r
+ return props;\r
+ }\r
+ \r
+ // @Override\r
+ public String getProperty(String key, String defaultValue) {\r
+ return get(staticSlot(key),defaultValue);\r
+ }\r
+\r
+ // @Override\r
+ public String setProperty(String key, String value) {\r
+ put(staticSlot(key),value==null?null:value.trim());\r
+ return value;\r
+ }\r
+ \r
+ protected Decryptor decryptor = Decryptor.NULL;\r
+ protected Encryptor encryptor = Encryptor.NULL;\r
+\r
+ \r
+ public Decryptor decryptor() {\r
+ return decryptor; \r
+ }\r
+ \r
+ public void set(Decryptor newDecryptor) {\r
+ decryptor = newDecryptor;\r
+ }\r
+ \r
+ public Encryptor encryptor() {\r
+ return encryptor; \r
+ }\r
+ \r
+ public void set(Encryptor newEncryptor) {\r
+ encryptor = newEncryptor;\r
+ }\r
+\r
+ \r
+// @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException {\r
+// if(String.class.isAssignableFrom(classes[0])) \r
+// return (DataFactory<T>) new StringDF(this);\r
+ return new JAXBDF<T>(this,classes);\r
+ }\r
+\r
+// @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException {\r
+// if(String.class.isAssignableFrom(classes[0])) \r
+// return (DataFactory<T>) new StringDF(this);\r
+ return new JAXBDF<T>(this, schema, classes);\r
+ }\r
+\r
+// @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public<T> DataFactory<T> newDataFactory(QName qName, Class<?> ... classes) throws APIException {\r
+// if(String.class.isAssignableFrom(classes[0])) \r
+// return (DataFactory<T>) new StringDF(this);\r
+ return new JAXBDF<T>(this, qName, classes);\r
+ }\r
+\r
+ // @Override\r
+ public<T> DataFactory<T> newDataFactory(Schema schema, QName qName, Class<?> ... classes) throws APIException {\r
+ return new JAXBDF<T>(this, schema, qName, classes);\r
+ }\r
+\r
+ // @Override\r
+ public BasicTrans newTrans() {\r
+ return new BasicTrans(this);\r
+ }\r
+\r
+ public void loadFromSystemPropsStartsWith(String ... str) {\r
+ for(String name : System.getProperties().stringPropertyNames()) {\r
+ for(String s : str) {\r
+ if(name.startsWith(s)) {\r
+ setProperty(name, System.getProperty(name));\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * \r
+ * \r
+ */\r
+ public void loadToSystemPropsStartsWith(String ... str) {\r
+ String value;\r
+ for(String name : existingStaticSlotNames()) {\r
+ for(String s : str) {\r
+ if(name.startsWith(s)) {\r
+ if((value = getProperty(name))!=null)\r
+ System.setProperty(name,value);\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ public void loadPropFiles(String tag, ClassLoader classloader) throws IOException {\r
+ String propfiles = getProperty(tag);\r
+ if(propfiles!=null) {\r
+ for(String pf : Split.splitTrim(File.pathSeparatorChar, propfiles)) {\r
+ InputStream is = classloader==null?null:classloader.getResourceAsStream(pf);\r
+ if(is==null) {\r
+ File f = new File(pf);\r
+ if(f.exists()) {\r
+ is = new FileInputStream(f);\r
+ }\r
+ }\r
+ if(is!=null) {\r
+ BufferedReader br = new BufferedReader(new InputStreamReader(is));\r
+ try {\r
+ String line;\r
+ while((line=br.readLine())!=null) {\r
+ line = line.trim();\r
+ if(!line.startsWith("#")) {\r
+ String[] tv = Split.splitTrim('=', line);\r
+ if(tv.length==2) {\r
+ setProperty(tv[0],tv[1]);\r
+ }\r
+ }\r
+ }\r
+ } finally {\r
+ try {\r
+ br.close();\r
+ } catch (IOException e) {\r
+ error().log(e);\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Create a StaticSlot, and load it from existing Properties\r
+ * \r
+ * @param name\r
+ * @param propName\r
+ * @return\r
+ */\r
+ public synchronized StaticSlot staticSlot(String name, final String propName) {\r
+ StaticSlot ss = staticSlot(name);\r
+ put(ss,getProperty(propName));\r
+ return ss;\r
+ }\r
+\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import org.onap.aaf.misc.env.Decryptor;
-import org.onap.aaf.misc.env.Encryptor;
-import org.onap.aaf.misc.env.EnvJAXB;
-import org.onap.aaf.misc.env.Slot;
-import org.onap.aaf.misc.env.StaticSlot;
-import org.onap.aaf.misc.env.TimeTaken;
-
-
-public class BasicTrans extends AbsTransJAXB {
-
- public BasicTrans(EnvJAXB env) {
- super(env);
- }
-
- @Override
- protected TimeTaken newTimeTaken(String name, int flag) {
- /**
- * Note: could have created a different format for Time Taken, but using BasicEnv's instead
- */
- return delegate.start(name, flag);
- }
-
- public Slot slot(String name) {
- return delegate.slot(name);
- }
-
- public <T> T get(StaticSlot slot) {
- return delegate.get(slot);
- }
-
- public <T> T get(StaticSlot slot, T dflt) {
- return delegate.get(slot,dflt);
- }
-
- public String setProperty(String tag, String value) {
- delegate.setProperty(tag, value);
- return value;
- }
-
- public String getProperty(String tag) {
- return delegate.getProperty(tag);
- }
-
- public String getProperty(String tag, String deflt) {
- return delegate.getProperty(tag, deflt);
- }
-
- @Override
- public Decryptor decryptor() {
- return delegate.decryptor();
- }
-
- @Override
- public Encryptor encryptor() {
- return delegate.encryptor();
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import org.onap.aaf.misc.env.Decryptor;\r
+import org.onap.aaf.misc.env.Encryptor;\r
+import org.onap.aaf.misc.env.EnvJAXB;\r
+import org.onap.aaf.misc.env.Slot;\r
+import org.onap.aaf.misc.env.StaticSlot;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+\r
+\r
+public class BasicTrans extends AbsTransJAXB {\r
+ \r
+ public BasicTrans(EnvJAXB env) {\r
+ super(env);\r
+ }\r
+\r
+ @Override\r
+ protected TimeTaken newTimeTaken(String name, int flag) {\r
+ /**\r
+ * Note: could have created a different format for Time Taken, but using BasicEnv's instead\r
+ */\r
+ return delegate.start(name, flag);\r
+ }\r
+ \r
+ public Slot slot(String name) {\r
+ return delegate.slot(name);\r
+ }\r
+\r
+ public <T> T get(StaticSlot slot) {\r
+ return delegate.get(slot);\r
+ }\r
+\r
+ public <T> T get(StaticSlot slot, T dflt) {\r
+ return delegate.get(slot,dflt);\r
+ }\r
+\r
+ public String setProperty(String tag, String value) {\r
+ delegate.setProperty(tag, value);\r
+ return value;\r
+ }\r
+\r
+ public String getProperty(String tag) {\r
+ return delegate.getProperty(tag);\r
+ }\r
+\r
+ public String getProperty(String tag, String deflt) {\r
+ return delegate.getProperty(tag, deflt);\r
+ }\r
+\r
+ @Override\r
+ public Decryptor decryptor() {\r
+ return delegate.decryptor();\r
+ }\r
+\r
+ @Override\r
+ public Encryptor encryptor() {\r
+ return delegate.encryptor();\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import org.onap.aaf.misc.env.EnvJAXB;
-import org.onap.aaf.misc.env.TransCreate;
-import org.onap.aaf.misc.env.TransJAXB;
-
-/**
- * EnvFactory
- *
- * @author Jonathan
- *
- */
-public class EnvFactory {
-
- public static final String SCHEMA_DIR = "env-schema_dir";
- public static final String DEFAULT_SCHEMA_DIR = "src/main/xsd";
- static BasicEnv singleton;
-
- static {
- singleton = new BasicEnv();
- }
- public static BasicEnv singleton() {
- return singleton;
- }
-
- public static void setSingleton(BasicEnv be) {
- singleton = be;
- }
-
- public static TransJAXB newTrans() {
- return new BasicTrans(singleton);
- }
-
- public static TransJAXB newTrans(EnvJAXB env) {
- return new BasicTrans(env);
- }
-
- public static TransCreate<TransJAXB> transCreator() {
- return new TransCreate<TransJAXB>() {
- // @Override
- public BasicTrans newTrans() {
- return singleton.newTrans();
- }
- };
- }
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import org.onap.aaf.misc.env.EnvJAXB;\r
+import org.onap.aaf.misc.env.TransCreate;\r
+import org.onap.aaf.misc.env.TransJAXB;\r
+\r
+/**\r
+ * EnvFactory\r
+ * \r
+ * @author Jonathan\r
+ * \r
+ */\r
+public class EnvFactory {\r
+\r
+ public static final String SCHEMA_DIR = "env-schema_dir";\r
+ public static final String DEFAULT_SCHEMA_DIR = "src/main/xsd";\r
+ static BasicEnv singleton;\r
+\r
+ static {\r
+ singleton = new BasicEnv();\r
+ }\r
+ public static BasicEnv singleton() {\r
+ return singleton;\r
+ }\r
+ \r
+ public static void setSingleton(BasicEnv be) {\r
+ singleton = be;\r
+ }\r
+ \r
+ public static TransJAXB newTrans() {\r
+ return new BasicTrans(singleton);\r
+ }\r
+\r
+ public static TransJAXB newTrans(EnvJAXB env) {\r
+ return new BasicTrans(env);\r
+ }\r
+ \r
+ public static TransCreate<TransJAXB> transCreator() {\r
+ return new TransCreate<TransJAXB>() {\r
+ // @Override\r
+ public BasicTrans newTrans() {\r
+ return singleton.newTrans();\r
+ }\r
+ };\r
+ }\r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.onap.aaf.misc.env.LogTarget;
-
-/**
- * This LogTarget Implementation is included mostly because the JavaUtil based logging is included in the
- * JDK. This makes the default implementation independent of any external Jars.
- *
- * Log4j is often considered more Enterprise capable. See Log4JLogTarget for that implementation
- *
- * @author Jonathan
- *
- */
-public class JavaUtilLogTarget implements LogTarget {
- private Level level;
- private Logger log;
-
- public JavaUtilLogTarget(Logger logger, Level theLevel) {
- log = logger;
- level = theLevel;
- }
-
- public boolean isLoggable() {
- return log.isLoggable(level);
- }
-
- public void log(Object ... msgs) {
- if(log.isLoggable(level)) {
- StringBuilder sb = new StringBuilder();
- String msg;
- for(int i=0;i<msgs.length;++i) {
- msg = msgs[i].toString();
- if(msg!=null && msg.length()>0) {
- int sbl = sb.length();
- if(sbl>0) {
- char last = sb.charAt(sbl-1);
- if(" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' ');
- }
- sb.append(msg);
- }
- }
- log.log(level, sb.toString());
- }
- }
-
- public void log(Throwable e, Object ... msgs) {
- String str = e.getLocalizedMessage();
- if(str==null) {
- str = e.getMessage();
- }
- if(str==null) {
- str = e.getClass().getName();
- }
- log.log(level,str,msgs);
- }
-
- /* (non-Javadoc)
- * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[])
- */
- @Override
- public void printf(String fmt, Object ... vars) {
- if(log.isLoggable(level)) {
- log.log(level,String.format(fmt,vars));
- }
- }
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import java.util.logging.Level;\r
+import java.util.logging.Logger;\r
+\r
+import org.onap.aaf.misc.env.LogTarget;\r
+\r
+/**\r
+ * This LogTarget Implementation is included mostly because the JavaUtil based logging is included in the\r
+ * JDK. This makes the default implementation independent of any external Jars.\r
+ * \r
+ * Log4j is often considered more Enterprise capable. See Log4JLogTarget for that implementation\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public class JavaUtilLogTarget implements LogTarget {\r
+ private Level level;\r
+ private Logger log;\r
+\r
+ public JavaUtilLogTarget(Logger logger, Level theLevel) {\r
+ log = logger;\r
+ level = theLevel;\r
+ }\r
+\r
+ public boolean isLoggable() {\r
+ return log.isLoggable(level);\r
+ }\r
+\r
+ public void log(Object ... msgs) {\r
+ if(log.isLoggable(level)) {\r
+ StringBuilder sb = new StringBuilder();\r
+ String msg;\r
+ for(int i=0;i<msgs.length;++i) {\r
+ msg = msgs[i].toString();\r
+ if(msg!=null && msg.length()>0) {\r
+ int sbl = sb.length();\r
+ if(sbl>0) {\r
+ char last = sb.charAt(sbl-1);\r
+ if(" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' ');\r
+ }\r
+ sb.append(msg);\r
+ }\r
+ }\r
+ log.log(level, sb.toString());\r
+ }\r
+ }\r
+\r
+ public void log(Throwable e, Object ... msgs) {\r
+ String str = e.getLocalizedMessage();\r
+ if(str==null) {\r
+ str = e.getMessage();\r
+ }\r
+ if(str==null) {\r
+ str = e.getClass().getName();\r
+ }\r
+ log.log(level,str,msgs);\r
+ }\r
+\r
+ /* (non-Javadoc)\r
+ * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[])\r
+ */\r
+ @Override\r
+ public void printf(String fmt, Object ... vars) {\r
+ if(log.isLoggable(level)) {\r
+ log.log(level,String.format(fmt,vars));\r
+ }\r
+ }\r
+} \r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.impl;
-
-import java.io.PrintWriter;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.LogTarget;
-import org.onap.aaf.misc.env.util.StringBuilderWriter;
-
-/**
- * Many services have chosen to use Log4J for their lower level Logging Implementation. This LogTarget will allow
- * any of the messages sent to be set to the appropriate Log4J level.
- *
- * @author Jonathan
- *
- */
-public class Log4JLogTarget implements LogTarget {
- private Level level;
- private Logger log;
-
- public Log4JLogTarget(String loggerName, Level level) throws APIException {
- this.level = level;
- if (loggerName != null && loggerName.length() > 0) {
- log = Logger.getLogger(loggerName);
- } else {
- log = Logger.getRootLogger();
- }
- }
-
- // @Override
- public boolean isLoggable() {
- return log.isEnabledFor(level);
- }
-
- // @Override
- public void log(Object... msgs) {
- log(null, msgs);
- }
-
- // @Override
- public void log(Throwable e, Object... msgs) {
- if (log.isEnabledFor(level)) {
- StringBuilder sb = new StringBuilder();
-
- String msg;
- if (e != null) {
- e.printStackTrace(new PrintWriter(new StringBuilderWriter(sb)));
- }
- for (int i = 0; i < msgs.length; ++i) {
- if(msgs[i]!=null) {
- msg = msgs[i].toString();
- if (msg != null && msg.length() > 0) {
- int sbl = sb.length();
- if (sbl > 0) {
- char last = sb.charAt(sbl - 1);
- if (" (.".indexOf(last) < 0
- && "().".indexOf(msg.charAt(0)) < 0)
- sb.append(' ');
- }
- sb.append(msg);
- }
- }
- }
- log.log(level, sb.toString());
- }
- }
-
- /* (non-Javadoc)
- * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[])
- */
- @Override
- public void printf(String fmt, Object ... vars) {
- if(log.isEnabledFor(level)) {
- log.log(level,String.format(fmt,vars));
- }
- }
-
- public static void setLog4JEnv(String loggerName, BasicEnv env) throws APIException {
- env.fatal = new Log4JLogTarget(loggerName,Level.FATAL);
- env.error = new Log4JLogTarget(loggerName,Level.ERROR);
- env.warn = env.audit = env.init = new Log4JLogTarget(loggerName,Level.WARN);
- env.info = new Log4JLogTarget(loggerName,Level.INFO);
- env.debug = new Log4JLogTarget(loggerName,Level.DEBUG);
- env.trace = new Log4JLogTarget(loggerName,Level.TRACE);
- }
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import java.io.PrintWriter;\r
+\r
+import org.apache.log4j.Level;\r
+import org.apache.log4j.Logger;\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+import org.onap.aaf.misc.env.util.StringBuilderWriter;\r
+\r
+/**\r
+ * Many services have chosen to use Log4J for their lower level Logging Implementation. This LogTarget will allow\r
+ * any of the messages sent to be set to the appropriate Log4J level.\r
+ * \r
+ * @author Jonathan \r
+ *\r
+ */\r
+public class Log4JLogTarget implements LogTarget {\r
+ private Level level;\r
+ private Logger log;\r
+\r
+ public Log4JLogTarget(String loggerName, Level level) throws APIException {\r
+ this.level = level;\r
+ if (loggerName != null && loggerName.length() > 0) {\r
+ log = Logger.getLogger(loggerName);\r
+ } else {\r
+ log = Logger.getRootLogger();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public boolean isLoggable() {\r
+ return log.isEnabledFor(level);\r
+ }\r
+\r
+ // @Override\r
+ public void log(Object... msgs) {\r
+ log(null, msgs);\r
+ }\r
+\r
+ // @Override\r
+ public void log(Throwable e, Object... msgs) {\r
+ if (log.isEnabledFor(level)) {\r
+ StringBuilder sb = new StringBuilder();\r
+ \r
+ String msg;\r
+ if (e != null) {\r
+ e.printStackTrace(new PrintWriter(new StringBuilderWriter(sb)));\r
+ }\r
+ for (int i = 0; i < msgs.length; ++i) {\r
+ if(msgs[i]!=null) {\r
+ msg = msgs[i].toString();\r
+ if (msg != null && msg.length() > 0) {\r
+ int sbl = sb.length();\r
+ if (sbl > 0) {\r
+ char last = sb.charAt(sbl - 1);\r
+ if (" (.".indexOf(last) < 0\r
+ && "().".indexOf(msg.charAt(0)) < 0)\r
+ sb.append(' ');\r
+ }\r
+ sb.append(msg);\r
+ }\r
+ }\r
+ }\r
+ log.log(level, sb.toString());\r
+ }\r
+ }\r
+\r
+ /* (non-Javadoc)\r
+ * @see com.att.inno.env.LogTarget#printf(java.lang.String, java.lang.String[])\r
+ */\r
+ @Override\r
+ public void printf(String fmt, Object ... vars) {\r
+ if(log.isEnabledFor(level)) {\r
+ log.log(level,String.format(fmt,vars));\r
+ }\r
+ }\r
+\r
+ public static void setLog4JEnv(String loggerName, BasicEnv env) throws APIException {\r
+ env.fatal = new Log4JLogTarget(loggerName,Level.FATAL);\r
+ env.error = new Log4JLogTarget(loggerName,Level.ERROR);\r
+ env.warn = env.audit = env.init = new Log4JLogTarget(loggerName,Level.WARN);\r
+ env.info = new Log4JLogTarget(loggerName,Level.INFO);\r
+ env.debug = new Log4JLogTarget(loggerName,Level.DEBUG);\r
+ env.trace = new Log4JLogTarget(loggerName,Level.TRACE);\r
+ }\r
+ \r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- *
- */
-package org.onap.aaf.misc.env.impl;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.LifeCycle;
-
-
-
-/**
- * <h1>NullLifeCycle</h1>
- *
- * This is a convenience class for those Objects which should
- * implement LifeCycle, but don't have anything to do in any of the
- * LifeCycle methods defined. Extending
- * NullLifeCycle reduces the required methods for the class by 5.
- * Any one or two of them can be overloaded.<p>
- *
- * If more are overloaded, it is
- * recommended just to implement LifeCycle.
- * <p>
- *
- * This only works, though, if the Object doesn't need to extend something
- * else, due to Java's Single Extension policy. In other cases, just
- * implement LifeCycle, and leave them empty.
- *
- * @author Jonathan
- *
- */
-public class NullLifeCycle implements LifeCycle {
- public void servicePrestart(Env env) throws APIException {}
- public void threadPrestart(Env env) throws APIException {}
- public void refresh(Env env) throws APIException {}
- public void threadDestroy(Env env) throws APIException {}
- public void serviceDestroy(Env env) throws APIException {}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * \r
+ */\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.LifeCycle;\r
+\r
+\r
+\r
+/**\r
+ * <h1>NullLifeCycle</h1>\r
+ * \r
+ * This is a convenience class for those Objects which should\r
+ * implement LifeCycle, but don't have anything to do in any of the \r
+ * LifeCycle methods defined. Extending\r
+ * NullLifeCycle reduces the required methods for the class by 5. \r
+ * Any one or two of them can be overloaded.<p>\r
+ * \r
+ * If more are overloaded, it is\r
+ * recommended just to implement LifeCycle.\r
+ * <p>\r
+ * \r
+ * This only works, though, if the Object doesn't need to extend something\r
+ * else, due to Java's Single Extension policy. In other cases, just\r
+ * implement LifeCycle, and leave them empty.\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public class NullLifeCycle implements LifeCycle {\r
+ public void servicePrestart(Env env) throws APIException {}\r
+ public void threadPrestart(Env env) throws APIException {}\r
+ public void refresh(Env env) throws APIException {}\r
+ public void threadDestroy(Env env) throws APIException {}\r
+ public void serviceDestroy(Env env) throws APIException {}\r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.jaxb;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.namespace.QName;
-import javax.xml.validation.Schema;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.BaseDataFactory;
-import org.onap.aaf.misc.env.Data;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.EnvJAXB;
-import org.onap.aaf.misc.env.TimeTaken;
-import org.onap.aaf.misc.env.old.IOObjectifier;
-import org.onap.aaf.misc.env.old.IOStringifier;
-import org.onap.aaf.misc.env.old.OldDataFactory;
-
-public class JAXBDF<T> extends BaseDataFactory implements OldDataFactory<T>,IOObjectifier<T>, IOStringifier<T> {
- // Package on purpose
- EnvJAXB primaryEnv;
- JAXBumar jumar;
- JAXBmar jmar;
-
- public JAXBDF(EnvJAXB env, Class<?> ... classes) throws APIException {
- try {
- primaryEnv = env;
- jumar = new JAXBumar(classes);
- jmar = new JAXBmar(classes) ;
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public JAXBDF(EnvJAXB env, Schema schema, Class<?> ... classes) throws APIException {
- try {
- primaryEnv = env;
- jumar = new JAXBumar(schema, classes);
- jmar = new JAXBmar(classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public JAXBDF(EnvJAXB env, QName qname, Class<?> ... classes) throws APIException {
- try {
- primaryEnv = env;
- jumar = new JAXBumar(classes);
- jmar = new JAXBmar(qname, classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public JAXBDF(EnvJAXB env, Schema schema, QName qname, Class<?> ... classes) throws APIException {
- try {
- primaryEnv = env;
- jumar = new JAXBumar(schema, classes);
- jmar = new JAXBmar(qname, classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public T newInstance() throws APIException {
- try {
- return jumar.newInstance();
- } catch (Exception e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public IOStringifier<T> pretty(boolean pretty) {
- jmar.pretty(pretty);
- return this;
- }
-
- // @Override
- public IOStringifier<T> asFragment(boolean fragment) {
- jmar.asFragment(fragment);
- return this;
- }
-
- // @Override
- public void servicePrestart(Env env) throws APIException {
- }
-
- // @Override
- public void threadPrestart(Env env) throws APIException {
- }
-
- // @Override
- public void refresh(Env env) throws APIException {
- }
-
- // @Override
- public void threadDestroy(Env env) throws APIException {
- }
-
- // @Override
- public void serviceDestroy(Env env) throws APIException {
- }
-
- @SuppressWarnings("unchecked")
- // @Override
- public Data<T> newData() {
- return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),"",(Class<T>)jmar.getMarshalClass());
- }
-
- @SuppressWarnings("unchecked")
- // @Override
- public Data<T> newData(Env env) {
- return new JAXBData<T>(env, this,new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),"",(Class<T>)jmar.getMarshalClass());
- }
-
- // @Override
- public Data<T> newData(T type) {
- return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar), type);
- }
-
- // @Override
- public Data<T> newDataFromStream(Env env, InputStream input) throws APIException {
- //TODO Write an unvalidated String using STAX checking for end of Doc?
- // perhaps key evaluation as well.
- try {
- T t = jumar.unmarshal(env.debug(), input);
- return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),t);
- } catch(JAXBException e) {
- throw new APIException(e);
- }
- }
-
- @SuppressWarnings("unchecked")
- // @Override
- public Data<T> newDataFromString(String string) {
- return new JAXBData<T>(primaryEnv, this,new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar), string,(Class<T>)jmar.getMarshalClass());
- }
-
- /////////// Old DataFactory Interface
- // @Override
- public String stringify(T type) throws APIException {
- try {
- StringWriter sw = new StringWriter();
- jmar.marshal(primaryEnv.debug(), type, sw);
- return sw.toString();
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public void stringify(T type, Writer writer) throws APIException {
- try {
- jmar.marshal(primaryEnv.debug(), type, writer);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public void stringify(T type, OutputStream os) throws APIException {
- try {
- jmar.marshal(primaryEnv.debug(), type, os);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- /////////// New DataFactory Interface
- // @Override
- public String stringify(Env env, T input, boolean ... options) throws APIException {
- try {
- StringWriter sw = new StringWriter();
- TimeTaken tt = env.start("JAXB Stringify", Env.XML);
- try {
- jmar.marshal(env.debug(), input, sw, options);
- } finally {
- tt.done();
- }
- String str = sw.toString();
- tt.size(str.getBytes().length);
- return str;
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException {
- TimeTaken tt = env.start("JAXB Stringify", Env.XML);
- try {
- jmar.marshal(env.debug(), input, writer, options);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException {
- TimeTaken tt = env.start("JAXB Stringify", Env.XML);
- try {
- jmar.marshal(env.debug(), input, os, options);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public T objectify(Env env, Reader rdr) throws APIException {
- TimeTaken tt = env.start("JAXB Objectify", Env.XML);
- try {
- return jumar.unmarshal(env.debug(), rdr);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public T objectify(Reader rdr) throws APIException {
- try {
- return jumar.unmarshal(primaryEnv.debug(), rdr);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public T objectify(Env env, InputStream is) throws APIException {
- TimeTaken tt = env.start("JAXB Objectify", Env.XML);
- try {
- return jumar.unmarshal(env.debug(), is);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public T objectify(InputStream is) throws APIException {
- try {
- return jumar.unmarshal(primaryEnv.debug(), is);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // @Override
- public T objectify(Env env, String input) throws APIException {
- TimeTaken tt = env.start("JAXB Objectify", Env.XML);
- tt.size(input.getBytes().length);
- try {
- return jumar.unmarshal(env.debug(), input);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public T objectify(String text) throws APIException {
- try {
- return jumar.unmarshal(primaryEnv.debug(), text);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- @SuppressWarnings("unchecked")
- // @Override
- public Class<T> getTypeClass() {
- return (Class<T>)jmar.getMarshalClass();
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.jaxb;\r
+\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.io.Reader;\r
+import java.io.StringWriter;\r
+import java.io.Writer;\r
+\r
+import javax.xml.bind.JAXBException;\r
+import javax.xml.namespace.QName;\r
+import javax.xml.validation.Schema;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.BaseDataFactory;\r
+import org.onap.aaf.misc.env.Data;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.EnvJAXB;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+import org.onap.aaf.misc.env.old.IOObjectifier;\r
+import org.onap.aaf.misc.env.old.IOStringifier;\r
+import org.onap.aaf.misc.env.old.OldDataFactory;\r
+\r
+public class JAXBDF<T> extends BaseDataFactory implements OldDataFactory<T>,IOObjectifier<T>, IOStringifier<T> {\r
+ // Package on purpose\r
+ EnvJAXB primaryEnv;\r
+ JAXBumar jumar;\r
+ JAXBmar jmar;\r
+\r
+ public JAXBDF(EnvJAXB env, Class<?> ... classes) throws APIException {\r
+ try {\r
+ primaryEnv = env;\r
+ jumar = new JAXBumar(classes);\r
+ jmar = new JAXBmar(classes) ;\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ public JAXBDF(EnvJAXB env, Schema schema, Class<?> ... classes) throws APIException {\r
+ try {\r
+ primaryEnv = env;\r
+ jumar = new JAXBumar(schema, classes);\r
+ jmar = new JAXBmar(classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ public JAXBDF(EnvJAXB env, QName qname, Class<?> ... classes) throws APIException {\r
+ try {\r
+ primaryEnv = env;\r
+ jumar = new JAXBumar(classes);\r
+ jmar = new JAXBmar(qname, classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ public JAXBDF(EnvJAXB env, Schema schema, QName qname, Class<?> ... classes) throws APIException {\r
+ try {\r
+ primaryEnv = env;\r
+ jumar = new JAXBumar(schema, classes);\r
+ jmar = new JAXBmar(qname, classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ // @Override\r
+ public T newInstance() throws APIException {\r
+ try {\r
+ return jumar.newInstance();\r
+ } catch (Exception e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public IOStringifier<T> pretty(boolean pretty) {\r
+ jmar.pretty(pretty);\r
+ return this;\r
+ }\r
+\r
+ // @Override\r
+ public IOStringifier<T> asFragment(boolean fragment) {\r
+ jmar.asFragment(fragment);\r
+ return this;\r
+ }\r
+\r
+ // @Override\r
+ public void servicePrestart(Env env) throws APIException {\r
+ }\r
+\r
+ // @Override\r
+ public void threadPrestart(Env env) throws APIException {\r
+ }\r
+\r
+ // @Override\r
+ public void refresh(Env env) throws APIException {\r
+ }\r
+\r
+ // @Override\r
+ public void threadDestroy(Env env) throws APIException {\r
+ }\r
+\r
+ // @Override\r
+ public void serviceDestroy(Env env) throws APIException {\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public Data<T> newData() {\r
+ return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),"",(Class<T>)jmar.getMarshalClass());\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public Data<T> newData(Env env) {\r
+ return new JAXBData<T>(env, this,new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),"",(Class<T>)jmar.getMarshalClass());\r
+ }\r
+\r
+ // @Override\r
+ public Data<T> newData(T type) {\r
+ return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar), type);\r
+ }\r
+\r
+ // @Override\r
+ public Data<T> newDataFromStream(Env env, InputStream input) throws APIException {\r
+ //TODO Write an unvalidated String using STAX checking for end of Doc?\r
+ // perhaps key evaluation as well.\r
+ try {\r
+ T t = jumar.unmarshal(env.debug(), input);\r
+ return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),t);\r
+ } catch(JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public Data<T> newDataFromString(String string) {\r
+ return new JAXBData<T>(primaryEnv, this,new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar), string,(Class<T>)jmar.getMarshalClass());\r
+ }\r
+\r
+ /////////// Old DataFactory Interface \r
+ // @Override\r
+ public String stringify(T type) throws APIException {\r
+ try {\r
+ StringWriter sw = new StringWriter();\r
+ jmar.marshal(primaryEnv.debug(), type, sw);\r
+ return sw.toString();\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } \r
+ }\r
+\r
+ // @Override\r
+ public void stringify(T type, Writer writer) throws APIException {\r
+ try {\r
+ jmar.marshal(primaryEnv.debug(), type, writer);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } \r
+ }\r
+\r
+ // @Override\r
+ public void stringify(T type, OutputStream os) throws APIException {\r
+ try {\r
+ jmar.marshal(primaryEnv.debug(), type, os);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } \r
+ }\r
+\r
+ /////////// New DataFactory Interface \r
+ // @Override\r
+ public String stringify(Env env, T input, boolean ... options) throws APIException {\r
+ try {\r
+ StringWriter sw = new StringWriter();\r
+ TimeTaken tt = env.start("JAXB Stringify", Env.XML);\r
+ try {\r
+ jmar.marshal(env.debug(), input, sw, options);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ String str = sw.toString();\r
+ tt.size(str.getBytes().length);\r
+ return str;\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Stringify", Env.XML);\r
+ try {\r
+ jmar.marshal(env.debug(), input, writer, options);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Stringify", Env.XML);\r
+ try {\r
+ jmar.marshal(env.debug(), input, os, options);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public T objectify(Env env, Reader rdr) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Objectify", Env.XML);\r
+ try {\r
+ return jumar.unmarshal(env.debug(), rdr);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public T objectify(Reader rdr) throws APIException {\r
+ try {\r
+ return jumar.unmarshal(primaryEnv.debug(), rdr);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } \r
+ }\r
+\r
+ // @Override\r
+ public T objectify(Env env, InputStream is) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Objectify", Env.XML);\r
+ try {\r
+ return jumar.unmarshal(env.debug(), is);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public T objectify(InputStream is) throws APIException {\r
+ try {\r
+ return jumar.unmarshal(primaryEnv.debug(), is);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } \r
+ }\r
+\r
+ // @Override\r
+ public T objectify(Env env, String input) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Objectify", Env.XML);\r
+ tt.size(input.getBytes().length);\r
+ try {\r
+ return jumar.unmarshal(env.debug(), input);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public T objectify(String text) throws APIException {\r
+ try {\r
+ return jumar.unmarshal(primaryEnv.debug(), text);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } \r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public Class<T> getTypeClass() {\r
+ return (Class<T>)jmar.getMarshalClass();\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.jaxb;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-
-import javax.xml.bind.JAXBException;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Data;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.EnvJAXB;
-import org.onap.aaf.misc.env.old.IOStringifier;
-import org.onap.aaf.misc.env.old.Objectifier;
-import org.onap.aaf.misc.env.old.Stringifier;
-/**
- * <H1>Data</H1>
- * <i>Data</i> facilitates lazy marshaling of data with a pre-determined
- * marshaling mechanism.<p>
- *
- * It stores either Object (defined by Generic {@literal <T>}) or String.<p>
- *
- * On asking for Object of type {@literal <T>}, it will respond with the object
- * if it exists, or unmarshal the string and pass the result back.<p>
- *
- * On asking for String, it will respond with the String
- * if it exists, or marshal the String and pass the result back.<p>
- *
- * @author Jonathan
- *
- * @param <T>
- */
-public final class JAXBData<T> implements Data<T>{
- private Stringifier<T> stringifier;
- private Objectifier<T> objectifier;
- private String dataAsString;
- private T dataAsObject;
- private Class<T> tclass;
- private JAXBDF<T> df;
- private Env creatingEnv;
- private boolean options[] = new boolean[] {false, false};
-
- /**
- * Construct a Data Object with an appropriate Stringifier, Objectifier and Class to support
- *
- * @param env
- * @param strfr
- * @param objfr
- * @param text
- * @param typeClass
- */
- JAXBData(Env env, JAXBDF<T> df, Stringifier<T> strfr, Objectifier<T> objfr, String text, Class<T> typeClass) {
- dataAsString = text;
- dataAsObject = null;
- stringifier = strfr;
- objectifier = objfr;
- tclass = typeClass;
- creatingEnv = env;
- this.df = df;
- }
-
-
- /**
- * Construct a Data Object with an appropriate Stringifier, Objectifier and Object (which will
- * yield it's class)
- *
- * @param env
- * @param strfr
- * @param objfr
- * @param object
- */
- @SuppressWarnings("unchecked")
- JAXBData(Env env, JAXBDF<T> df, Stringifier<T> strfr, Objectifier<T> objfr, T object) {
- dataAsString = null;
- dataAsObject = object;
- stringifier = strfr;
- objectifier = objfr;
- tclass = (Class<T>) object.getClass();
- creatingEnv = env;
- this.df = df;
- }
-
- /**
- * Respond with the String if it exists, or marshal the String and pass the result back.<p>
- *
- * Explicitly use a specific Env for logging purposes
- *
- * @param env
- * @return String
- * @throws APIException
- */
- public String asString(EnvJAXB env) throws APIException {
- if(dataAsString!=null) {
- return dataAsString;
- } else {
- return dataAsString = stringifier.stringify(env, dataAsObject);
- }
- }
-
- /**
- * Respond with the String if it exists, or marshal the String and pass the result back.
- *
- * However, use the Env the Data Object was created with.
- *
- * @return String
- * @throws APIException
- */
- // @Override
- public String asString() throws APIException {
- if(dataAsString!=null) {
- return dataAsString;
- } else {
- return dataAsString = stringifier.stringify(creatingEnv, dataAsObject,options);
- }
- }
-
- public Data<T> to(OutputStream os) throws APIException, IOException {
- if(dataAsString!=null) {
- os.write(dataAsString.getBytes());
- } else if (stringifier instanceof IOStringifier){
- ((IOStringifier<T>)stringifier).stringify(creatingEnv, dataAsObject, os, options);
- } else {
- dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options);
- os.write(dataAsString.getBytes());
- }
- return this;
- }
-
-
- // @Override
- public JAXBData<T> to(Writer writer) throws APIException, IOException {
- if(dataAsString!=null) {
- writer.write(dataAsString);
- } else if (stringifier instanceof IOStringifier){
- ((IOStringifier<T>)stringifier).stringify(creatingEnv, dataAsObject, writer, options);
- } else {
- dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options);
- writer.write(dataAsString);
- }
- return this;
- }
-
-
- public InputStream getInputStream() throws APIException {
- if(dataAsString==null) {
- dataAsString = stringifier.stringify(creatingEnv,dataAsObject,options);
- }
- return new ByteArrayInputStream(dataAsString.getBytes());
- }
-
- /**
- * Respond with the Object of type {@literal <T>} if it exists, or unmarshal from String
- * and pass the result back.<p>
- *
- * Explicitly use a specific Env for logging purposes
- *
- * @param env
- * @return T
- * @throws APIException
- */
-
- public T asObject(EnvJAXB env) throws APIException {
- if(dataAsObject !=null) {
- return dataAsObject;
- } else {
- // Some Java compilers need two statements here
- dataAsObject = objectifier.objectify(env, dataAsString);
- return dataAsObject;
- }
- }
-
- /**
- * Respond with the Object of type {@literal <T>} if it exists, or unmarshal from String
- * and pass the result back.<p>
- *
- * However, use the Env the Data Object was created with.
- *
- * @return T
- * @throws APIException
- */
- // @Override
- public T asObject() throws APIException {
- if(dataAsObject !=null) {
- return dataAsObject;
- } else {
- // Some Java compilers need two statements here
- dataAsObject = objectifier.objectify(creatingEnv, dataAsString);
- return dataAsObject;
- }
- }
-
-
- /**
- * Return the Class Type supported by this DataObject
- *
- * @return {@literal Class<T>}
- */
- // @Override
- public Class<T> getTypeClass() {
- return tclass;
- }
-
-
- /**
- * For Debugging Convenience, we marshal to String if possible.
- *
- * Behavior is essentially the same as asString(), except asString() throws
- * an APIException. <p>
- * Since toString() must not throw exceptions, the function just catches and prints an
- * error, which is probably not the behavior desired.<p>
- *
- * Therefore, use "asString()" where possible in actual Transactional code.
- *
- * @see java.lang.Object#toString()
- */
- // @Override
- public String toString() {
- if(dataAsString!=null) {
- return dataAsString;
- } else {
- try {
- return dataAsString = stringifier.stringify(creatingEnv, dataAsObject);
- } catch (APIException e) {
- return "ERROR - Can't Stringify from Object " + e.getLocalizedMessage();
- }
- }
- }
-
- public Data<T> load(T t) throws APIException {
- dataAsObject = t;
- dataAsString = null;
- return this;
- }
-
-
- public Data<T> load(String str) throws APIException {
- dataAsObject = null;
- dataAsString = str;
- return this;
- }
-
-
- public Data<T> load(InputStream is) throws APIException {
- try {
- dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),is);
- dataAsString = null;
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- return this;
- }
-
-
- public Data<T> load(Reader rdr) throws APIException {
- try {
- dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),rdr);
- dataAsString = null;
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- return this;
- }
-
-
- // @Override
- public void direct(InputStream input, OutputStream output) throws APIException, IOException {
- byte b[] = new byte[128];
- int count;
- do {
- count = input.read(b);
- if(count>0)output.write(b, 0, count);
- } while(count>=0);
- }
-
-
- // @Override
- public Data<T> out(TYPE type) {
- // it's going to be XML regardless...
- return this;
- }
-
-
- // @Override
- public Data<T> in(TYPE type) {
- // Not Supported... will still be XML
- return this;
- }
-
-
- // @Override
- public Data<T> option(int option) {
- options[0] = (option&Data.PRETTY)==Data.PRETTY;
- options[1] = (option&Data.FRAGMENT)==Data.FRAGMENT;
- return this;
- }
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.jaxb;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.io.Reader;\r
+import java.io.Writer;\r
+\r
+import javax.xml.bind.JAXBException;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Data;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.EnvJAXB;\r
+import org.onap.aaf.misc.env.old.IOStringifier;\r
+import org.onap.aaf.misc.env.old.Objectifier;\r
+import org.onap.aaf.misc.env.old.Stringifier;\r
+/**\r
+ * <H1>Data</H1>\r
+ * <i>Data</i> facilitates lazy marshaling of data with a pre-determined\r
+ * marshaling mechanism.<p>\r
+ * \r
+ * It stores either Object (defined by Generic {@literal <T>}) or String.<p> \r
+ * \r
+ * On asking for Object of type {@literal <T>}, it will respond with the object\r
+ * if it exists, or unmarshal the string and pass the result back.<p>\r
+ * \r
+ * On asking for String, it will respond with the String\r
+ * if it exists, or marshal the String and pass the result back.<p>\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ * @param <T>\r
+ */\r
+public final class JAXBData<T> implements Data<T>{\r
+ private Stringifier<T> stringifier;\r
+ private Objectifier<T> objectifier;\r
+ private String dataAsString;\r
+ private T dataAsObject;\r
+ private Class<T> tclass;\r
+ private JAXBDF<T> df;\r
+ private Env creatingEnv;\r
+ private boolean options[] = new boolean[] {false, false};\r
+ \r
+ /**\r
+ * Construct a Data Object with an appropriate Stringifier, Objectifier and Class to support\r
+ * \r
+ * @param env\r
+ * @param strfr\r
+ * @param objfr\r
+ * @param text\r
+ * @param typeClass\r
+ */\r
+ JAXBData(Env env, JAXBDF<T> df, Stringifier<T> strfr, Objectifier<T> objfr, String text, Class<T> typeClass) {\r
+ dataAsString = text;\r
+ dataAsObject = null;\r
+ stringifier = strfr;\r
+ objectifier = objfr;\r
+ tclass = typeClass;\r
+ creatingEnv = env;\r
+ this.df = df;\r
+ }\r
+ \r
+ \r
+ /**\r
+ * Construct a Data Object with an appropriate Stringifier, Objectifier and Object (which will\r
+ * yield it's class)\r
+ * \r
+ * @param env\r
+ * @param strfr\r
+ * @param objfr\r
+ * @param object\r
+ */\r
+ @SuppressWarnings("unchecked")\r
+ JAXBData(Env env, JAXBDF<T> df, Stringifier<T> strfr, Objectifier<T> objfr, T object) {\r
+ dataAsString = null;\r
+ dataAsObject = object;\r
+ stringifier = strfr;\r
+ objectifier = objfr;\r
+ tclass = (Class<T>) object.getClass();\r
+ creatingEnv = env;\r
+ this.df = df;\r
+ }\r
+\r
+ /**\r
+ * Respond with the String if it exists, or marshal the String and pass the result back.<p>\r
+ * \r
+ * Explicitly use a specific Env for logging purposes\r
+ * \r
+ * @param env\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public String asString(EnvJAXB env) throws APIException {\r
+ if(dataAsString!=null) {\r
+ return dataAsString;\r
+ } else {\r
+ return dataAsString = stringifier.stringify(env, dataAsObject);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Respond with the String if it exists, or marshal the String and pass the result back.\r
+ * \r
+ * However, use the Env the Data Object was created with.\r
+ * \r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ // @Override\r
+ public String asString() throws APIException {\r
+ if(dataAsString!=null) {\r
+ return dataAsString;\r
+ } else {\r
+ return dataAsString = stringifier.stringify(creatingEnv, dataAsObject,options);\r
+ }\r
+ }\r
+ \r
+ public Data<T> to(OutputStream os) throws APIException, IOException {\r
+ if(dataAsString!=null) {\r
+ os.write(dataAsString.getBytes());\r
+ } else if (stringifier instanceof IOStringifier){\r
+ ((IOStringifier<T>)stringifier).stringify(creatingEnv, dataAsObject, os, options);\r
+ } else {\r
+ dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options);\r
+ os.write(dataAsString.getBytes());\r
+ }\r
+ return this;\r
+ }\r
+\r
+\r
+ // @Override\r
+ public JAXBData<T> to(Writer writer) throws APIException, IOException {\r
+ if(dataAsString!=null) {\r
+ writer.write(dataAsString);\r
+ } else if (stringifier instanceof IOStringifier){\r
+ ((IOStringifier<T>)stringifier).stringify(creatingEnv, dataAsObject, writer, options);\r
+ } else {\r
+ dataAsString = stringifier.stringify(creatingEnv, dataAsObject, options);\r
+ writer.write(dataAsString);\r
+ }\r
+ return this;\r
+ }\r
+\r
+\r
+ public InputStream getInputStream() throws APIException {\r
+ if(dataAsString==null) {\r
+ dataAsString = stringifier.stringify(creatingEnv,dataAsObject,options);\r
+ }\r
+ return new ByteArrayInputStream(dataAsString.getBytes());\r
+ }\r
+ \r
+ /**\r
+ * Respond with the Object of type {@literal <T>} if it exists, or unmarshal from String \r
+ * and pass the result back.<p>\r
+ * \r
+ * Explicitly use a specific Env for logging purposes\r
+ * \r
+ * @param env\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+\r
+ public T asObject(EnvJAXB env) throws APIException {\r
+ if(dataAsObject !=null) {\r
+ return dataAsObject;\r
+ } else {\r
+ // Some Java compilers need two statements here\r
+ dataAsObject = objectifier.objectify(env, dataAsString);\r
+ return dataAsObject;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Respond with the Object of type {@literal <T>} if it exists, or unmarshal from String \r
+ * and pass the result back.<p>\r
+ *\r
+ * However, use the Env the Data Object was created with.\r
+ * \r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ // @Override\r
+ public T asObject() throws APIException {\r
+ if(dataAsObject !=null) {\r
+ return dataAsObject;\r
+ } else {\r
+ // Some Java compilers need two statements here\r
+ dataAsObject = objectifier.objectify(creatingEnv, dataAsString);\r
+ return dataAsObject;\r
+ }\r
+ }\r
+ \r
+\r
+ /**\r
+ * Return the Class Type supported by this DataObject\r
+ * \r
+ * @return {@literal Class<T>}\r
+ */\r
+ // @Override\r
+ public Class<T> getTypeClass() {\r
+ return tclass;\r
+ }\r
+ \r
+ \r
+ /**\r
+ * For Debugging Convenience, we marshal to String if possible.\r
+ * \r
+ * Behavior is essentially the same as asString(), except asString() throws\r
+ * an APIException. <p>\r
+ * Since toString() must not throw exceptions, the function just catches and prints an\r
+ * error, which is probably not the behavior desired.<p>\r
+ * \r
+ * Therefore, use "asString()" where possible in actual Transactional code. \r
+ * \r
+ * @see java.lang.Object#toString()\r
+ */\r
+ // @Override\r
+ public String toString() {\r
+ if(dataAsString!=null) {\r
+ return dataAsString;\r
+ } else {\r
+ try {\r
+ return dataAsString = stringifier.stringify(creatingEnv, dataAsObject);\r
+ } catch (APIException e) {\r
+ return "ERROR - Can't Stringify from Object " + e.getLocalizedMessage();\r
+ }\r
+ }\r
+ }\r
+\r
+ public Data<T> load(T t) throws APIException {\r
+ dataAsObject = t;\r
+ dataAsString = null;\r
+ return this;\r
+ }\r
+\r
+\r
+ public Data<T> load(String str) throws APIException {\r
+ dataAsObject = null;\r
+ dataAsString = str;\r
+ return this;\r
+ }\r
+\r
+\r
+ public Data<T> load(InputStream is) throws APIException {\r
+ try {\r
+ dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),is);\r
+ dataAsString = null;\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ return this;\r
+ }\r
+\r
+\r
+ public Data<T> load(Reader rdr) throws APIException {\r
+ try {\r
+ dataAsObject = df.jumar.unmarshal(creatingEnv.debug(),rdr);\r
+ dataAsString = null;\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ return this;\r
+ }\r
+\r
+\r
+ // @Override\r
+ public void direct(InputStream input, OutputStream output) throws APIException, IOException {\r
+ byte b[] = new byte[128];\r
+ int count;\r
+ do {\r
+ count = input.read(b);\r
+ if(count>0)output.write(b, 0, count);\r
+ } while(count>=0);\r
+ }\r
+\r
+\r
+ // @Override\r
+ public Data<T> out(TYPE type) {\r
+ // it's going to be XML regardless...\r
+ return this;\r
+ }\r
+\r
+\r
+ // @Override\r
+ public Data<T> in(TYPE type) {\r
+ // Not Supported... will still be XML\r
+ return this;\r
+ }\r
+\r
+\r
+ // @Override\r
+ public Data<T> option(int option) {\r
+ options[0] = (option&Data.PRETTY)==Data.PRETTY;\r
+ options[1] = (option&Data.FRAGMENT)==Data.FRAGMENT;\r
+ return this;\r
+ }\r
+ \r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.jaxb;
-
-import java.io.InputStream;
-import java.io.Reader;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.validation.Schema;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.TimeTaken;
-import org.onap.aaf.misc.env.old.IOObjectifier;
-
-/**
- * Allow Extended IO interface usage without muddying up the Stringifier Interface
- */
-public class JAXBObjectifier<T> implements IOObjectifier<T> {
- private JAXBumar jumar;
-
- public JAXBObjectifier(Schema schema, Class<?>... classes) throws APIException {
- try {
- jumar = new JAXBumar(schema, classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public JAXBObjectifier(Class<?>... classes) throws APIException {
- try {
- jumar = new JAXBumar(classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // package on purpose
- JAXBObjectifier(JAXBumar jumar) {
- this.jumar = jumar;
- }
-
- @SuppressWarnings("unchecked")
- // @Override
- public T objectify(Env env, String input) throws APIException {
- TimeTaken tt = env.start("JAXB Unmarshal", Env.XML);
- try {
- tt.size(input.length());
- return (T)jumar.unmarshal(env.debug(), input);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- // @Override
- public T objectify(Env env, Reader rdr) throws APIException {
- //TODO create a Reader that Counts?
- TimeTaken tt = env.start("JAXB Unmarshal", Env.XML);
- try {
- return (T)jumar.unmarshal(env.debug(), rdr);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
-
- @SuppressWarnings("unchecked")
- // @Override
- public T objectify(Env env, InputStream is) throws APIException {
- //TODO create a Reader that Counts?
- TimeTaken tt = env.start("JAXB Unmarshal", Env.XML);
- try {
- return (T)jumar.unmarshal(env.debug(), is);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
-
- public void servicePrestart(Env env) throws APIException {
- }
-
- public void threadPrestart(Env env) throws APIException {
- }
-
- // // @Override
- public void refresh(Env env) throws APIException {
- }
-
- // // @Override
- public void threadDestroy(Env env) throws APIException {
- }
-
- // // @Override
- public void serviceDestroy(Env env) throws APIException {
- }
-
-
- @SuppressWarnings("unchecked")
- public T newInstance() throws APIException {
- try {
- return (T)jumar.newInstance();
- } catch (Exception e) {
- throw new APIException(e);
- }
- }
-
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.jaxb;\r
+\r
+import java.io.InputStream;\r
+import java.io.Reader;\r
+\r
+import javax.xml.bind.JAXBException;\r
+import javax.xml.validation.Schema;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+import org.onap.aaf.misc.env.old.IOObjectifier;\r
+\r
+/**\r
+ * Allow Extended IO interface usage without muddying up the Stringifier Interface\r
+ */\r
+public class JAXBObjectifier<T> implements IOObjectifier<T> {\r
+ private JAXBumar jumar;\r
+\r
+ public JAXBObjectifier(Schema schema, Class<?>... classes) throws APIException {\r
+ try {\r
+ jumar = new JAXBumar(schema, classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ public JAXBObjectifier(Class<?>... classes) throws APIException {\r
+ try {\r
+ jumar = new JAXBumar(classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ // package on purpose\r
+ JAXBObjectifier(JAXBumar jumar) {\r
+ this.jumar = jumar;\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public T objectify(Env env, String input) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Unmarshal", Env.XML);\r
+ try {\r
+ tt.size(input.length());\r
+ return (T)jumar.unmarshal(env.debug(), input);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public T objectify(Env env, Reader rdr) throws APIException {\r
+ //TODO create a Reader that Counts?\r
+ TimeTaken tt = env.start("JAXB Unmarshal", Env.XML);\r
+ try {\r
+ return (T)jumar.unmarshal(env.debug(), rdr);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+\r
+ @SuppressWarnings("unchecked")\r
+ // @Override\r
+ public T objectify(Env env, InputStream is) throws APIException {\r
+ //TODO create a Reader that Counts?\r
+ TimeTaken tt = env.start("JAXB Unmarshal", Env.XML);\r
+ try {\r
+ return (T)jumar.unmarshal(env.debug(), is);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+\r
+ public void servicePrestart(Env env) throws APIException {\r
+ }\r
+\r
+ public void threadPrestart(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void refresh(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void threadDestroy(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void serviceDestroy(Env env) throws APIException {\r
+ }\r
+\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public T newInstance() throws APIException {\r
+ try {\r
+ return (T)jumar.newInstance();\r
+ } catch (Exception e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.jaxb;
-
-import java.io.OutputStream;
-import java.io.StringWriter;
-import java.io.Writer;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.namespace.QName;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.TimeTaken;
-import org.onap.aaf.misc.env.old.IOStringifier;
-
-public class JAXBStringifier<T> implements IOStringifier<T> {
- private JAXBmar jmar;
-
- public JAXBStringifier(Class<?>... classes) throws APIException {
- try {
- jmar = new JAXBmar(classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public JAXBStringifier(QName qname, Class<?>... classes)
- throws APIException {
- try {
- jmar = new JAXBmar(qname, classes);
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- // package on purpose
- JAXBStringifier(JAXBmar jmar) {
- this.jmar = jmar;
- }
-
- // // @Override
- public void stringify(Env env, T input, Writer writer, boolean ... options)
- throws APIException {
- TimeTaken tt = env.start("JAXB Marshal", Env.XML);
- try {
- jmar.marshal(env.debug(), input, writer, options);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public void stringify(Env env, T input, OutputStream os, boolean ... options)
- throws APIException {
- // TODO create an OutputStream that Counts?
- TimeTaken tt = env.start("JAXB Marshal", Env.XML);
- try {
- jmar.marshal(env.debug(), input, os, options);
- } catch (JAXBException e) {
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // @Override
- public String stringify(Env env, T input, boolean ... options) throws APIException {
- TimeTaken tt = env.start("JAXB Marshal", Env.XML);
- StringWriter sw = new StringWriter();
- try {
- jmar.marshal(env.debug(), input, sw, options);
- String rv = sw.toString();
- tt.size(rv.length());
- return rv;
- } catch (JAXBException e) {
- tt.size(0);
- throw new APIException(e);
- } finally {
- tt.done();
- }
- }
-
- // // @Override
- public void servicePrestart(Env env) throws APIException {
- }
-
- // // @Override
- public void threadPrestart(Env env) throws APIException {
- }
-
- // // @Override
- public void refresh(Env env) throws APIException {
- }
-
- // // @Override
- public void threadDestroy(Env env) throws APIException {
- }
-
- // // @Override
- public void serviceDestroy(Env env) throws APIException {
- }
-
- // @Override
- public JAXBStringifier<T> pretty(boolean pretty) {
- jmar.pretty(pretty);
- return this;
- }
-
- // @Override
- public JAXBStringifier<T> asFragment(boolean fragment) {
- jmar.asFragment(fragment);
- return this;
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.jaxb;\r
+\r
+import java.io.OutputStream;\r
+import java.io.StringWriter;\r
+import java.io.Writer;\r
+\r
+import javax.xml.bind.JAXBException;\r
+import javax.xml.namespace.QName;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+import org.onap.aaf.misc.env.old.IOStringifier;\r
+\r
+public class JAXBStringifier<T> implements IOStringifier<T> {\r
+ private JAXBmar jmar;\r
+\r
+ public JAXBStringifier(Class<?>... classes) throws APIException {\r
+ try {\r
+ jmar = new JAXBmar(classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ public JAXBStringifier(QName qname, Class<?>... classes)\r
+ throws APIException {\r
+ try {\r
+ jmar = new JAXBmar(qname, classes);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ // package on purpose\r
+ JAXBStringifier(JAXBmar jmar) {\r
+ this.jmar = jmar;\r
+ }\r
+\r
+ // // @Override\r
+ public void stringify(Env env, T input, Writer writer, boolean ... options)\r
+ throws APIException {\r
+ TimeTaken tt = env.start("JAXB Marshal", Env.XML);\r
+ try {\r
+ jmar.marshal(env.debug(), input, writer, options);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public void stringify(Env env, T input, OutputStream os, boolean ... options)\r
+ throws APIException {\r
+ // TODO create an OutputStream that Counts?\r
+ TimeTaken tt = env.start("JAXB Marshal", Env.XML);\r
+ try {\r
+ jmar.marshal(env.debug(), input, os, options);\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // @Override\r
+ public String stringify(Env env, T input, boolean ... options) throws APIException {\r
+ TimeTaken tt = env.start("JAXB Marshal", Env.XML);\r
+ StringWriter sw = new StringWriter();\r
+ try {\r
+ jmar.marshal(env.debug(), input, sw, options);\r
+ String rv = sw.toString();\r
+ tt.size(rv.length());\r
+ return rv;\r
+ } catch (JAXBException e) {\r
+ tt.size(0);\r
+ throw new APIException(e);\r
+ } finally {\r
+ tt.done();\r
+ }\r
+ }\r
+\r
+ // // @Override\r
+ public void servicePrestart(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void threadPrestart(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void refresh(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void threadDestroy(Env env) throws APIException {\r
+ }\r
+\r
+ // // @Override\r
+ public void serviceDestroy(Env env) throws APIException {\r
+ }\r
+\r
+ // @Override\r
+ public JAXBStringifier<T> pretty(boolean pretty) {\r
+ jmar.pretty(pretty);\r
+ return this;\r
+ }\r
+\r
+ // @Override\r
+ public JAXBStringifier<T> asFragment(boolean fragment) {\r
+ jmar.asFragment(fragment);\r
+ return this;\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- * JAXBumar.java
- *
- * Created on: Apr 10, 2009
- * Created by: Jonathan
- *
- * Revamped to do away with ThreadLocal 5/27/2011, JG1555
- *
- * (c) 2009 SBC Knowledge Ventures, L.P. All rights reserved.
- *******************************************************************
- * RESTRICTED - PROPRIETARY INFORMATION The Information contained
- * herein is for use only by authorized employees of AT&T Services,
- * Inc., and authorized Affiliates of AT&T Services, Inc., and is
- * not for general distribution within or outside the respective
- * companies.
- *******************************************************************
- */
-package org.onap.aaf.misc.env.jaxb;
-
-import java.io.OutputStream;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.namespace.QName;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.LogTarget;
-import org.onap.aaf.misc.env.util.Pool;
-import org.onap.aaf.misc.env.util.Pool.Pooled;
-
-/**
- * JAXBmar classes are inexpensive for going in and out of scope
- * and have been made thread safe via Pooling
-
- * @author Jonathan
- *
- */
-public class JAXBmar {
- // Need to store off possible JAXBContexts based on Class, which will be stored in Creator
- private static Map<Class<?>[],Pool<PMarshaller>> pools = new HashMap<Class<?>[], Pool<PMarshaller>>();
-
- // Handle Marshaller class setting of properties only when needed
- private class PMarshaller {
- private Marshaller m;
- private boolean p;
- private boolean f;
-
- public PMarshaller(Marshaller marshaller) throws JAXBException {
- m = marshaller;
- m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = false);
- m.setProperty(Marshaller.JAXB_FRAGMENT, f = false);
- }
-
- public Marshaller get(boolean pretty, boolean fragment) throws JAXBException {
- if(pretty != p) {
- m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = pretty);
- }
- if(fragment != f) {
- m.setProperty(Marshaller.JAXB_FRAGMENT, f = fragment);
- }
- return m;
- }
- }
-
- private class Creator implements Pool.Creator<PMarshaller> {
- private JAXBContext jc;
- private String name;
- public Creator(Class<?>[] classes) throws JAXBException {
- jc = JAXBContext.newInstance(classes);
- name = "JAXBmar: " + classes[0].getName();
- }
-
- // @Override
- public PMarshaller create() throws APIException {
- try {
- return new PMarshaller(jc.createMarshaller());
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public String toString() {
- return name;
- }
-
- // @Override
- public void reuse(PMarshaller pm) {
- // Nothing to do
- }
-
- // @Override
- public void destroy(PMarshaller pm) {
- // Nothing to do
- }
-
- // @Override
- public boolean isValid(PMarshaller t) {
- return true;
- }
- }
-
- //TODO isn't UTF-8 a standard string somewhere for encoding?
- private boolean fragment= false;
- private boolean pretty=false;
- private QName qname;
-
- private Pool<PMarshaller> mpool; // specific Pool associated with constructed Classes
- private Class<?> cls;
-
- private Pool<PMarshaller> getPool(Class<?> ... classes) throws JAXBException {
- Pool<PMarshaller> mp;
- synchronized(pools) {
- mp = pools.get(classes);
- if(mp==null) {
- pools.put(classes,mp = new Pool<PMarshaller>(new Creator(classes)));
- }
- }
- return mp;
- }
-
- public JAXBmar(Class<?>... classes) throws JAXBException {
- cls = classes[0];
- mpool = getPool(classes);
- qname = null;
- }
-
- public JAXBmar(QName theQname, Class<?>... classes) throws JAXBException {
- cls = classes[0];
- mpool = getPool(classes);
- qname = theQname;
- }
-
- @SuppressWarnings("unchecked")
- public<O> O marshal(LogTarget lt,O o, Writer writer, boolean ... options) throws JAXBException, APIException {
- boolean pretty, fragment;
- pretty = options.length>0?options[0]:this.pretty;
- fragment = options.length>1?options[1]:this.fragment;
- Pooled<PMarshaller> m = mpool.get(lt);
- try {
- if(qname==null) {
- m.content.get(pretty,fragment).marshal(o, writer);
- } else {
- m.content.get(pretty,fragment).marshal(
- new JAXBElement<O>(qname, (Class<O>)cls, o ),
- writer);
- }
- return o;
- } finally {
- m.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- public<O> O marshal(LogTarget lt, O o, OutputStream os, boolean ... options) throws JAXBException, APIException {
- boolean pretty, fragment;
- pretty = options.length>0?options[0]:this.pretty;
- fragment = options.length>1?options[1]:this.fragment;
- Pooled<PMarshaller> m = mpool.get(lt);
- try {
- if(qname==null) {
- m.content.get(pretty,fragment).marshal(o, os);
- } else {
- m.content.get(pretty,fragment).marshal(
- new JAXBElement<O>(qname, (Class<O>)cls, o ),os);
- }
- return o;
- } finally {
- m.done();
- }
- }
-
- public<O> O marshal(LogTarget lt, O o, Writer writer, Class<O> clss) throws JAXBException, APIException {
- Pooled<PMarshaller> m = mpool.get(lt);
- try {
- if(qname==null) {
- m.content.get(pretty,fragment).marshal(o, writer);
- } else {
- m.content.get(pretty,fragment).marshal(
- new JAXBElement<O>(qname, clss, o),writer);
- }
- return o;
- } finally {
- m.done();
- }
-
- }
-
- public<O> O marshal(LogTarget lt, O o, OutputStream os, Class<O> clss) throws JAXBException, APIException {
- Pooled<PMarshaller> m = mpool.get(lt);
- try {
- if(qname==null) {
- m.content.get(pretty,fragment).marshal(o, os);
- } else {
- m.content.get(pretty,fragment).marshal(
- new JAXBElement<O>(qname, clss, o ),os);
- }
- return o;
- } finally {
- m.done();
- }
- }
-
- /**
- * @return
- */
- public Class<?> getMarshalClass() {
- return cls;
- }
-
- public<O> String stringify(LogTarget lt, O o) throws JAXBException, APIException {
- StringWriter sw = new StringWriter();
- marshal(lt,o,sw);
- return sw.toString();
- }
-
- public JAXBmar pretty(boolean pretty) {
- this.pretty = pretty;
- return this;
- }
-
- public JAXBmar asFragment(boolean fragment) {
- this.fragment = fragment;
- return this;
- }
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * JAXBumar.java\r
+ *\r
+ * Created on: Apr 10, 2009\r
+ * Created by: Jonathan\r
+ *\r
+ * Revamped to do away with ThreadLocal 5/27/2011, JonathanGathman\r
+ *\r
+ * (c) 2009 SBC Knowledge Ventures, L.P. All rights reserved.\r
+ ******************************************************************* \r
+ * RESTRICTED - PROPRIETARY INFORMATION The Information contained \r
+ * herein is for use only by authorized employees of AT&T Services, \r
+ * Inc., and authorized Affiliates of AT&T Services, Inc., and is \r
+ * not for general distribution within or outside the respective \r
+ * companies. \r
+ *******************************************************************\r
+ */\r
+package org.onap.aaf.misc.env.jaxb;\r
+\r
+import java.io.OutputStream;\r
+import java.io.StringWriter;\r
+import java.io.Writer;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import javax.xml.bind.JAXBContext;\r
+import javax.xml.bind.JAXBElement;\r
+import javax.xml.bind.JAXBException;\r
+import javax.xml.bind.Marshaller;\r
+import javax.xml.namespace.QName;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+import org.onap.aaf.misc.env.util.Pool;\r
+import org.onap.aaf.misc.env.util.Pool.Pooled;\r
+\r
+/**\r
+ * JAXBmar classes are inexpensive for going in and out of scope\r
+ * and have been made thread safe via Pooling\r
+\r
+ * @author Jonathan\r
+ *\r
+ */\r
+public class JAXBmar {\r
+ // Need to store off possible JAXBContexts based on Class, which will be stored in Creator\r
+ private static Map<Class<?>[],Pool<PMarshaller>> pools = new HashMap<Class<?>[], Pool<PMarshaller>>();\r
+\r
+ // Handle Marshaller class setting of properties only when needed\r
+ private class PMarshaller {\r
+ private Marshaller m;\r
+ private boolean p;\r
+ private boolean f;\r
+ \r
+ public PMarshaller(Marshaller marshaller) throws JAXBException {\r
+ m = marshaller;\r
+ m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");\r
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = false);\r
+ m.setProperty(Marshaller.JAXB_FRAGMENT, f = false);\r
+ }\r
+ \r
+ public Marshaller get(boolean pretty, boolean fragment) throws JAXBException {\r
+ if(pretty != p) {\r
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = pretty);\r
+ }\r
+ if(fragment != f) {\r
+ m.setProperty(Marshaller.JAXB_FRAGMENT, f = fragment);\r
+ }\r
+ return m;\r
+ }\r
+ }\r
+ \r
+ private class Creator implements Pool.Creator<PMarshaller> {\r
+ private JAXBContext jc;\r
+ private String name;\r
+ public Creator(Class<?>[] classes) throws JAXBException {\r
+ jc = JAXBContext.newInstance(classes);\r
+ name = "JAXBmar: " + classes[0].getName();\r
+ }\r
+ \r
+ // @Override\r
+ public PMarshaller create() throws APIException {\r
+ try {\r
+ return new PMarshaller(jc.createMarshaller());\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+\r
+ public String toString() {\r
+ return name;\r
+ }\r
+\r
+ // @Override\r
+ public void reuse(PMarshaller pm) {\r
+ // Nothing to do\r
+ }\r
+ \r
+ // @Override\r
+ public void destroy(PMarshaller pm) {\r
+ // Nothing to do\r
+ }\r
+\r
+ // @Override\r
+ public boolean isValid(PMarshaller t) {\r
+ return true; \r
+ }\r
+ }\r
+\r
+ //TODO isn't UTF-8 a standard string somewhere for encoding?\r
+ private boolean fragment= false;\r
+ private boolean pretty=false;\r
+ private QName qname;\r
+ \r
+ private Pool<PMarshaller> mpool; // specific Pool associated with constructed Classes\r
+ private Class<?> cls;\r
+ \r
+ private Pool<PMarshaller> getPool(Class<?> ... classes) throws JAXBException {\r
+ Pool<PMarshaller> mp;\r
+ synchronized(pools) {\r
+ mp = pools.get(classes);\r
+ if(mp==null) {\r
+ pools.put(classes,mp = new Pool<PMarshaller>(new Creator(classes)));\r
+ }\r
+ } \r
+ return mp;\r
+ }\r
+ \r
+ public JAXBmar(Class<?>... classes) throws JAXBException {\r
+ cls = classes[0];\r
+ mpool = getPool(classes);\r
+ qname = null;\r
+ }\r
+\r
+ public JAXBmar(QName theQname, Class<?>... classes) throws JAXBException {\r
+ cls = classes[0];\r
+ mpool = getPool(classes);\r
+ qname = theQname;\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public<O> O marshal(LogTarget lt,O o, Writer writer, boolean ... options) throws JAXBException, APIException {\r
+ boolean pretty, fragment;\r
+ pretty = options.length>0?options[0]:this.pretty;\r
+ fragment = options.length>1?options[1]:this.fragment;\r
+ Pooled<PMarshaller> m = mpool.get(lt);\r
+ try {\r
+ if(qname==null) {\r
+ m.content.get(pretty,fragment).marshal(o, writer);\r
+ } else {\r
+ m.content.get(pretty,fragment).marshal(\r
+ new JAXBElement<O>(qname, (Class<O>)cls, o ),\r
+ writer);\r
+ }\r
+ return o;\r
+ } finally {\r
+ m.done();\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public<O> O marshal(LogTarget lt, O o, OutputStream os, boolean ... options) throws JAXBException, APIException {\r
+ boolean pretty, fragment;\r
+ pretty = options.length>0?options[0]:this.pretty;\r
+ fragment = options.length>1?options[1]:this.fragment;\r
+ Pooled<PMarshaller> m = mpool.get(lt);\r
+ try {\r
+ if(qname==null) {\r
+ m.content.get(pretty,fragment).marshal(o, os);\r
+ } else {\r
+ m.content.get(pretty,fragment).marshal(\r
+ new JAXBElement<O>(qname, (Class<O>)cls, o ),os);\r
+ }\r
+ return o;\r
+ } finally {\r
+ m.done();\r
+ }\r
+ }\r
+ \r
+ public<O> O marshal(LogTarget lt, O o, Writer writer, Class<O> clss) throws JAXBException, APIException {\r
+ Pooled<PMarshaller> m = mpool.get(lt);\r
+ try {\r
+ if(qname==null) {\r
+ m.content.get(pretty,fragment).marshal(o, writer);\r
+ } else {\r
+ m.content.get(pretty,fragment).marshal(\r
+ new JAXBElement<O>(qname, clss, o),writer);\r
+ }\r
+ return o;\r
+ } finally {\r
+ m.done();\r
+ }\r
+ \r
+ }\r
+\r
+ public<O> O marshal(LogTarget lt, O o, OutputStream os, Class<O> clss) throws JAXBException, APIException {\r
+ Pooled<PMarshaller> m = mpool.get(lt);\r
+ try {\r
+ if(qname==null) { \r
+ m.content.get(pretty,fragment).marshal(o, os);\r
+ } else {\r
+ m.content.get(pretty,fragment).marshal(\r
+ new JAXBElement<O>(qname, clss, o ),os);\r
+ }\r
+ return o;\r
+ } finally {\r
+ m.done();\r
+ }\r
+ }\r
+\r
+ /**\r
+ * @return\r
+ */\r
+ public Class<?> getMarshalClass() {\r
+ return cls;\r
+ }\r
+\r
+ public<O> String stringify(LogTarget lt, O o) throws JAXBException, APIException {\r
+ StringWriter sw = new StringWriter();\r
+ marshal(lt,o,sw);\r
+ return sw.toString();\r
+ }\r
+\r
+ public JAXBmar pretty(boolean pretty) {\r
+ this.pretty = pretty;\r
+ return this;\r
+ }\r
+ \r
+ public JAXBmar asFragment(boolean fragment) {\r
+ this.fragment = fragment;\r
+ return this;\r
+ }\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- * JAXBumar.java
- *
- * Created on: Apr 10, 2009
- * Created by: Jonathan
- *
- * Revamped to do away with ThreadLocal 5/27/2011, JG1555
- *
- * (c) 2009 SBC Knowledge Ventures, L.P. All rights reserved.
- *******************************************************************
- * RESTRICTED - PROPRIETARY INFORMATION The Information contained
- * herein is for use only by authorized employees of AT&T Services,
- * Inc., and authorized Affiliates of AT&T Services, Inc., and is
- * not for general distribution within or outside the respective
- * companies.
- *******************************************************************
- */
-package org.onap.aaf.misc.env.jaxb;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.stream.XMLEventReader;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.LogTarget;
-import org.onap.aaf.misc.env.util.Pool;
-import org.onap.aaf.misc.env.util.Pool.Pooled;
-import org.w3c.dom.Node;
-
-/**
- * JAXBumar classes are inexpensive for going in and out of scope
- * and have been made thread safe via Pooling
- *
- * @author Jonathan
- *
- */
-public class JAXBumar {
- // Need to store off possible JAXBContexts based on Class, which will be stored in Creator
- private static Map<Class<?>[],Pool<SUnmarshaller>> pools = new HashMap<Class<?>[], Pool<SUnmarshaller>>();
-
- private Class<?> cls;
- private Schema schema;
- private Pool<SUnmarshaller> mpool;;
-
- // Handle Marshaller class setting of properties only when needed
- private class SUnmarshaller {
- private Unmarshaller u;
- private Schema s;
-
- public SUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {
- u = unmarshaller;
- s = null;
- }
-
- public Unmarshaller get(Schema schema) throws JAXBException {
- if(s != schema) {
- u.setSchema(s = schema);
- }
- return u;
- }
- }
-
- private class Creator implements Pool.Creator<SUnmarshaller> {
- private JAXBContext jc;
- private String name;
-
- public Creator(Class<?>[] classes) throws JAXBException {
- jc = JAXBContext.newInstance(classes);
- name = "JAXBumar: " + classes[0].getName();
- }
-
- // @Override
- public SUnmarshaller create() throws APIException {
- try {
- return new SUnmarshaller(jc.createUnmarshaller());
- } catch (JAXBException e) {
- throw new APIException(e);
- }
- }
-
- public String toString() {
- return name;
- }
-
- // @Override
- public void destroy(SUnmarshaller sui) {
- // Nothing to do
- }
-
- // @Override
- public boolean isValid(SUnmarshaller t) {
- return true;
- }
-
- // @Override
- public void reuse(SUnmarshaller t) {
- // Nothing to do here
- }
-
- }
-
- private Pool<SUnmarshaller> getPool(Class<?> ... classes) throws JAXBException {
- Pool<SUnmarshaller> mp;
- synchronized(pools) {
- mp = pools.get(classes);
- if(mp==null) {
- pools.put(classes,mp = new Pool<SUnmarshaller>(new Creator(classes)));
- }
- }
- return mp;
- }
-
- public JAXBumar(Class<?> ... classes) throws JAXBException {
- cls = classes[0];
- mpool = getPool(classes);
- schema = null;
- }
-
- /**
- * Constructs a new JAXBumar with schema validation enabled.
- *
- * @param schema
- * @param theClass
- * @throws JAXBException
- */
- public JAXBumar(Schema schema, Class<?> ... classes) throws JAXBException {
- cls = classes[0];
- mpool = getPool(classes);
- this.schema = schema;
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env, Node node) throws JAXBException, APIException {
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return s.content.get(schema).unmarshal(node,(Class<O>)cls).getValue();
- } finally {
- s.done();
- }
-
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env, String xml) throws JAXBException, APIException {
- if(xml==null) throw new JAXBException("Null Input for String unmarshal");
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return (O)s.content.get(schema).unmarshal(
- new StreamSource(new StringReader(xml))
- ,(Class<O>)cls).getValue();
- } finally {
- s.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env, File xmlFile) throws JAXBException, APIException {
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return (O)s.content.get(schema).unmarshal(xmlFile);
- } finally {
- s.done();
- }
-
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env,InputStream is) throws JAXBException, APIException {
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return (O)s.content.get(schema).unmarshal(is);
- } finally {
- s.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env, Reader rdr) throws JAXBException, APIException {
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return (O)s.content.get(schema).unmarshal(rdr);
- } finally {
- s.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env, XMLStreamReader xsr) throws JAXBException, APIException {
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return (O)s.content.get(schema).unmarshal(xsr,(Class<O>)cls).getValue();
- } finally {
- s.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- public<O> O unmarshal(LogTarget env, XMLEventReader xer) throws JAXBException, APIException {
- Pooled<SUnmarshaller> s = mpool.get(env);
- try {
- return (O)s.content.get(schema).unmarshal(xer,(Class<O>)cls).getValue();
- } finally {
- s.done();
- }
- }
-
- @SuppressWarnings("unchecked")
- public<O> O newInstance() throws InstantiationException, IllegalAccessException{
- return ((Class<O>)cls).newInstance();
- }
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * JAXBumar.java\r
+ *\r
+ * Created on: Apr 10, 2009\r
+ * Created by: Jonathan\r
+ *\r
+ * Revamped to do away with ThreadLocal 5/27/2011, JonathanGathman\r
+ *\r
+ * (c) 2009 SBC Knowledge Ventures, L.P. All rights reserved.\r
+ ******************************************************************* \r
+ * RESTRICTED - PROPRIETARY INFORMATION The Information contained \r
+ * herein is for use only by authorized employees of AT&T Services, \r
+ * Inc., and authorized Affiliates of AT&T Services, Inc., and is \r
+ * not for general distribution within or outside the respective \r
+ * companies. \r
+ *******************************************************************\r
+ */\r
+package org.onap.aaf.misc.env.jaxb;\r
+\r
+import java.io.File;\r
+import java.io.InputStream;\r
+import java.io.Reader;\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import javax.xml.bind.JAXBContext;\r
+import javax.xml.bind.JAXBException;\r
+import javax.xml.bind.Unmarshaller;\r
+import javax.xml.stream.XMLEventReader;\r
+import javax.xml.stream.XMLStreamReader;\r
+import javax.xml.transform.stream.StreamSource;\r
+import javax.xml.validation.Schema;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+import org.onap.aaf.misc.env.util.Pool;\r
+import org.onap.aaf.misc.env.util.Pool.Pooled;\r
+import org.w3c.dom.Node;\r
+\r
+/**\r
+ * JAXBumar classes are inexpensive for going in and out of scope\r
+ * and have been made thread safe via Pooling\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ */\r
+public class JAXBumar {\r
+ // Need to store off possible JAXBContexts based on Class, which will be stored in Creator\r
+ private static Map<Class<?>[],Pool<SUnmarshaller>> pools = new HashMap<Class<?>[], Pool<SUnmarshaller>>();\r
+\r
+ private Class<?> cls;\r
+ private Schema schema;\r
+ private Pool<SUnmarshaller> mpool;;\r
+\r
+ // Handle Marshaller class setting of properties only when needed\r
+ private class SUnmarshaller {\r
+ private Unmarshaller u;\r
+ private Schema s;\r
+ \r
+ public SUnmarshaller(Unmarshaller unmarshaller) throws JAXBException {\r
+ u = unmarshaller;\r
+ s = null;\r
+ }\r
+ \r
+ public Unmarshaller get(Schema schema) throws JAXBException {\r
+ if(s != schema) {\r
+ u.setSchema(s = schema);\r
+ }\r
+ return u;\r
+ }\r
+ }\r
+ \r
+ private class Creator implements Pool.Creator<SUnmarshaller> {\r
+ private JAXBContext jc;\r
+ private String name;\r
+ \r
+ public Creator(Class<?>[] classes) throws JAXBException {\r
+ jc = JAXBContext.newInstance(classes);\r
+ name = "JAXBumar: " + classes[0].getName();\r
+ }\r
+ \r
+ // @Override\r
+ public SUnmarshaller create() throws APIException {\r
+ try {\r
+ return new SUnmarshaller(jc.createUnmarshaller());\r
+ } catch (JAXBException e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ public String toString() {\r
+ return name;\r
+ }\r
+\r
+ // @Override\r
+ public void destroy(SUnmarshaller sui) {\r
+ // Nothing to do\r
+ }\r
+ \r
+ // @Override\r
+ public boolean isValid(SUnmarshaller t) {\r
+ return true; \r
+ }\r
+\r
+ // @Override\r
+ public void reuse(SUnmarshaller t) {\r
+ // Nothing to do here\r
+ }\r
+\r
+ }\r
+\r
+ private Pool<SUnmarshaller> getPool(Class<?> ... classes) throws JAXBException {\r
+ Pool<SUnmarshaller> mp;\r
+ synchronized(pools) {\r
+ mp = pools.get(classes);\r
+ if(mp==null) {\r
+ pools.put(classes,mp = new Pool<SUnmarshaller>(new Creator(classes)));\r
+ }\r
+ } \r
+ return mp;\r
+ }\r
+\r
+ public JAXBumar(Class<?> ... classes) throws JAXBException {\r
+ cls = classes[0];\r
+ mpool = getPool(classes);\r
+ schema = null;\r
+ }\r
+ \r
+ /**\r
+ * Constructs a new JAXBumar with schema validation enabled.\r
+ * \r
+ * @param schema\r
+ * @param theClass\r
+ * @throws JAXBException\r
+ */\r
+ public JAXBumar(Schema schema, Class<?> ... classes) throws JAXBException {\r
+ cls = classes[0];\r
+ mpool = getPool(classes);\r
+ this.schema = schema;\r
+ }\r
+ \r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env, Node node) throws JAXBException, APIException {\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return s.content.get(schema).unmarshal(node,(Class<O>)cls).getValue();\r
+ } finally {\r
+ s.done();\r
+ }\r
+\r
+ }\r
+ \r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env, String xml) throws JAXBException, APIException {\r
+ if(xml==null) throw new JAXBException("Null Input for String unmarshal");\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return (O)s.content.get(schema).unmarshal(\r
+ new StreamSource(new StringReader(xml))\r
+ ,(Class<O>)cls).getValue();\r
+ } finally {\r
+ s.done();\r
+ }\r
+ }\r
+ \r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env, File xmlFile) throws JAXBException, APIException {\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return (O)s.content.get(schema).unmarshal(xmlFile);\r
+ } finally {\r
+ s.done();\r
+ }\r
+\r
+ }\r
+ \r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env,InputStream is) throws JAXBException, APIException {\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return (O)s.content.get(schema).unmarshal(is);\r
+ } finally {\r
+ s.done();\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env, Reader rdr) throws JAXBException, APIException {\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return (O)s.content.get(schema).unmarshal(rdr);\r
+ } finally {\r
+ s.done();\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env, XMLStreamReader xsr) throws JAXBException, APIException {\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return (O)s.content.get(schema).unmarshal(xsr,(Class<O>)cls).getValue();\r
+ } finally {\r
+ s.done();\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public<O> O unmarshal(LogTarget env, XMLEventReader xer) throws JAXBException, APIException {\r
+ Pooled<SUnmarshaller> s = mpool.get(env);\r
+ try {\r
+ return (O)s.content.get(schema).unmarshal(xer,(Class<O>)cls).getValue();\r
+ } finally {\r
+ s.done();\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ public<O> O newInstance() throws InstantiationException, IllegalAccessException{\r
+ return ((Class<O>)cls).newInstance();\r
+ }\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.old;
-
-import java.io.InputStream;
-import java.io.Reader;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-
-public interface IOObjectifier<T> extends Objectifier<T> {
- /**
- * Marshal to Object T from a Reader, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return T
- * @throws APIException
- */
- public abstract T objectify(Env env, Reader rdr) throws APIException;
-
- /**
- * Marshal to Object T from an InputStream, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return T
- * @throws APIException
- */
- public abstract T objectify(Env env, InputStream is) throws APIException;
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.old;\r
+\r
+import java.io.InputStream;\r
+import java.io.Reader;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+\r
+public interface IOObjectifier<T> extends Objectifier<T> {\r
+ /**\r
+ * Marshal to Object T from a Reader, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T objectify(Env env, Reader rdr) throws APIException;\r
+ \r
+ /**\r
+ * Marshal to Object T from an InputStream, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T objectify(Env env, InputStream is) throws APIException;\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.old;
-
-import java.io.OutputStream;
-import java.io.Writer;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-
-/**
- * Allow Extended IO interface usage without muddying up the Stringifier Interface
- */
-public interface IOStringifier<T> extends Stringifier<T> {
- /**
- * Marshal from an Object T onto a Writer, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startTime(<string>, Env.XML)" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return String
- * @throws APIException
- */
- public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException;
-
- /**
- * Marshal from a String to an Object T, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return String
- * @throws APIException
- */
- public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException;
-
- /**
- * Set Pretty XML, where possible
- *
- * @param pretty
- * @throws APIException
- */
- public abstract IOStringifier<T> pretty(boolean pretty);
-
- /**
- * Set Generate Fragment
- *
- * @param fragment
- * @throws APIException
- */
- public abstract IOStringifier<T> asFragment(boolean fragment);
-
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.old;\r
+\r
+import java.io.OutputStream;\r
+import java.io.Writer;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+\r
+/**\r
+ * Allow Extended IO interface usage without muddying up the Stringifier Interface\r
+ */\r
+public interface IOStringifier<T> extends Stringifier<T> {\r
+ /**\r
+ * Marshal from an Object T onto a Writer, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startTime(<string>, Env.XML)" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public abstract void stringify(Env env, T input, Writer writer, boolean ... options) throws APIException;\r
+ \r
+ /**\r
+ * Marshal from a String to an Object T, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public abstract void stringify(Env env, T input, OutputStream os, boolean ... options) throws APIException;\r
+\r
+ /**\r
+ * Set Pretty XML, where possible\r
+ * \r
+ * @param pretty\r
+ * @throws APIException\r
+ */\r
+ public abstract IOStringifier<T> pretty(boolean pretty);\r
+\r
+ /**\r
+ * Set Generate Fragment\r
+ * \r
+ * @param fragment\r
+ * @throws APIException\r
+ */\r
+ public abstract IOStringifier<T> asFragment(boolean fragment);\r
+\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/**
- *
- */
-package org.onap.aaf.misc.env.old;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.LifeCycle;
-
-
-/**
- * <h1>Objectifier</h1>
- * <i>Objectifier</i> abstracts the unmarshaling of an Object from a String, and
- * the creation of an uninitialized object.
- */
-public interface Objectifier<T> extends LifeCycle {
- /**
- * Marshal to Object T from a String, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return T
- * @throws APIException
- */
- public abstract T objectify(Env env, String input) throws APIException;
-
- /**
- * Create a new object of type T. This is often more efficiently done with
- * the underlying XML (or other) Library.
- * @return T
- * @throws APIException
- */
- public abstract T newInstance() throws APIException;
-
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/**\r
+ * \r
+ */\r
+package org.onap.aaf.misc.env.old;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.LifeCycle;\r
+\r
+\r
+/**\r
+ * <h1>Objectifier</h1>\r
+ * <i>Objectifier</i> abstracts the unmarshaling of an Object from a String, and \r
+ * the creation of an uninitialized object. \r
+ */\r
+public interface Objectifier<T> extends LifeCycle {\r
+ /**\r
+ * Marshal to Object T from a String, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T objectify(Env env, String input) throws APIException;\r
+\r
+ /**\r
+ * Create a new object of type T. This is often more efficiently done with\r
+ * the underlying XML (or other) Library.\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public abstract T newInstance() throws APIException;\r
+\r
+ \r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.old;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Data;
-import org.onap.aaf.misc.env.DataFactory;
-import org.onap.aaf.misc.env.Env;
-
-public interface OldDataFactory<T> extends DataFactory<T> {
- public abstract String stringify(T type) throws APIException;
- public abstract void stringify(T type, OutputStream os) throws APIException;
- public abstract void stringify(T type, Writer writer) throws APIException;
- public abstract T objectify(InputStream is) throws APIException;
- public abstract T objectify(Reader rdr) throws APIException;
- public abstract T objectify(String text) throws APIException;
- public abstract T newInstance() throws APIException;
- public abstract Data<T> newData(T type);
- public abstract Data<T> newDataFromStream(Env env, InputStream input) throws APIException;
- public abstract Data<T> newDataFromString(String string);
-
-}
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.old;\r
+\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.io.Reader;\r
+import java.io.Writer;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Data;\r
+import org.onap.aaf.misc.env.DataFactory;\r
+import org.onap.aaf.misc.env.Env;\r
+\r
+public interface OldDataFactory<T> extends DataFactory<T> {\r
+ public abstract String stringify(T type) throws APIException;\r
+ public abstract void stringify(T type, OutputStream os) throws APIException;\r
+ public abstract void stringify(T type, Writer writer) throws APIException;\r
+ public abstract T objectify(InputStream is) throws APIException;\r
+ public abstract T objectify(Reader rdr) throws APIException;\r
+ public abstract T objectify(String text) throws APIException;\r
+ public abstract T newInstance() throws APIException;\r
+ public abstract Data<T> newData(T type);\r
+ public abstract Data<T> newDataFromStream(Env env, InputStream input) throws APIException;\r
+ public abstract Data<T> newDataFromString(String string);\r
+ \r
+}\r
+\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.old;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.LifeCycle;
-
-
-/**
- * <h1>Stringifier</h1>
- * <i>Stringifier</i> abstracts the marshaling of a String to an Object
- */
-public interface Stringifier<T> extends LifeCycle {
-
- /**
- * Marshal from a String to an Object T, using contents from Env as necessary.<p>
- *
- * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark
- * XML time, since this is often a costly process.
- *
- * @param env
- * @param input
- * @return String
- * @throws APIException
- */
- public abstract String stringify(Env env, T input, boolean ... options) throws APIException;
-
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.old;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.LifeCycle;\r
+\r
+\r
+/**\r
+ * <h1>Stringifier</h1>\r
+ * <i>Stringifier</i> abstracts the marshaling of a String to an Object\r
+ */\r
+public interface Stringifier<T> extends LifeCycle {\r
+ \r
+ /**\r
+ * Marshal from a String to an Object T, using contents from Env as necessary.<p>\r
+ * \r
+ * Implementations should use the {@link Env} to call "env.startXMLTime()" to mark\r
+ * XML time, since this is often a costly process.\r
+ *\r
+ * @param env\r
+ * @param input\r
+ * @return String\r
+ * @throws APIException\r
+ */\r
+ public abstract String stringify(Env env, T input, boolean ... options) throws APIException;\r
+ \r
}
\ No newline at end of file
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.security.SecureRandom;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.TimeZone;
-import java.util.UUID;
-import java.util.logging.Formatter;
-import java.util.logging.LogRecord;
-
-import javax.xml.datatype.DatatypeConfigurationException;
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-public class Chrono {
- private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;
-
- public final static DateFormat dateFmt, dateOnlyFmt, niceDateFmt, utcFmt,iso8601Fmt;
- // Give general access to XML DataType Factory, since it's pretty common
- public static final DatatypeFactory xmlDatatypeFactory;
-
- static {
- try {
- xmlDatatypeFactory = DatatypeFactory.newInstance();
- } catch (DatatypeConfigurationException e) {
- throw new RuntimeException(e);
- }
- dateOnlyFmt = new SimpleDateFormat("yyyy-MM-dd");
- niceDateFmt = new SimpleDateFormat("yyyy/MM/dd HH:mm zzz");
- dateFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
- utcFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
- iso8601Fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
- utcFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
- }
-
-
- public static class Formatter8601 extends Formatter {
-
- @Override
- public String format(LogRecord r) {
- StringBuilder sb = new StringBuilder();
- sb.append(dateFmt.format(new Date(r.getMillis())));
- sb.append(' ');
- sb.append(r.getThreadID());
- sb.append(' ');
- sb.append(r.getLevel());
- sb.append(": ");
- sb.append(r.getMessage());
- sb.append('\n');
- return sb.toString();
- }
-
- }
-
- /**
- * timeStamp
- *
- * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with "now"
- * @return
- */
- public static XMLGregorianCalendar timeStamp() {
- return xmlDatatypeFactory.newXMLGregorianCalendar(new GregorianCalendar());
- }
-
- /**
- * timestamp
- *
- * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with passed in Date
- * @param date
- * @return
- */
- public static XMLGregorianCalendar timeStamp(Date date) {
- GregorianCalendar gc = new GregorianCalendar();
- gc.setTime(date);
- return xmlDatatypeFactory.newXMLGregorianCalendar(gc);
- }
-
- public static XMLGregorianCalendar timeStamp(GregorianCalendar gc) {
- return xmlDatatypeFactory.newXMLGregorianCalendar(gc);
- }
-
- public static String utcStamp() {
- return utcFmt.format(new Date());
- }
-
- public static String utcStamp(Date date) {
- if(date==null)return "";
- return utcFmt.format(date);
- }
-
- public static String utcStamp(GregorianCalendar gc) {
- if(gc==null)return "";
- return utcFmt.format(gc.getTime());
- }
-
- public static String utcStamp(XMLGregorianCalendar xgc) {
- if(xgc==null)return "";
- return utcFmt.format(xgc.toGregorianCalendar().getTime());
- }
-
- public static String dateStamp() {
- return dateFmt.format(new Date());
- }
-
- public static String dateStamp(GregorianCalendar gc) {
- if(gc == null)return "";
- return dateFmt.format(gc.getTime());
- }
-
- public static String dateStamp(Date date) {
- if(date == null)return "";
- return dateFmt.format(date);
- }
-
- public static String dateStamp(XMLGregorianCalendar xgc) {
- if(xgc==null)return "";
- return dateFmt.format(xgc.toGregorianCalendar().getTime());
- }
-
- /**
- * JAXB compatible dataTime Stamp
- *
- * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.
- *
- * @return
- */
- public static String dateTime() {
- return dateTime(new GregorianCalendar());
- }
-
- /**
- * JAXB compatible dataTime Stamp
- *
- * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.
- *
- * @return
- */
- public static String dateTime(Date date) {
- GregorianCalendar gc = new GregorianCalendar();
- gc.setTime(date);
- return dateTime(gc);
- }
-
- /**
- * JAXB compatible dataTime Stamp
- *
- * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.
- *
- * @return
- */
- public static String dateTime(GregorianCalendar gc) {
- if(gc == null)return "";
- TimeZone tz = gc.getTimeZone();
- int tz1 = (tz.getRawOffset()+tz.getDSTSavings())/0x8CA0;
- int tz1abs = Math.abs(tz1);
- return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d",
- gc.get(GregorianCalendar.YEAR),
- gc.get(GregorianCalendar.MONTH)+1,
- gc.get(GregorianCalendar.DAY_OF_MONTH),
- gc.get(GregorianCalendar.HOUR),
- gc.get(GregorianCalendar.MINUTE),
- gc.get(GregorianCalendar.SECOND),
- gc.get(GregorianCalendar.MILLISECOND),
- tz1==tz1abs?'+':'-',
- tz1abs/100,
- ((tz1abs-(tz1abs/100)*100)*6)/10 // Get the "10s", then convert to mins (without losing int place)
- );
- }
-
- /**
- * JAXB compatible dataTime Stamp
- *
- * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.
- *
- * @return
- */
- public static String dateTime(XMLGregorianCalendar xgc) {
- return xgc==null?"":dateTime(xgc.toGregorianCalendar());
- }
-
- public static String dateOnlyStamp() {
- return dateOnlyFmt.format(new Date());
- }
-
- public static String dateOnlyStamp(GregorianCalendar gc) {
- return gc == null?"":dateOnlyFmt.format(gc.getTime());
- }
-
- public static String dateOnlyStamp(Date date) {
- return date == null?"":dateOnlyFmt.format(date);
- }
-
- public static String dateOnlyStamp(XMLGregorianCalendar xgc) {
- return xgc==null?"":dateOnlyFmt.format(xgc.toGregorianCalendar().getTime());
- }
-
- public static String niceDateStamp() {
- return niceDateFmt.format(new Date());
- }
-
- public static String niceDateStamp(Date date) {
- return date==null?"":niceDateFmt.format(date);
- }
-
- public static String niceDateStamp(GregorianCalendar gc) {
- return gc==null?"":niceDateFmt.format(gc.getTime());
- }
-
- public static String niceDateStamp(XMLGregorianCalendar xgc) {
- return xgc==null?"":niceDateFmt.format(xgc.toGregorianCalendar().getTime());
- }
-
-
- ////////////////////// HELPFUL Strings
- public static final String BAD_DIR_CHARS_REGEX = "[/:\\;.]";
- public static final String SPLIT_DIR_REGEX = "/";
-
- public static long firstMomentOfDay(long utc) {
- GregorianCalendar begin = new GregorianCalendar();
- begin.setTimeInMillis(utc);
- return firstMomentOfDay(begin).getTimeInMillis();
- }
-
- public static long lastMomentOfDay(long utc) {
- GregorianCalendar end = new GregorianCalendar();
- end.setTimeInMillis(utc);
- return lastMomentOfDay(end).getTimeInMillis();
- }
-
- public static GregorianCalendar firstMomentOfDay(GregorianCalendar begin) {
- if(begin==null)begin = new GregorianCalendar();
- begin.set(GregorianCalendar.HOUR, 0);
- begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);
- begin.set(GregorianCalendar.MINUTE, 0);
- begin.set(GregorianCalendar.SECOND, 0);
- begin.set(GregorianCalendar.MILLISECOND, 0);
- return begin;
- }
-
- public static GregorianCalendar lastMomentOfDay(GregorianCalendar end) {
- if(end==null)end = new GregorianCalendar();
- end.set(GregorianCalendar.HOUR, 11);
- end.set(GregorianCalendar.MINUTE, 59);
- end.set(GregorianCalendar.SECOND, 59);
- end.set(GregorianCalendar.MILLISECOND, 999);
- end.set(GregorianCalendar.AM_PM, GregorianCalendar.PM);
- return end;
- }
-
- // UUID needs to be converted from UUID Epoch
- public static final Date uuidToDate(UUID id) {
- return new Date((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000);
- }
-
- public static final long uuidToUnix(UUID id) {
- return (id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000;
- }
-
- public static float millisFromNanos(long start, long end) {
- return (end - start) / 1000000f;
- }
-
-
- private static long sequence = new SecureRandom().nextInt();
- private static synchronized long sequence() {
- return ++sequence;
- }
-
- public static final UUID dateToUUID(Date origTime) {
- return dateToUUID(origTime.getTime());
- }
-
- public static final UUID dateToUUID(long origTime) {
- /*
- * From Cassandra : http://wiki.apache.org/cassandra/FAQ
- Magic number obtained from #cassandra's thobbs, who
- claims to have stolen it from a Python library.
- */
- long time = origTime * 10000 + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH;
- long timeLow = time & 0xffffffffL;
- long timeMid = time & 0xffff00000000L;
- long timeHi = time & 0xfff000000000000L;
- long upperLong = (timeLow << 32) | (timeMid >> 16) | (1 << 12) | (timeHi >> 48) ;
- return new java.util.UUID(upperLong, (0xC000000000000000L | sequence()));
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.security.SecureRandom;\r
+import java.text.DateFormat;\r
+import java.text.SimpleDateFormat;\r
+import java.util.Date;\r
+import java.util.GregorianCalendar;\r
+import java.util.TimeZone;\r
+import java.util.UUID;\r
+import java.util.logging.Formatter;\r
+import java.util.logging.LogRecord;\r
+\r
+import javax.xml.datatype.DatatypeConfigurationException;\r
+import javax.xml.datatype.DatatypeFactory;\r
+import javax.xml.datatype.XMLGregorianCalendar;\r
+\r
+public class Chrono {\r
+ private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;\r
+\r
+ public final static DateFormat dateFmt, dateOnlyFmt, niceDateFmt, utcFmt,iso8601Fmt;\r
+ // Give general access to XML DataType Factory, since it's pretty common\r
+ public static final DatatypeFactory xmlDatatypeFactory;\r
+ \r
+ static {\r
+ try {\r
+ xmlDatatypeFactory = DatatypeFactory.newInstance();\r
+ } catch (DatatypeConfigurationException e) {\r
+ throw new RuntimeException(e);\r
+ }\r
+ dateOnlyFmt = new SimpleDateFormat("yyyy-MM-dd");\r
+ niceDateFmt = new SimpleDateFormat("yyyy/MM/dd HH:mm zzz");\r
+ dateFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");\r
+ utcFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");\r
+ iso8601Fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");\r
+ utcFmt.setTimeZone(TimeZone.getTimeZone("UTC"));\r
+ }\r
+ \r
+\r
+ public static class Formatter8601 extends Formatter {\r
+\r
+ @Override\r
+ public String format(LogRecord r) {\r
+ StringBuilder sb = new StringBuilder();\r
+ sb.append(dateFmt.format(new Date(r.getMillis())));\r
+ sb.append(' ');\r
+ sb.append(r.getThreadID());\r
+ sb.append(' ');\r
+ sb.append(r.getLevel());\r
+ sb.append(": ");\r
+ sb.append(r.getMessage());\r
+ sb.append('\n');\r
+ return sb.toString();\r
+ }\r
+ \r
+ }\r
+ \r
+ /**\r
+ * timeStamp\r
+ * \r
+ * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with "now" \r
+ * @return\r
+ */\r
+ public static XMLGregorianCalendar timeStamp() {\r
+ return xmlDatatypeFactory.newXMLGregorianCalendar(new GregorianCalendar());\r
+ }\r
+\r
+ /**\r
+ * timestamp\r
+ * \r
+ * Convenience method to setup an XML dateTime (XMLGregorianCalendar) with passed in Date \r
+ * @param date\r
+ * @return\r
+ */\r
+ public static XMLGregorianCalendar timeStamp(Date date) {\r
+ GregorianCalendar gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ return xmlDatatypeFactory.newXMLGregorianCalendar(gc);\r
+ }\r
+\r
+ public static XMLGregorianCalendar timeStamp(GregorianCalendar gc) {\r
+ return xmlDatatypeFactory.newXMLGregorianCalendar(gc);\r
+ }\r
+\r
+ public static String utcStamp() {\r
+ return utcFmt.format(new Date());\r
+ }\r
+\r
+ public static String utcStamp(Date date) {\r
+ if(date==null)return "";\r
+ return utcFmt.format(date);\r
+ }\r
+\r
+ public static String utcStamp(GregorianCalendar gc) {\r
+ if(gc==null)return "";\r
+ return utcFmt.format(gc.getTime());\r
+ }\r
+\r
+ public static String utcStamp(XMLGregorianCalendar xgc) {\r
+ if(xgc==null)return "";\r
+ return utcFmt.format(xgc.toGregorianCalendar().getTime());\r
+ }\r
+\r
+ public static String dateStamp() {\r
+ return dateFmt.format(new Date());\r
+ }\r
+\r
+ public static String dateStamp(GregorianCalendar gc) {\r
+ if(gc == null)return "";\r
+ return dateFmt.format(gc.getTime());\r
+ }\r
+\r
+ public static String dateStamp(Date date) {\r
+ if(date == null)return "";\r
+ return dateFmt.format(date);\r
+ }\r
+\r
+ public static String dateStamp(XMLGregorianCalendar xgc) {\r
+ if(xgc==null)return "";\r
+ return dateFmt.format(xgc.toGregorianCalendar().getTime());\r
+ }\r
+\r
+ /**\r
+ * JAXB compatible dataTime Stamp\r
+ * \r
+ * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.\r
+ * \r
+ * @return\r
+ */\r
+ public static String dateTime() {\r
+ return dateTime(new GregorianCalendar());\r
+ }\r
+\r
+ /**\r
+ * JAXB compatible dataTime Stamp\r
+ * \r
+ * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.\r
+ * \r
+ * @return\r
+ */\r
+ public static String dateTime(Date date) {\r
+ GregorianCalendar gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ return dateTime(gc);\r
+ }\r
+\r
+ /**\r
+ * JAXB compatible dataTime Stamp\r
+ * \r
+ * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.\r
+ * \r
+ * @return\r
+ */\r
+ public static String dateTime(GregorianCalendar gc) {\r
+ if(gc == null)return "";\r
+ TimeZone tz = gc.getTimeZone();\r
+ int tz1 = (tz.getRawOffset()+tz.getDSTSavings())/0x8CA0;\r
+ int tz1abs = Math.abs(tz1);\r
+ return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d", \r
+ gc.get(GregorianCalendar.YEAR),\r
+ gc.get(GregorianCalendar.MONTH)+1,\r
+ gc.get(GregorianCalendar.DAY_OF_MONTH),\r
+ gc.get(GregorianCalendar.HOUR),\r
+ gc.get(GregorianCalendar.MINUTE),\r
+ gc.get(GregorianCalendar.SECOND),\r
+ gc.get(GregorianCalendar.MILLISECOND),\r
+ tz1==tz1abs?'+':'-',\r
+ tz1abs/100,\r
+ ((tz1abs-(tz1abs/100)*100)*6)/10 // Get the "10s", then convert to mins (without losing int place)\r
+ );\r
+ }\r
+\r
+ /**\r
+ * JAXB compatible dataTime Stamp\r
+ * \r
+ * Java 6 does not format Timezone with -05:00 format, and JAXB XML breaks without it.\r
+ * \r
+ * @return\r
+ */\r
+ public static String dateTime(XMLGregorianCalendar xgc) {\r
+ return xgc==null?"":dateTime(xgc.toGregorianCalendar());\r
+ }\r
+\r
+ public static String dateOnlyStamp() {\r
+ return dateOnlyFmt.format(new Date());\r
+ }\r
+\r
+ public static String dateOnlyStamp(GregorianCalendar gc) {\r
+ return gc == null?"":dateOnlyFmt.format(gc.getTime());\r
+ }\r
+\r
+ public static String dateOnlyStamp(Date date) {\r
+ return date == null?"":dateOnlyFmt.format(date);\r
+ }\r
+\r
+ public static String dateOnlyStamp(XMLGregorianCalendar xgc) {\r
+ return xgc==null?"":dateOnlyFmt.format(xgc.toGregorianCalendar().getTime());\r
+ }\r
+\r
+ public static String niceDateStamp() {\r
+ return niceDateFmt.format(new Date());\r
+ }\r
+\r
+ public static String niceDateStamp(Date date) {\r
+ return date==null?"":niceDateFmt.format(date);\r
+ }\r
+\r
+ public static String niceDateStamp(GregorianCalendar gc) {\r
+ return gc==null?"":niceDateFmt.format(gc.getTime());\r
+ }\r
+\r
+ public static String niceDateStamp(XMLGregorianCalendar xgc) {\r
+ return xgc==null?"":niceDateFmt.format(xgc.toGregorianCalendar().getTime());\r
+ }\r
+\r
+\r
+ ////////////////////// HELPFUL Strings\r
+ public static final String BAD_DIR_CHARS_REGEX = "[/:\\;.]";\r
+ public static final String SPLIT_DIR_REGEX = "/";\r
+\r
+ public static long firstMomentOfDay(long utc) {\r
+ GregorianCalendar begin = new GregorianCalendar();\r
+ begin.setTimeInMillis(utc);\r
+ return firstMomentOfDay(begin).getTimeInMillis();\r
+ } \r
+ \r
+ public static long lastMomentOfDay(long utc) {\r
+ GregorianCalendar end = new GregorianCalendar();\r
+ end.setTimeInMillis(utc);\r
+ return lastMomentOfDay(end).getTimeInMillis();\r
+ }\r
+\r
+ public static GregorianCalendar firstMomentOfDay(GregorianCalendar begin) {\r
+ if(begin==null)begin = new GregorianCalendar();\r
+ begin.set(GregorianCalendar.HOUR, 0);\r
+ begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);\r
+ begin.set(GregorianCalendar.MINUTE, 0);\r
+ begin.set(GregorianCalendar.SECOND, 0);\r
+ begin.set(GregorianCalendar.MILLISECOND, 0);\r
+ return begin;\r
+ } \r
+\r
+ public static GregorianCalendar lastMomentOfDay(GregorianCalendar end) {\r
+ if(end==null)end = new GregorianCalendar();\r
+ end.set(GregorianCalendar.HOUR, 11);\r
+ end.set(GregorianCalendar.MINUTE, 59);\r
+ end.set(GregorianCalendar.SECOND, 59);\r
+ end.set(GregorianCalendar.MILLISECOND, 999);\r
+ end.set(GregorianCalendar.AM_PM, GregorianCalendar.PM);\r
+ return end;\r
+ }\r
+\r
+ // UUID needs to be converted from UUID Epoch\r
+ public static final Date uuidToDate(UUID id) {\r
+ return new Date((id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000);\r
+ }\r
+\r
+ public static final long uuidToUnix(UUID id) {\r
+ return (id.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH)/10000;\r
+ }\r
+\r
+ public static float millisFromNanos(long start, long end) {\r
+ return (end - start) / 1000000f;\r
+ }\r
+\r
+\r
+ private static long sequence = new SecureRandom().nextInt();\r
+ private static synchronized long sequence() {\r
+ return ++sequence;\r
+ }\r
+ \r
+ public static final UUID dateToUUID(Date origTime) {\r
+ return dateToUUID(origTime.getTime());\r
+ }\r
+ \r
+ public static final UUID dateToUUID(long origTime) {\r
+ /*\r
+ * From Cassandra : http://wiki.apache.org/cassandra/FAQ\r
+ Magic number obtained from #cassandra's thobbs, who\r
+ claims to have stolen it from a Python library.\r
+ */\r
+ long time = origTime * 10000 + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH;\r
+ long timeLow = time & 0xffffffffL;\r
+ long timeMid = time & 0xffff00000000L;\r
+ long timeHi = time & 0xfff000000000000L;\r
+ long upperLong = (timeLow << 32) | (timeMid >> 16) | (1 << 12) | (timeHi >> 48) ;\r
+ return new java.util.UUID(upperLong, (0xC000000000000000L | sequence()));\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-public class DoubleOutputStream extends OutputStream {
- private OutputStream[] oss;
- private boolean[] close;
-
- /**
- * Create a Double Stream Writer
- * Some Streams should not be closed by this object (i.e. System.out), therefore, mark them with booleans
- */
- public DoubleOutputStream(OutputStream a, boolean closeA, OutputStream b, boolean closeB) {
- oss = new OutputStream[] {a,b};
- close = new boolean[] {closeA,closeB};
- }
-
- /**
- * Write a single character.
- * @throws IOException
- */
- @Override
- public void write(int c) throws IOException {
- for(OutputStream os : oss) {
- os.write(c);
- }
- }
-
- /**
- * Write a portion of an array of characters.
- *
- * @param bbuf Array of characters
- * @param off Offset from which to start writing characters
- * @param len Number of characters to write
- * @throws IOException
- */
- @Override
- public void write(byte bbuf[], int off, int len) throws IOException {
- for(OutputStream os : oss) {
- os.write(bbuf,off,len);
- }
- }
-
- @Override
- public void write(byte[] b) throws IOException {
- for(OutputStream os : oss) {
- os.write(b);
- }
- }
-
- /* (non-Javadoc)
- * @see java.io.OutputStream#close()
- */
- @Override
- public void close() throws IOException {
- for(int i=0;i<oss.length;++i) {
- if(close[i]) {
- oss[i].close();
- }
- }
- }
-
- /* (non-Javadoc)
- * @see java.io.OutputStream#flush()
- */
- @Override
- public void flush() throws IOException {
- for(OutputStream os : oss) {
- os.flush();
- }
- }
-
-
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.io.IOException;\r
+import java.io.OutputStream;\r
+\r
+public class DoubleOutputStream extends OutputStream {\r
+ private OutputStream[] oss;\r
+ private boolean[] close;\r
+\r
+ /**\r
+ * Create a Double Stream Writer\r
+ * Some Streams should not be closed by this object (i.e. System.out), therefore, mark them with booleans\r
+ */\r
+ public DoubleOutputStream(OutputStream a, boolean closeA, OutputStream b, boolean closeB) {\r
+ oss = new OutputStream[] {a,b};\r
+ close = new boolean[] {closeA,closeB};\r
+ }\r
+\r
+ /**\r
+ * Write a single character.\r
+ * @throws IOException \r
+ */\r
+ @Override\r
+ public void write(int c) throws IOException {\r
+ for(OutputStream os : oss) {\r
+ os.write(c);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Write a portion of an array of characters.\r
+ *\r
+ * @param bbuf Array of characters\r
+ * @param off Offset from which to start writing characters\r
+ * @param len Number of characters to write\r
+ * @throws IOException \r
+ */\r
+ @Override\r
+ public void write(byte bbuf[], int off, int len) throws IOException {\r
+ for(OutputStream os : oss) {\r
+ os.write(bbuf,off,len);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void write(byte[] b) throws IOException {\r
+ for(OutputStream os : oss) {\r
+ os.write(b);\r
+ }\r
+ }\r
+\r
+ /* (non-Javadoc)\r
+ * @see java.io.OutputStream#close()\r
+ */\r
+ @Override\r
+ public void close() throws IOException {\r
+ for(int i=0;i<oss.length;++i) {\r
+ if(close[i]) {\r
+ oss[i].close();\r
+ }\r
+ }\r
+ }\r
+\r
+ /* (non-Javadoc)\r
+ * @see java.io.OutputStream#flush()\r
+ */\r
+ @Override\r
+ public void flush() throws IOException {\r
+ for(OutputStream os : oss) {\r
+ os.flush();\r
+ }\r
+ }\r
+\r
+\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.util.regex.Pattern;
-
-public class IPValidator {
- private static final Pattern ipv4_p = Pattern.compile(
- "^((\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}\\2$"
- );
-
- private static final Pattern ipv6_p = Pattern.compile(
- "^(([0-9a-fA-F]{0,4})([:|.])){2,7}([0-9a-fA-F]{0,4})$"
- );
-
- private static final Pattern doubleColon = Pattern.compile(
- ".*::.*::.*"
- );
-
- private static final Pattern tooManyColon = Pattern.compile(
- "(.*:){1,7}"
- );
-
-
- public static boolean ipv4(String str) {
- return ipv4_p.matcher(str).matches();
- }
-
- public static boolean ipv6(String str) {
- return ipv6_p.matcher(str).matches() &&
- !doubleColon.matcher(str).matches() &&
- !tooManyColon.matcher(str).matches();
- }
-
- public static boolean ip (String str) {
- return ipv4_p.matcher(str).matches() || ipv6(str);
- }
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.util.regex.Pattern;\r
+\r
+public class IPValidator {\r
+ private static final Pattern ipv4_p = Pattern.compile(\r
+ "^((\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}\\2$"\r
+ );\r
+\r
+ private static final Pattern ipv6_p = Pattern.compile(\r
+ "^(([0-9a-fA-F]{0,4})([:|.])){2,7}([0-9a-fA-F]{0,4})$"\r
+ );\r
+ \r
+ private static final Pattern doubleColon = Pattern.compile(\r
+ ".*::.*::.*"\r
+ );\r
+\r
+ private static final Pattern tooManyColon = Pattern.compile(\r
+ "(.*:){1,7}"\r
+ );\r
+\r
+ \r
+ public static boolean ipv4(String str) {\r
+ return ipv4_p.matcher(str).matches();\r
+ }\r
+ \r
+ public static boolean ipv6(String str) {\r
+ return ipv6_p.matcher(str).matches() &&\r
+ !doubleColon.matcher(str).matches() &&\r
+ !tooManyColon.matcher(str).matches();\r
+ }\r
+ \r
+ public static boolean ip (String str) {\r
+ return ipv4_p.matcher(str).matches() || ipv6(str);\r
+ }\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.Writer;
-
-/**
- * @author Jonathan
- *
- * Catch \n and indent according to current indent levels of JavaGen
- */
-public class IndentPrintWriter extends PrintWriter {
- public static int INDENT = 2;
- private boolean addIndent;
- private int indent;
- private int col;
-
- public IndentPrintWriter(Writer out) {
- super(out);
- addIndent = false;
- indent = col = 0;
- }
-
- public IndentPrintWriter(OutputStream out) {
- super(out);
- addIndent = false;
- indent = col = 0;
- }
-
-
- public void write(String str) {
- int len = str.length();
- for(int i=0;i<len;++i) {
- write((int)str.charAt(i));
- }
- }
-
- public void println() {
- write((int)'\n');
- }
- public void write(String str, int off, int len) {
- len = Math.min(str.length(),off+len);
- for(int i=off;i<len;++i) {
- write((int)str.charAt(i));
- }
- }
- public void write(int b) {
- if (b == '\n') {
- addIndent = true;
- col = 0;
- } else if (addIndent) {
- addIndent = false;
- toIndent();
- } else {
- ++col;
- }
- super.write(b);
- }
-
- @Override
- public void write(char[] buf, int off, int len) {
- for (int i = 0; i < len; ++i)
- write(buf[i] + off);
- }
-
- public void setIndent(int size) {
- indent = size;
- }
-
- public void inc() {
- ++indent;
- }
-
- public void dec() {
- --indent;
- }
-
- public void toCol(int idx) {
- while(idx>col++)super.write((int)' ');
- }
-
- public int getIndent() {
- return indent;
- }
-
- public void toIndent() {
- int end = indent * INDENT;
- for (int i = 0; i < end; ++i) {
- super.write((int) ' ');
- }
- col = end;
- }
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.io.OutputStream;\r
+import java.io.PrintWriter;\r
+import java.io.Writer;\r
+\r
+/**\r
+ * @author Jonathan\r
+ * \r
+ * Catch \n and indent according to current indent levels of JavaGen\r
+ */\r
+public class IndentPrintWriter extends PrintWriter {\r
+ public static int INDENT = 2;\r
+ private boolean addIndent;\r
+ private int indent;\r
+ private int col;\r
+\r
+ public IndentPrintWriter(Writer out) {\r
+ super(out);\r
+ addIndent = false;\r
+ indent = col = 0;\r
+ }\r
+ \r
+ public IndentPrintWriter(OutputStream out) {\r
+ super(out);\r
+ addIndent = false;\r
+ indent = col = 0;\r
+ }\r
+\r
+\r
+ public void write(String str) {\r
+ int len = str.length();\r
+ for(int i=0;i<len;++i) {\r
+ write((int)str.charAt(i));\r
+ }\r
+ }\r
+ \r
+ public void println() {\r
+ write((int)'\n');\r
+ }\r
+ public void write(String str, int off, int len) {\r
+ len = Math.min(str.length(),off+len);\r
+ for(int i=off;i<len;++i) {\r
+ write((int)str.charAt(i));\r
+ }\r
+ }\r
+ public void write(int b) {\r
+ if (b == '\n') {\r
+ addIndent = true;\r
+ col = 0;\r
+ } else if (addIndent) {\r
+ addIndent = false;\r
+ toIndent();\r
+ } else {\r
+ ++col;\r
+ }\r
+ super.write(b);\r
+ }\r
+\r
+ @Override\r
+ public void write(char[] buf, int off, int len) {\r
+ for (int i = 0; i < len; ++i)\r
+ write(buf[i] + off);\r
+ }\r
+\r
+ public void setIndent(int size) {\r
+ indent = size;\r
+ }\r
+\r
+ public void inc() {\r
+ ++indent;\r
+ }\r
+ \r
+ public void dec() {\r
+ --indent;\r
+ }\r
+\r
+ public void toCol(int idx) {\r
+ while(idx>col++)super.write((int)' ');\r
+ }\r
+\r
+ public int getIndent() {\r
+ return indent;\r
+ }\r
+\r
+ public void toIndent() {\r
+ int end = indent * INDENT;\r
+ for (int i = 0; i < end; ++i) {\r
+ super.write((int) ' ');\r
+ }\r
+ col = end;\r
+ }\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-/*
- * Pool
- *
- * Author: Jonathan
- * 5/27/2011
- */
-package org.onap.aaf.misc.env.util;
-
-import java.util.LinkedList;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.LogTarget;
-
-/**
- * This Class pools on an As-Needed-Basis any particular kind of class, which is
- * quite suitable for expensive operations.
- *
- * The user calls "get" on a Pool, and if a waiting resource (T) is available,
- * it will be returned. Otherwise, one will be created with the "Creator" class
- * (must be defined for (T)).
- *
- * You can Prime the instances to avoid huge startup costs
- *
- * The returned "Pooled" object simply has to call "done()" and the object is
- * returned to the pool. If the developer does not return the object, a memory
- * leak does not occur. There are no references to the object once "get" is
- * called. However, the developer who does not return the object when done
- * obviates the point of the pool, as new Objects are created in place of the
- * Object not returned when another call to "get" is made.
- *
- * There is a cushion of extra objects, currently defaulted to MAX_RANGE. If the
- * items returned become higher than the MAX_RANGE, the object is allowed to go
- * out of scope, and be cleaned up. the default can be changed on a per-pool
- * basis.
- *
- *
- * @author Jonathan
- *
- * @param <T>
- */
-public class Pool<T> {
- /**
- * This is a constant which specified the default maximum number of unused
- * objects to be held at any given time.
- */
- private static final int MAX_RANGE = 6; // safety
-
- /**
- * only Simple List needed.
- *
- * NOTE TO MAINTAINERS: THIS OBJECT DOES IT'S OWN SYNCHRONIZATION. All
- * changes that touch list must account for correctly synchronizing list.
- */
- private LinkedList<Pooled<T>> list;
-
- /**
- * keep track of how many elements exist, to avoid asking list.
- */
- private int count;
-
- /**
- * Spares are those Object that are primed and ready to go.
- */
- private int spares;
-
- /**
- * Actual MAX number of spares allowed to hang around. Can be set to
- * something besides the default MAX_RANGE.
- */
- private int max_range = MAX_RANGE;
-
- /**
- * The Creator for this particular pool. It must work for type T.
- */
- private Creator<T> creator;
-
- /**
- * Create a new Pool, given the implementation of Creator<T>, which must be
- * able to create/destroy T objects at will.
- *
- * @param creator
- */
- public Pool(Creator<T> creator) {
- count = spares = 0;
- this.creator = creator;
- list = new LinkedList<Pooled<T>>();
- }
-
- /**
- * Preallocate a certain number of T Objects. Useful for services so that
- * the first transactions don't get hit with all the Object creation costs
- *
- * @param lt
- * @param prime
- * @throws APIException
- */
- public void prime(LogTarget lt, int prime) throws APIException {
- for (int i = 0; i < prime; ++i) {
- Pooled<T> pt = new Pooled<T>(creator.create(), this, lt);
- synchronized (list) {
- list.addFirst(pt);
- ++count;
- }
- }
-
- }
-
- /**
- * Destroy and remove all remaining objects. This is valuable for closing
- * down all Allocated objects cleanly for exiting. It is also a good method
- * for removing objects when, for instance, all Objects are invalid because
- * of broken connections, etc.
- */
- public void drain() {
- synchronized (list) {
- for (int i = 0; i < list.size(); ++i) {
- Pooled<T> pt = list.remove();
- creator.destroy(pt.content);
- pt.logTarget.log("Pool drained ", creator.toString());
- }
- count = spares = 0;
- }
-
- }
-
- /**
- * This is the essential function for Pool. Get an Object "T" inside a
- * "Pooled<T>" object. If there is a spare Object, then use it. If not, then
- * create and pass back.
- *
- * This one uses a Null LogTarget
- *
- * IMPORTANT: When the use of this object is done (and the object is still
- * in a valid state), then "done()" should be called immediately to allow
- * the object to be reused. That is the point of the Pool...
- *
- * If the Object is in an invalid state, then "toss()" should be used so the
- * Pool doesn't pass on invalid objects to others.
- *
- * @param lt
- * @return
- * @throws APIException
- */
- public Pooled<T> get() throws APIException {
- Pooled<T> pt;
- synchronized (list) {
- if (list.isEmpty()) {
- pt = null;
- } else {
- pt = list.removeLast();
- --count;
- creator.reuse(pt.content);
- }
- }
- if (pt == null) {
- if (spares < max_range)
- ++spares;
- pt = new Pooled<T>(creator.create(), this, LogTarget.NULL);
- } else {
- if (spares > 1)
- --spares;
- }
- return pt;
- }
-
- /**
- * This is the essential function for Pool. Get an Object "T" inside a
- * "Pooled<T>" object. If there is a spare Object, then use it. If not, then
- * create and pass back.
- *
- * If you don't have access to a LogTarget from Env, use LogTarget.NULL
- *
- * IMPORTANT: When the use of this object is done (and the object is still
- * in a valid state), then "done()" should be called immediately to allow
- * the object to be reused. That is the point of the Pool...
- *
- * If the Object is in an invalid state, then "toss()" should be used so the
- * Pool doesn't pass on invalid objects to others.
- *
- * @param lt
- * @return
- * @throws APIException
- */
- public Pooled<T> get(LogTarget lt) throws APIException {
- Pooled<T> pt;
- synchronized (list) {
- if (list.isEmpty()) {
- pt = null;
- } else {
- pt = list.remove();
- --count;
- creator.reuse(pt.content);
- }
- }
- if (pt == null) {
- if (spares < max_range)
- ++spares;
- pt = new Pooled<T>(creator.create(), this, lt);
- lt.log("Pool created ", creator.toString());
- } else {
- if (spares > 1)
- --spares;
- }
- return pt;
- }
-
- /**
- * This function will validate whether the Objects are still in a usable
- * state. If not, they are tossed from the Pool. This is valuable to have
- * when Remote Connections go down, and there is a question on whether the
- * Pooled Objects are still functional.
- *
- * @return
- */
- public boolean validate() {
- boolean rv = true;
- synchronized (list) {
- for (Pooled<T> t : list) {
- if (!creator.isValid(t.content)) {
- rv = false;
- t.toss();
- list.remove(t);
- }
- }
- }
- return rv;
- }
-
- /**
- * This is an internal method, used only by the Internal Pooled<T> class.
- *
- * The Pooled<T> class "offers" it's Object back after use. It is an
- * "offer", because Pool will simply destroy and remove the object if it has
- * more than enough spares.
- *
- * @param lt
- * @param used
- * @return
- */
- // Used only by Pooled<T>
- private boolean offer(LogTarget lt, Pooled<T> used) {
- if (count < spares) {
- synchronized (list) {
- list.addFirst(used);
- ++count;
- }
- lt.log("Pool recovered ", creator.toString());
- } else {
- lt.log("Pool destroyed ", creator.toString());
- creator.destroy(used.content);
- }
- return false;
- }
-
- /**
- * The Creator Interface give the Pool the ability to Create, Destroy and
- * Validate the Objects it is maintaining. Thus, it is a specially written
- * Implementation for each type.
- *
- * @author Jonathan
- *
- * @param <T>
- */
- public interface Creator<T> {
- public T create() throws APIException;
-
- public void destroy(T t);
-
- public boolean isValid(T t);
-
- public void reuse(T t);
- }
-
- /**
- * The "Pooled<T>" class is the transient class that wraps the actual Object
- * T for API use/ It gives the ability to return ("done()", or "toss()") the
- * Object to the Pool when processing is finished.
- *
- * For Safety, i.e. to avoid memory leaks and invalid Object States, there
- * is a "finalize" method. It is strictly for when coder forgets to return
- * the object, or perhaps hasn't covered the case during Exceptions or
- * Runtime Exceptions with finally (preferred). This should not be
- * considered normal procedure, as finalize() is called at an undetermined
- * time during garbage collection, and is thus rather useless for a Pool.
- * However, we don't want Coding Mistakes to put the whole program in an
- * invalid state, so if something happened such that "done()" or "toss()"
- * were not called, the resource is still cleaned up as well as possible.
- *
- * @author Jonathan
- *
- * @param <T>
- */
- public static class Pooled<T> {
- public final T content;
- private Pool<T> pool;
- protected LogTarget logTarget;
-
- /**
- * Create the Wrapping Object Pooled<T>.
- *
- * @param t
- * @param pool
- * @param logTarget
- */
- public Pooled(T t, Pool<T> pool, LogTarget logTarget) {
- content = t;
- this.pool = pool;
- this.logTarget = logTarget;
- }
-
- /**
- * This is the key API for the Pool, as calling "done()" offers this
- * object back to the Pool for reuse.
- *
- * Do not use the Pooled<T> object again after calling "done()".
- */
- public void done() {
- if (pool != null) {
- pool.offer(logTarget, this);
- }
- }
-
- /**
- * The user of the Object may discover that the Object t is no longer in
- * a valid state. Don't put Garbage back in the Refrigerator... Toss it,
- * if it's no longer valid.
- *
- * toss() is also used for draining the Pool, etc.
- *
- * toss() will attempt to destroy the Object by using the Creator
- * Interface.
- *
- */
- public void toss() {
- if (pool != null) {
- pool.creator.destroy(content);
- }
- // Don't allow finalize to put it back in.
- pool = null;
- }
-
- /**
- * Just in case someone neglected to offer back object... Do not rely on
- * this, as there is no specific time when finalize is called, which
- * rather defeats the purpose of a Pool.
- */
- @Override
- protected void finalize() throws Throwable {
- if (pool != null) {
- done();
- pool = null;
- }
- }
- }
-
- /**
- * Get the maximum number of spare objects allowed at any moment
- *
- * @return
- */
- public int getMaxRange() {
- return max_range;
- }
-
- /**
- * Set a Max Range for numbers of spare objects waiting to be used.
- *
- * No negative numbers are allowed
- *
- * @return
- */
- public void setMaxRange(int max_range) {
- // Do not allow negative numbers
- this.max_range = Math.max(0, max_range);
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+/*\r
+ * Pool\r
+ * \r
+ * Author: Jonathan\r
+ * 5/27/2011\r
+ */\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.util.LinkedList;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+\r
+/**\r
+ * This Class pools on an As-Needed-Basis any particular kind of class, which is\r
+ * quite suitable for expensive operations.\r
+ * \r
+ * The user calls "get" on a Pool, and if a waiting resource (T) is available,\r
+ * it will be returned. Otherwise, one will be created with the "Creator" class\r
+ * (must be defined for (T)).\r
+ * \r
+ * You can Prime the instances to avoid huge startup costs\r
+ * \r
+ * The returned "Pooled" object simply has to call "done()" and the object is\r
+ * returned to the pool. If the developer does not return the object, a memory\r
+ * leak does not occur. There are no references to the object once "get" is\r
+ * called. However, the developer who does not return the object when done\r
+ * obviates the point of the pool, as new Objects are created in place of the\r
+ * Object not returned when another call to "get" is made.\r
+ * \r
+ * There is a cushion of extra objects, currently defaulted to MAX_RANGE. If the\r
+ * items returned become higher than the MAX_RANGE, the object is allowed to go\r
+ * out of scope, and be cleaned up. the default can be changed on a per-pool\r
+ * basis.\r
+ * \r
+ * \r
+ * @author Jonathan\r
+ * \r
+ * @param <T>\r
+ */\r
+public class Pool<T> {\r
+ /**\r
+ * This is a constant which specified the default maximum number of unused\r
+ * objects to be held at any given time.\r
+ */\r
+ private static final int MAX_RANGE = 6; // safety\r
+\r
+ /**\r
+ * only Simple List needed.\r
+ * \r
+ * NOTE TO MAINTAINERS: THIS OBJECT DOES IT'S OWN SYNCHRONIZATION. All\r
+ * changes that touch list must account for correctly synchronizing list.\r
+ */\r
+ private LinkedList<Pooled<T>> list;\r
+\r
+ /**\r
+ * keep track of how many elements exist, to avoid asking list.\r
+ */\r
+ private int count;\r
+\r
+ /**\r
+ * Spares are those Object that are primed and ready to go.\r
+ */\r
+ private int spares;\r
+\r
+ /**\r
+ * Actual MAX number of spares allowed to hang around. Can be set to\r
+ * something besides the default MAX_RANGE.\r
+ */\r
+ private int max_range = MAX_RANGE;\r
+\r
+ /**\r
+ * The Creator for this particular pool. It must work for type T.\r
+ */\r
+ private Creator<T> creator;\r
+\r
+ /**\r
+ * Create a new Pool, given the implementation of Creator<T>, which must be\r
+ * able to create/destroy T objects at will.\r
+ * \r
+ * @param creator\r
+ */\r
+ public Pool(Creator<T> creator) {\r
+ count = spares = 0;\r
+ this.creator = creator;\r
+ list = new LinkedList<Pooled<T>>();\r
+ }\r
+\r
+ /**\r
+ * Preallocate a certain number of T Objects. Useful for services so that\r
+ * the first transactions don't get hit with all the Object creation costs\r
+ * \r
+ * @param lt\r
+ * @param prime\r
+ * @throws APIException\r
+ */\r
+ public void prime(LogTarget lt, int prime) throws APIException {\r
+ for (int i = 0; i < prime; ++i) {\r
+ Pooled<T> pt = new Pooled<T>(creator.create(), this, lt);\r
+ synchronized (list) {\r
+ list.addFirst(pt);\r
+ ++count;\r
+ }\r
+ }\r
+\r
+ }\r
+\r
+ /**\r
+ * Destroy and remove all remaining objects. This is valuable for closing\r
+ * down all Allocated objects cleanly for exiting. It is also a good method\r
+ * for removing objects when, for instance, all Objects are invalid because\r
+ * of broken connections, etc.\r
+ */\r
+ public void drain() {\r
+ synchronized (list) {\r
+ for (int i = 0; i < list.size(); ++i) {\r
+ Pooled<T> pt = list.remove();\r
+ creator.destroy(pt.content);\r
+ pt.logTarget.log("Pool drained ", creator.toString());\r
+ }\r
+ count = spares = 0;\r
+ }\r
+\r
+ }\r
+\r
+ /**\r
+ * This is the essential function for Pool. Get an Object "T" inside a\r
+ * "Pooled<T>" object. If there is a spare Object, then use it. If not, then\r
+ * create and pass back.\r
+ * \r
+ * This one uses a Null LogTarget\r
+ * \r
+ * IMPORTANT: When the use of this object is done (and the object is still\r
+ * in a valid state), then "done()" should be called immediately to allow\r
+ * the object to be reused. That is the point of the Pool...\r
+ * \r
+ * If the Object is in an invalid state, then "toss()" should be used so the\r
+ * Pool doesn't pass on invalid objects to others.\r
+ * \r
+ * @param lt\r
+ * @return\r
+ * @throws APIException\r
+ */\r
+ public Pooled<T> get() throws APIException {\r
+ Pooled<T> pt;\r
+ synchronized (list) {\r
+ if (list.isEmpty()) {\r
+ pt = null;\r
+ } else {\r
+ pt = list.removeLast();\r
+ --count;\r
+ creator.reuse(pt.content);\r
+ }\r
+ }\r
+ if (pt == null) {\r
+ if (spares < max_range)\r
+ ++spares;\r
+ pt = new Pooled<T>(creator.create(), this, LogTarget.NULL);\r
+ } else {\r
+ if (spares > 1)\r
+ --spares;\r
+ }\r
+ return pt;\r
+ }\r
+\r
+ /**\r
+ * This is the essential function for Pool. Get an Object "T" inside a\r
+ * "Pooled<T>" object. If there is a spare Object, then use it. If not, then\r
+ * create and pass back.\r
+ * \r
+ * If you don't have access to a LogTarget from Env, use LogTarget.NULL\r
+ * \r
+ * IMPORTANT: When the use of this object is done (and the object is still\r
+ * in a valid state), then "done()" should be called immediately to allow\r
+ * the object to be reused. That is the point of the Pool...\r
+ * \r
+ * If the Object is in an invalid state, then "toss()" should be used so the\r
+ * Pool doesn't pass on invalid objects to others.\r
+ * \r
+ * @param lt\r
+ * @return\r
+ * @throws APIException\r
+ */\r
+ public Pooled<T> get(LogTarget lt) throws APIException {\r
+ Pooled<T> pt;\r
+ synchronized (list) {\r
+ if (list.isEmpty()) {\r
+ pt = null;\r
+ } else {\r
+ pt = list.remove();\r
+ --count;\r
+ creator.reuse(pt.content);\r
+ }\r
+ }\r
+ if (pt == null) {\r
+ if (spares < max_range)\r
+ ++spares;\r
+ pt = new Pooled<T>(creator.create(), this, lt);\r
+ lt.log("Pool created ", creator.toString());\r
+ } else {\r
+ if (spares > 1)\r
+ --spares;\r
+ }\r
+ return pt;\r
+ }\r
+\r
+ /**\r
+ * This function will validate whether the Objects are still in a usable\r
+ * state. If not, they are tossed from the Pool. This is valuable to have\r
+ * when Remote Connections go down, and there is a question on whether the\r
+ * Pooled Objects are still functional.\r
+ * \r
+ * @return\r
+ */\r
+ public boolean validate() {\r
+ boolean rv = true;\r
+ synchronized (list) {\r
+ for (Pooled<T> t : list) {\r
+ if (!creator.isValid(t.content)) {\r
+ rv = false;\r
+ t.toss();\r
+ list.remove(t);\r
+ }\r
+ }\r
+ }\r
+ return rv;\r
+ }\r
+\r
+ /**\r
+ * This is an internal method, used only by the Internal Pooled<T> class.\r
+ * \r
+ * The Pooled<T> class "offers" it's Object back after use. It is an\r
+ * "offer", because Pool will simply destroy and remove the object if it has\r
+ * more than enough spares.\r
+ * \r
+ * @param lt\r
+ * @param used\r
+ * @return\r
+ */\r
+ // Used only by Pooled<T>\r
+ private boolean offer(LogTarget lt, Pooled<T> used) {\r
+ if (count < spares) {\r
+ synchronized (list) {\r
+ list.addFirst(used);\r
+ ++count;\r
+ }\r
+ lt.log("Pool recovered ", creator.toString());\r
+ } else {\r
+ lt.log("Pool destroyed ", creator.toString());\r
+ creator.destroy(used.content);\r
+ }\r
+ return false;\r
+ }\r
+\r
+ /**\r
+ * The Creator Interface give the Pool the ability to Create, Destroy and\r
+ * Validate the Objects it is maintaining. Thus, it is a specially written\r
+ * Implementation for each type.\r
+ * \r
+ * @author Jonathan\r
+ * \r
+ * @param <T>\r
+ */\r
+ public interface Creator<T> {\r
+ public T create() throws APIException;\r
+\r
+ public void destroy(T t);\r
+\r
+ public boolean isValid(T t);\r
+\r
+ public void reuse(T t);\r
+ }\r
+\r
+ /**\r
+ * The "Pooled<T>" class is the transient class that wraps the actual Object\r
+ * T for API use/ It gives the ability to return ("done()", or "toss()") the\r
+ * Object to the Pool when processing is finished.\r
+ * \r
+ * For Safety, i.e. to avoid memory leaks and invalid Object States, there\r
+ * is a "finalize" method. It is strictly for when coder forgets to return\r
+ * the object, or perhaps hasn't covered the case during Exceptions or\r
+ * Runtime Exceptions with finally (preferred). This should not be\r
+ * considered normal procedure, as finalize() is called at an undetermined\r
+ * time during garbage collection, and is thus rather useless for a Pool.\r
+ * However, we don't want Coding Mistakes to put the whole program in an\r
+ * invalid state, so if something happened such that "done()" or "toss()"\r
+ * were not called, the resource is still cleaned up as well as possible.\r
+ * \r
+ * @author Jonathan\r
+ * \r
+ * @param <T>\r
+ */\r
+ public static class Pooled<T> {\r
+ public final T content;\r
+ private Pool<T> pool;\r
+ protected LogTarget logTarget;\r
+\r
+ /**\r
+ * Create the Wrapping Object Pooled<T>.\r
+ * \r
+ * @param t\r
+ * @param pool\r
+ * @param logTarget\r
+ */\r
+ public Pooled(T t, Pool<T> pool, LogTarget logTarget) {\r
+ content = t;\r
+ this.pool = pool;\r
+ this.logTarget = logTarget;\r
+ }\r
+\r
+ /**\r
+ * This is the key API for the Pool, as calling "done()" offers this\r
+ * object back to the Pool for reuse.\r
+ * \r
+ * Do not use the Pooled<T> object again after calling "done()".\r
+ */\r
+ public void done() {\r
+ if (pool != null) {\r
+ pool.offer(logTarget, this);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * The user of the Object may discover that the Object t is no longer in\r
+ * a valid state. Don't put Garbage back in the Refrigerator... Toss it,\r
+ * if it's no longer valid.\r
+ * \r
+ * toss() is also used for draining the Pool, etc.\r
+ * \r
+ * toss() will attempt to destroy the Object by using the Creator\r
+ * Interface.\r
+ * \r
+ */\r
+ public void toss() {\r
+ if (pool != null) {\r
+ pool.creator.destroy(content);\r
+ }\r
+ // Don't allow finalize to put it back in.\r
+ pool = null;\r
+ }\r
+\r
+ /**\r
+ * Just in case someone neglected to offer back object... Do not rely on\r
+ * this, as there is no specific time when finalize is called, which\r
+ * rather defeats the purpose of a Pool.\r
+ */\r
+ @Override\r
+ protected void finalize() throws Throwable {\r
+ if (pool != null) {\r
+ done();\r
+ pool = null;\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Get the maximum number of spare objects allowed at any moment\r
+ * \r
+ * @return\r
+ */\r
+ public int getMaxRange() {\r
+ return max_range;\r
+ }\r
+\r
+ /**\r
+ * Set a Max Range for numbers of spare objects waiting to be used.\r
+ * \r
+ * No negative numbers are allowed\r
+ * \r
+ * @return\r
+ */\r
+ public void setMaxRange(int max_range) {\r
+ // Do not allow negative numbers\r
+ this.max_range = Math.max(0, max_range);\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.onap.aaf.misc.env.APIException;
-import org.onap.aaf.misc.env.Creatable;
-import org.onap.aaf.misc.env.Env;
-import org.onap.aaf.misc.env.LifeCycle;
-
-
-/**
- * <h1>RefreshableThreadObject</h1>
- * This is a ThreadLocal like implementation, but it responds to
- * the {@link LifeCycle} mechanism for configuration refreshes, and
- * implements {@link Creatable} (for use in destroy, etc).<p>
- *
- * In addition to the Thread instance semantics, it compares when the object
- * was created versus the last "refresh(env)" call when getting, for the
- * thread, and if necessary to replace the created object, destroying the
- * previous.<p>
- *
- * In most cases, it's better to use the new "Pool" mechanism, as it deals with
- * gaining and returning resources on an as needed basis. This, however, remains
- * in the cases where specific Objects need to be retained to specific Threads.<p>
- *
- * There is no way to do this kind of specialized behavior in ThreadLocal.
- *
- * @author Jonathan
- *
- * @param <T>
- */
-public class RefreshableThreadObject<T extends Creatable<T>> {
- private Map<Thread,T> objs;
- private long refreshed;
- private Constructor<T> cnst;
-
- /**
- * The passed in class <b>must</b> implement the constructor
- * <pre>
- * public MyClass(Env env) {
- * ...
- * }
- * </pre>
- * @param clss
- * @throws APIException
- */
- public RefreshableThreadObject(Class<T> clss) throws APIException {
- objs = new ConcurrentHashMap<Thread,T>();
- try {
- cnst = clss.getConstructor(new Class[]{Env.class} );
- } catch (Exception e) {
- throw new APIException(e);
- }
- }
-
- /**
- * Get the "T" class from the current thread
- *
- * @param env
- * @return T
- * @throws APIException
- */
- public T get(Env env) throws APIException {
- Thread t = Thread.currentThread();
- T obj = objs.get(t);
- if(obj==null || refreshed>obj.created()) {
- try {
- obj = cnst.newInstance(new Object[]{env});
- } catch (InvocationTargetException e) {
- throw new APIException(e.getTargetException());
- } catch (Exception e) {
- throw new APIException(e);
- }
- T destroyMe = objs.put(t,obj);
- if(destroyMe!=null) {
- destroyMe.destroy(env);
- }
- }
- return obj;
- }
-
- /**
- * Mark the timestamp of refreshed.
- *
- * @param env
- */
- public void refresh(Env env) {
- refreshed = System.currentTimeMillis();
- }
-
- /**
- * Remove the object from the Thread instances
- * @param env
- */
- public void remove(Env env) {
- T obj = objs.remove(Thread.currentThread());
- if(obj!=null)
- obj.destroy(env);
- }
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.lang.reflect.Constructor;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.util.Map;\r
+import java.util.concurrent.ConcurrentHashMap;\r
+\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Creatable;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.LifeCycle;\r
+\r
+\r
+/**\r
+ * <h1>RefreshableThreadObject</h1>\r
+ * This is a ThreadLocal like implementation, but it responds to \r
+ * the {@link LifeCycle} mechanism for configuration refreshes, and \r
+ * implements {@link Creatable} (for use in destroy, etc).<p>\r
+ * \r
+ * In addition to the Thread instance semantics, it compares when the object\r
+ * was created versus the last "refresh(env)" call when getting, for the\r
+ * thread, and if necessary to replace the created object, destroying the \r
+ * previous.<p>\r
+ * \r
+ * In most cases, it's better to use the new "Pool" mechanism, as it deals with \r
+ * gaining and returning resources on an as needed basis. This, however, remains\r
+ * in the cases where specific Objects need to be retained to specific Threads.<p>\r
+ * \r
+ * There is no way to do this kind of specialized behavior in ThreadLocal.\r
+ * \r
+ * @author Jonathan\r
+ *\r
+ * @param <T>\r
+ */\r
+public class RefreshableThreadObject<T extends Creatable<T>> {\r
+ private Map<Thread,T> objs;\r
+ private long refreshed;\r
+ private Constructor<T> cnst;\r
+ \r
+ /**\r
+ * The passed in class <b>must</b> implement the constructor\r
+ * <pre>\r
+ * public MyClass(Env env) {\r
+ * ...\r
+ * }\r
+ * </pre>\r
+ * @param clss\r
+ * @throws APIException\r
+ */\r
+ public RefreshableThreadObject(Class<T> clss) throws APIException {\r
+ objs = new ConcurrentHashMap<Thread,T>();\r
+ try {\r
+ cnst = clss.getConstructor(new Class[]{Env.class} );\r
+ } catch (Exception e) {\r
+ throw new APIException(e);\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Get the "T" class from the current thread\r
+ * \r
+ * @param env\r
+ * @return T\r
+ * @throws APIException\r
+ */\r
+ public T get(Env env) throws APIException {\r
+ Thread t = Thread.currentThread();\r
+ T obj = objs.get(t);\r
+ if(obj==null || refreshed>obj.created()) {\r
+ try {\r
+ obj = cnst.newInstance(new Object[]{env});\r
+ } catch (InvocationTargetException e) {\r
+ throw new APIException(e.getTargetException());\r
+ } catch (Exception e) {\r
+ throw new APIException(e);\r
+ }\r
+ T destroyMe = objs.put(t,obj);\r
+ if(destroyMe!=null) {\r
+ destroyMe.destroy(env);\r
+ }\r
+ } \r
+ return obj;\r
+ }\r
+ \r
+ /**\r
+ * Mark the timestamp of refreshed.\r
+ * \r
+ * @param env\r
+ */\r
+ public void refresh(Env env) {\r
+ refreshed = System.currentTimeMillis();\r
+ }\r
+ \r
+ /**\r
+ * Remove the object from the Thread instances\r
+ * @param env\r
+ */\r
+ public void remove(Env env) {\r
+ T obj = objs.remove(Thread.currentThread());\r
+ if(obj!=null)\r
+ obj.destroy(env);\r
+ }\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-/**
- * Split by Char, optional Trim
- *
- * Note: I read the String split and Pattern split code, and we can do this more efficiently for a single Character
- *
- * Jonathan 8/20/2015
- */
-
-public class Split {
- public static String[] split(char c, String value) {
- // Count items to preallocate Array (memory alloc is more expensive than counting twice)
- int count,idx;
- for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);
- String[] rv = new String[count];
- if(count==1) {
- rv[0]=value;
- } else {
- int last=0;
- count=-1;
- for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {
- rv[++count]=value.substring(last,idx);
- last = ++idx;
- }
- rv[++count]=value.substring(last);
- }
- return rv;
- }
-
- public static String[] splitTrim(char c, String value) {
- // Count items to preallocate Array (memory alloc is more expensive than counting twice)
- int count,idx;
- for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);
- String[] rv = new String[count];
- if(count==1) {
- rv[0]=value.trim();
- } else {
- int last=0;
- count=-1;
- for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {
- rv[++count]=value.substring(last,idx).trim();
- last = ++idx;
- }
- rv[++count]=value.substring(last).trim();
- }
- return rv;
- }
-
- public static String[] splitTrim(char c, String value, int size) {
- int idx;
- String[] rv = new String[size];
- if(size==1) {
- rv[0]=value.trim();
- } else {
- int last=0;
- int count=-1;
- size-=2;
- for(idx=value.indexOf(c);idx>=0 && count<size;idx=value.indexOf(c,idx)) {
- rv[++count]=value.substring(last,idx).trim();
- last = ++idx;
- }
- rv[++count]=value.substring(last).trim();
- }
- return rv;
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+/**\r
+ * Split by Char, optional Trim\r
+ * \r
+ * Note: I read the String split and Pattern split code, and we can do this more efficiently for a single Character\r
+ * \r
+ * Jonathan 8/20/2015\r
+ */\r
+\r
+public class Split {\r
+ public static String[] split(char c, String value) {\r
+ // Count items to preallocate Array (memory alloc is more expensive than counting twice)\r
+ int count,idx;\r
+ for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);\r
+ String[] rv = new String[count];\r
+ if(count==1) {\r
+ rv[0]=value;\r
+ } else {\r
+ int last=0;\r
+ count=-1;\r
+ for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {\r
+ rv[++count]=value.substring(last,idx);\r
+ last = ++idx;\r
+ }\r
+ rv[++count]=value.substring(last);\r
+ }\r
+ return rv;\r
+ }\r
+\r
+ public static String[] splitTrim(char c, String value) {\r
+ // Count items to preallocate Array (memory alloc is more expensive than counting twice)\r
+ int count,idx;\r
+ for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);\r
+ String[] rv = new String[count];\r
+ if(count==1) {\r
+ rv[0]=value.trim();\r
+ } else {\r
+ int last=0;\r
+ count=-1;\r
+ for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {\r
+ rv[++count]=value.substring(last,idx).trim();\r
+ last = ++idx;\r
+ }\r
+ rv[++count]=value.substring(last).trim();\r
+ }\r
+ return rv;\r
+ }\r
+\r
+ public static String[] splitTrim(char c, String value, int size) {\r
+ int idx;\r
+ String[] rv = new String[size];\r
+ if(size==1) {\r
+ rv[0]=value.trim();\r
+ } else {\r
+ int last=0;\r
+ int count=-1;\r
+ size-=2;\r
+ for(idx=value.indexOf(c);idx>=0 && count<size;idx=value.indexOf(c,idx)) {\r
+ rv[++count]=value.substring(last,idx).trim();\r
+ last = ++idx;\r
+ }\r
+ rv[++count]=value.substring(last).trim();\r
+ }\r
+ return rv;\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-public class StringBuilderOutputStream extends OutputStream {
- private StringBuilder buf;
-
-
- /**
- * Create a new string writer using the default initial string-buffer
- * size.
- */
- public StringBuilderOutputStream() {
- buf = new StringBuilder();
- }
-
- /**
- * Create a new string writer using a passed in StringBuilder
- * size.
- */
- public StringBuilderOutputStream(StringBuilder sb) {
- buf = sb;
- }
-
- /**
- * Create a new string writer using the specified initial string-buffer
- * size.
- *
- * @param initialSize
- * The number of <tt>byte</tt> values that will fit into this buffer
- * before it is automatically expanded
- *
- * @throws IllegalArgumentException
- * If <tt>initialSize</tt> is negative
- */
- public StringBuilderOutputStream(int initialSize) {
- if (initialSize < 0) {
- throw new IllegalArgumentException("Negative buffer size");
- }
- buf = new StringBuilder(initialSize);
- }
-
- /**
- * Write a single character.
- */
- public void write(int c) {
- buf.append((byte) c);
- }
-
- /**
- * Write a portion of an array of characters.
- *
- * @param bbuf Array of characters
- * @param off Offset from which to start writing characters
- * @param len Number of characters to write
- */
-
- public void write(byte bbuf[], int off, int len) {
- if ((off < 0) || (off > bbuf.length) || (len < 0) ||
- ((off + len) > bbuf.length) || ((off + len) < 0)) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0) {
- return;
- }
- buf.append(new String(bbuf, off, len));
- }
-
- @Override
- public void write(byte[] b) throws IOException {
- buf.append(new String(b));
- }
-
- /**
- * Write a string.
- */
- public void write(String str) {
- buf.append(str);
- }
-
- /**
- * Write a portion of a string.
- *
- * @param str String to be written
- * @param off Offset from which to start writing characters
- * @param len Number of characters to write
- */
- public void write(String str, int off, int len) {
- buf.append(str,off,len);
- }
-
- public StringBuilderOutputStream append(CharSequence csq) {
- if (csq == null) {
- write("null");
- } else {
- for(int i = 0;i<csq.length();++i) {
- buf.append(csq.charAt(i));
- }
- }
- return this;
- }
-
- public StringBuilderOutputStream append(CharSequence csq, int start, int end) {
- CharSequence cs = (csq == null ? "null" : csq);
- return append(cs.subSequence(start, end));
- }
-
- /**
- * Appends the specified character to this writer.
- *
- * <p> An invocation of this method of the form <tt>out.append(c)</tt>
- * behaves in exactly the same way as the invocation
- *
- * <pre>
- * out.write(c) </pre>
- *
- * @param c
- * The 16-bit character to append
- *
- * @return This writer
- *
- * @since 1.5
- */
- public StringBuilderOutputStream append(byte c) {
- buf.append(c);
- return this;
- }
-
- /**
- * Return the buffer's current value as a string.
- */
- public String toString() {
- return buf.toString();
- }
-
- /**
- * Return the string buffer itself.
- *
- * @return StringBuffer holding the current buffer value.
- */
- public StringBuilder getBuffer() {
- return buf;
- }
-
- public void reset() {
- buf.setLength(0);
- }
-
- @Override
- public void flush() throws IOException {
- }
-
- @Override
- public void close() throws IOException {
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.io.IOException;\r
+import java.io.OutputStream;\r
+\r
+public class StringBuilderOutputStream extends OutputStream {\r
+ private StringBuilder buf;\r
+\r
+\r
+ /**\r
+ * Create a new string writer using the default initial string-buffer\r
+ * size.\r
+ */\r
+ public StringBuilderOutputStream() {\r
+ buf = new StringBuilder();\r
+ }\r
+\r
+ /**\r
+ * Create a new string writer using a passed in StringBuilder\r
+ * size.\r
+ */\r
+ public StringBuilderOutputStream(StringBuilder sb) {\r
+ buf = sb;\r
+ }\r
+\r
+ /**\r
+ * Create a new string writer using the specified initial string-buffer\r
+ * size.\r
+ *\r
+ * @param initialSize\r
+ * The number of <tt>byte</tt> values that will fit into this buffer\r
+ * before it is automatically expanded\r
+ *\r
+ * @throws IllegalArgumentException\r
+ * If <tt>initialSize</tt> is negative\r
+ */\r
+ public StringBuilderOutputStream(int initialSize) {\r
+ if (initialSize < 0) {\r
+ throw new IllegalArgumentException("Negative buffer size");\r
+ }\r
+ buf = new StringBuilder(initialSize);\r
+ }\r
+\r
+ /**\r
+ * Write a single character.\r
+ */\r
+ public void write(int c) {\r
+ buf.append((byte) c);\r
+ }\r
+\r
+ /**\r
+ * Write a portion of an array of characters.\r
+ *\r
+ * @param bbuf Array of characters\r
+ * @param off Offset from which to start writing characters\r
+ * @param len Number of characters to write\r
+ */\r
+ \r
+ public void write(byte bbuf[], int off, int len) {\r
+ if ((off < 0) || (off > bbuf.length) || (len < 0) ||\r
+ ((off + len) > bbuf.length) || ((off + len) < 0)) {\r
+ throw new IndexOutOfBoundsException();\r
+ } else if (len == 0) {\r
+ return;\r
+ }\r
+ buf.append(new String(bbuf, off, len));\r
+ }\r
+\r
+ @Override\r
+ public void write(byte[] b) throws IOException {\r
+ buf.append(new String(b));\r
+ }\r
+\r
+ /**\r
+ * Write a string.\r
+ */\r
+ public void write(String str) {\r
+ buf.append(str);\r
+ }\r
+\r
+ /**\r
+ * Write a portion of a string.\r
+ *\r
+ * @param str String to be written\r
+ * @param off Offset from which to start writing characters\r
+ * @param len Number of characters to write\r
+ */\r
+ public void write(String str, int off, int len) {\r
+ buf.append(str,off,len);\r
+ }\r
+\r
+ public StringBuilderOutputStream append(CharSequence csq) {\r
+ if (csq == null) {\r
+ write("null");\r
+ } else {\r
+ for(int i = 0;i<csq.length();++i) {\r
+ buf.append(csq.charAt(i));\r
+ }\r
+ }\r
+ return this;\r
+ }\r
+\r
+ public StringBuilderOutputStream append(CharSequence csq, int start, int end) {\r
+ CharSequence cs = (csq == null ? "null" : csq);\r
+ return append(cs.subSequence(start, end));\r
+ }\r
+\r
+ /**\r
+ * Appends the specified character to this writer. \r
+ *\r
+ * <p> An invocation of this method of the form <tt>out.append(c)</tt>\r
+ * behaves in exactly the same way as the invocation\r
+ *\r
+ * <pre>\r
+ * out.write(c) </pre>\r
+ *\r
+ * @param c\r
+ * The 16-bit character to append\r
+ *\r
+ * @return This writer\r
+ *\r
+ * @since 1.5\r
+ */\r
+ public StringBuilderOutputStream append(byte c) {\r
+ buf.append(c);\r
+ return this;\r
+ }\r
+\r
+ /**\r
+ * Return the buffer's current value as a string.\r
+ */\r
+ public String toString() {\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Return the string buffer itself.\r
+ *\r
+ * @return StringBuffer holding the current buffer value.\r
+ */\r
+ public StringBuilder getBuffer() {\r
+ return buf;\r
+ }\r
+ \r
+ public void reset() {\r
+ buf.setLength(0);\r
+ }\r
+\r
+ @Override\r
+ public void flush() throws IOException {\r
+ }\r
+\r
+ @Override\r
+ public void close() throws IOException {\r
+ }\r
+\r
+}\r
-/**
- * ============LICENSE_START====================================================
- * org.onap.aaf
- * ===========================================================================
- * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
- * ===========================================================================
- * Licensed 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.
- * ============LICENSE_END====================================================
- *
- */
-
-package org.onap.aaf.misc.env.util;
-
-import java.io.IOException;
-import java.io.Writer;
-
-public class StringBuilderWriter extends Writer {
- private StringBuilder buf;
-
-
- /**
- * Create a new string writer using the default initial string-buffer
- * size.
- */
- public StringBuilderWriter() {
- buf = new StringBuilder();
- }
-
- /**
- * Create a new string writer using a passed in StringBuilder
- * size.
- */
- public StringBuilderWriter(StringBuilder sb) {
- buf = sb;
- }
-
- /**
- * Create a new string writer using the specified initial string-buffer
- * size.
- *
- * @param initialSize
- * The number of <tt>char</tt> values that will fit into this buffer
- * before it is automatically expanded
- *
- * @throws IllegalArgumentException
- * If <tt>initialSize</tt> is negative
- */
- public StringBuilderWriter(int initialSize) {
- if (initialSize < 0) {
- throw new IllegalArgumentException("Negative buffer size");
- }
- buf = new StringBuilder(initialSize);
- }
-
- /**
- * Write a single character.
- */
- public void write(int c) {
- buf.append((char) c);
- }
-
- /**
- * Write a portion of an array of characters.
- *
- * @param cbuf Array of characters
- * @param off Offset from which to start writing characters
- * @param len Number of characters to write
- */
- public void write(char cbuf[], int off, int len) {
- if ((off < 0) || (off > cbuf.length) || (len < 0) ||
- ((off + len) > cbuf.length) || ((off + len) < 0)) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0) {
- return;
- }
- buf.append(cbuf, off, len);
- }
-
- /**
- * Write a string.
- */
- public void write(String str) {
- buf.append(str);
- }
-
- /**
- * Write a portion of a string.
- *
- * @param str String to be written
- * @param off Offset from which to start writing characters
- * @param len Number of characters to write
- */
- public void write(String str, int off, int len) {
- char[] chars = new char[len];
- str.getChars(off, off+len, chars, 0);
- buf.append(chars);
- }
-
- public StringBuilderWriter append(CharSequence csq) {
- if (csq == null) {
- write("null");
- } else {
- buf.append(csq);
- }
- return this;
- }
-
- public StringBuilderWriter append(CharSequence csq, int start, int end) {
- CharSequence cs = (csq == null ? "null" : csq);
- return append(cs.subSequence(start, end));
- }
-
- /**
- * Appends the specified character to this writer.
- *
- * <p> An invocation of this method of the form <tt>out.append(c)</tt>
- * behaves in exactly the same way as the invocation
- *
- * <pre>
- * out.write(c) </pre>
- *
- * @param c
- * The 16-bit character to append
- *
- * @return This writer
- *
- * @since 1.5
- */
- public StringBuilderWriter append(char c) {
- buf.append(c);
- return this;
- }
-
- /**
- * Return the buffer's current value as a string.
- */
- public String toString() {
- return buf.toString();
- }
-
- /**
- * Return the string buffer itself.
- *
- * @return StringBuffer holding the current buffer value.
- */
- public StringBuilder getBuffer() {
- return buf;
- }
-
- public void reset() {
- buf.setLength(0);
- }
-
- @Override
- public void flush() throws IOException {
- }
-
- @Override
- public void close() throws IOException {
- }
-
-}
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import java.io.IOException;\r
+import java.io.Writer;\r
+\r
+public class StringBuilderWriter extends Writer {\r
+ private StringBuilder buf;\r
+\r
+\r
+ /**\r
+ * Create a new string writer using the default initial string-buffer\r
+ * size.\r
+ */\r
+ public StringBuilderWriter() {\r
+ buf = new StringBuilder();\r
+ }\r
+\r
+ /**\r
+ * Create a new string writer using a passed in StringBuilder\r
+ * size.\r
+ */\r
+ public StringBuilderWriter(StringBuilder sb) {\r
+ buf = sb;\r
+ }\r
+\r
+ /**\r
+ * Create a new string writer using the specified initial string-buffer\r
+ * size.\r
+ *\r
+ * @param initialSize\r
+ * The number of <tt>char</tt> values that will fit into this buffer\r
+ * before it is automatically expanded\r
+ *\r
+ * @throws IllegalArgumentException\r
+ * If <tt>initialSize</tt> is negative\r
+ */\r
+ public StringBuilderWriter(int initialSize) {\r
+ if (initialSize < 0) {\r
+ throw new IllegalArgumentException("Negative buffer size");\r
+ }\r
+ buf = new StringBuilder(initialSize);\r
+ }\r
+\r
+ /**\r
+ * Write a single character.\r
+ */\r
+ public void write(int c) {\r
+ buf.append((char) c);\r
+ }\r
+\r
+ /**\r
+ * Write a portion of an array of characters.\r
+ *\r
+ * @param cbuf Array of characters\r
+ * @param off Offset from which to start writing characters\r
+ * @param len Number of characters to write\r
+ */\r
+ public void write(char cbuf[], int off, int len) {\r
+ if ((off < 0) || (off > cbuf.length) || (len < 0) ||\r
+ ((off + len) > cbuf.length) || ((off + len) < 0)) {\r
+ throw new IndexOutOfBoundsException();\r
+ } else if (len == 0) {\r
+ return;\r
+ }\r
+ buf.append(cbuf, off, len);\r
+ }\r
+\r
+ /**\r
+ * Write a string.\r
+ */\r
+ public void write(String str) {\r
+ buf.append(str);\r
+ }\r
+\r
+ /**\r
+ * Write a portion of a string.\r
+ *\r
+ * @param str String to be written\r
+ * @param off Offset from which to start writing characters\r
+ * @param len Number of characters to write\r
+ */\r
+ public void write(String str, int off, int len) {\r
+ char[] chars = new char[len];\r
+ str.getChars(off, off+len, chars, 0);\r
+ buf.append(chars);\r
+ }\r
+\r
+ public StringBuilderWriter append(CharSequence csq) {\r
+ if (csq == null) {\r
+ write("null");\r
+ } else {\r
+ buf.append(csq);\r
+ }\r
+ return this;\r
+ }\r
+\r
+ public StringBuilderWriter append(CharSequence csq, int start, int end) {\r
+ CharSequence cs = (csq == null ? "null" : csq);\r
+ return append(cs.subSequence(start, end));\r
+ }\r
+\r
+ /**\r
+ * Appends the specified character to this writer. \r
+ *\r
+ * <p> An invocation of this method of the form <tt>out.append(c)</tt>\r
+ * behaves in exactly the same way as the invocation\r
+ *\r
+ * <pre>\r
+ * out.write(c) </pre>\r
+ *\r
+ * @param c\r
+ * The 16-bit character to append\r
+ *\r
+ * @return This writer\r
+ *\r
+ * @since 1.5\r
+ */\r
+ public StringBuilderWriter append(char c) {\r
+ buf.append(c);\r
+ return this;\r
+ }\r
+\r
+ /**\r
+ * Return the buffer's current value as a string.\r
+ */\r
+ public String toString() {\r
+ return buf.toString();\r
+ }\r
+\r
+ /**\r
+ * Return the string buffer itself.\r
+ *\r
+ * @return StringBuffer holding the current buffer value.\r
+ */\r
+ public StringBuilder getBuffer() {\r
+ return buf;\r
+ }\r
+ \r
+ public void reset() {\r
+ buf.setLength(0);\r
+ }\r
+\r
+ @Override\r
+ public void flush() throws IOException {\r
+ }\r
+\r
+ @Override\r
+ public void close() throws IOException {\r
+ }\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+package org.onap.aaf.misc.env;\r
+\r
+import static org.junit.Assert.assertFalse;\r
+import static org.junit.Assert.assertTrue;\r
+import static org.mockito.Mockito.mock;\r
+import static org.mockito.Mockito.times;\r
+import static org.mockito.Mockito.verify;\r
+\r
+import java.util.Date;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.mockito.Mock;\r
+\r
+public class JU_LogTargetTest {\r
+\r
+ @Mock\r
+ Throwable t;\r
+\r
+ @Before\r
+ public void setup() {\r
+ t = mock(Throwable.class);\r
+ }\r
+\r
+ @Test\r
+ public void testLogTargetNull() {\r
+ LogTarget nullTarget = LogTarget.NULL;\r
+\r
+ // Expect methods doing nothing as no implemenation provided.\r
+ nullTarget.log(new Throwable(), null, null);\r
+ nullTarget.log("String", null);\r
+ nullTarget.printf(null, null, null);\r
+\r
+ assertFalse(nullTarget.isLoggable());\r
+ }\r
+\r
+ @Test\r
+ public void testLogTargetSysOut() {\r
+ LogTarget outTarget = LogTarget.SYSOUT;\r
+\r
+ outTarget.printf("format", new Date());\r
+ outTarget.log("null", null, null);\r
+\r
+ outTarget.log(t);\r
+ outTarget.log(t, "First String Object");\r
+\r
+ assertTrue(outTarget.isLoggable());\r
+\r
+ verify(t, times(2)).printStackTrace(System.out);\r
+ }\r
+\r
+ @Test\r
+ public void testLogTargetSysErr() {\r
+ LogTarget errTarget = LogTarget.SYSERR;\r
+\r
+ errTarget.printf("format", new Date());\r
+ errTarget.log("null", "null");\r
+\r
+ errTarget.log(t);\r
+ errTarget.log(t, "First String Object");\r
+\r
+ assertTrue(errTarget.isLoggable());\r
+\r
+ verify(t, times(2)).printStackTrace(System.err);\r
+ }\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertNull;\r
+import static org.junit.Assert.assertTrue;\r
+import static org.mockito.Mockito.mock;\r
+\r
+import java.applet.Applet;\r
+import java.io.IOException;\r
+import java.util.Properties;\r
+\r
+import org.junit.After;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.mockito.Mock;\r
+import org.onap.aaf.misc.env.Decryptor;\r
+import org.onap.aaf.misc.env.Encryptor;\r
+import org.onap.aaf.misc.env.LogTarget;\r
+import org.onap.aaf.misc.env.TimeTaken;\r
+\r
+public class JU_BasicEnvTest {\r
+\r
+ @Mock\r
+ Decryptor decrypt;\r
+\r
+ @Mock\r
+ Encryptor encrypt;\r
+\r
+ @Before\r
+ public void setup() {\r
+ decrypt = mock(Decryptor.class);\r
+ encrypt = mock(Encryptor.class);\r
+ }\r
+\r
+ @Test\r
+ public void testLogTarget() {\r
+ Properties prop = new Properties();\r
+ BasicEnv env = new BasicEnv(prop);\r
+\r
+ assertEquals(env.fatal(), LogTarget.SYSERR);\r
+ assertEquals(env.error(), LogTarget.SYSERR);\r
+ assertEquals(env.audit(), LogTarget.SYSOUT);\r
+ assertEquals(env.warn(), LogTarget.SYSERR);\r
+ assertEquals(env.init(), LogTarget.SYSOUT);\r
+ assertEquals(env.info(), LogTarget.SYSOUT);\r
+ assertEquals(env.debug(), LogTarget.NULL);\r
+ assertEquals(env.trace(), LogTarget.NULL);\r
+\r
+ env.debug(LogTarget.SYSOUT);\r
+ assertEquals(env.debug(), LogTarget.SYSOUT);\r
+\r
+ assertNull(env.getProperty("key"));\r
+ assertEquals("default", env.getProperty("key", "default"));\r
+\r
+ env.setProperty("key", "value");\r
+ assertEquals("value", env.getProperty("key", "default"));\r
+\r
+ Properties filteredProperties = env.getProperties("key");\r
+ assertEquals(filteredProperties.size(), 1);\r
+\r
+ env.setProperty("key", null);\r
+ assertEquals("default", env.getProperty("key", "default"));\r
+\r
+ filteredProperties = env.getProperties("key1");\r
+ assertEquals(filteredProperties.size(), 0);\r
+\r
+ filteredProperties = env.getProperties();\r
+ assertEquals(filteredProperties.size(), 0);\r
+\r
+ }\r
+\r
+ @Test\r
+ public void testBasicEnv() {\r
+ Applet applet = null;\r
+\r
+ BasicEnv env = new BasicEnv(applet, "tag1", "tag2");\r
+\r
+ TimeTaken tt = env.start("Name", 2);\r
+\r
+ long end = tt.end();\r
+ StringBuilder sb = new StringBuilder();\r
+\r
+ assertEquals(tt.toString(), "Name " + (end - tt.start) / 1000000f + "ms ");\r
+ tt.output(sb);\r
+ assertEquals(sb.toString(), "XML Name " + (end - tt.start) / 1000000f + "ms");\r
+\r
+ env.set(decrypt);\r
+ assertEquals(env.decryptor(), decrypt);\r
+ env.set(encrypt);\r
+ assertEquals(env.encryptor(), encrypt);\r
+ }\r
+\r
+ @Test\r
+ public void testBasicEnvDiffFlag() {\r
+ Properties prop = new Properties();\r
+\r
+ BasicEnv env = new BasicEnv("tag1", prop);\r
+\r
+ TimeTaken tt = env.start("Name", 1);\r
+\r
+ long end = tt.end();\r
+ StringBuilder sb = new StringBuilder();\r
+\r
+ assertEquals(tt.toString(), "Name " + (end - tt.start) / 1000000f + "ms ");\r
+ tt.output(sb);\r
+ assertEquals(sb.toString(), "REMOTE Name " + (end - tt.start) / 1000000f + "ms");\r
+\r
+ tt = env.start("New Name", 4);\r
+ tt.size(10);\r
+ sb = new StringBuilder();\r
+ tt.output(sb);\r
+ assertEquals(tt.toString(), "New Name " + (end - tt.start) / 1000000f + "ms 10");\r
+ assertEquals(sb.toString(), "JSON New Name " + (end - tt.start) / 1000000f + "ms size: 10");\r
+\r
+ env.staticSlot("tag", "prop");\r
+\r
+ if (System.getProperties().keySet().iterator().hasNext()) {\r
+ String key = (String) System.getProperties().keySet().iterator().next();\r
+\r
+ env.loadFromSystemPropsStartsWith(key);\r
+ assertEquals(env.getProperty(key), System.getProperties().get(key));\r
+ }\r
+\r
+ BasicTrans trans = env.newTrans();\r
+ assertEquals(trans.delegate, env);\r
+\r
+ }\r
+\r
+ @Test\r
+ public void testLoadProperties() throws IOException {\r
+ Properties prop = new Properties();\r
+\r
+ BasicEnv env = new BasicEnv("tag1", prop);\r
+\r
+ env.loadPropFiles("tag1", null);\r
+ env.setProperty("tag1", "propfile.properties");\r
+ env.loadPropFiles("tag1", null);\r
+\r
+ assertEquals(env.getProperty("prop1"), "New Property");\r
+\r
+ env.loadToSystemPropsStartsWith("prop1");\r
+\r
+ assertTrue(System.getProperties().keySet().contains("prop1"));\r
+ assertEquals(System.getProperties().get("prop1"), "New Property");\r
+ }\r
+\r
+ @After\r
+ public void tearDown() throws IOException {\r
+ /*\r
+ * File file = new File("./log-Append" + ending + "_0.log"); if (file.exists())\r
+ * { Files.delete(Paths.get(file.getAbsolutePath())); } file = new\r
+ * File("./log-Append" + ending + "_1.log"); if (file.exists()) {\r
+ * Files.delete(Paths.get(file.getAbsolutePath())); } file = new File("./Append"\r
+ * + ending + "_0.log"); if (file.exists()) {\r
+ * Files.delete(Paths.get(file.getAbsolutePath())); } file = new File("./Append"\r
+ * + ending + "_1.log"); if (file.exists()) {\r
+ * Files.delete(Paths.get(file.getAbsolutePath())); }\r
+ */\r
+ }\r
+}\r
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.impl;\r
+\r
+import static org.junit.Assert.assertFalse;\r
+import static org.powermock.api.mockito.PowerMockito.when;\r
+\r
+import org.apache.log4j.Level;\r
+import org.apache.log4j.Logger;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.mockito.Mock;\r
+import org.mockito.MockitoAnnotations;\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.powermock.api.mockito.PowerMockito;\r
+import org.powermock.core.classloader.annotations.PrepareForTest;\r
+import org.powermock.modules.junit4.PowerMockRunner;\r
+\r
+@RunWith(PowerMockRunner.class)\r
+@PrepareForTest({ Log4JLogTarget.class, Logger.class })\r
+public class JU_Log4JLogTargetTest {\r
+\r
+ @Mock\r
+ Logger log;\r
+\r
+ @Before\r
+ public void setup() {\r
+ MockitoAnnotations.initMocks(this);\r
+ PowerMockito.mockStatic(Logger.class);\r
+ when(Logger.getLogger("Info")).thenReturn(log);\r
+ when(log.isEnabledFor(Level.DEBUG)).thenReturn(false);\r
+ }\r
+\r
+ @Test\r
+ public void test() throws APIException {\r
+ Log4JLogTarget target = new Log4JLogTarget(null, Level.INFO);\r
+ Log4JLogTarget target1 = new Log4JLogTarget("Info", Level.DEBUG);\r
+\r
+ assertFalse(target1.isLoggable());\r
+\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import java.util.Calendar;\r
+import java.util.Date;\r
+import java.util.GregorianCalendar;\r
+import java.util.TimeZone;\r
+import java.util.logging.Level;\r
+import java.util.logging.LogRecord;\r
+\r
+import javax.xml.datatype.XMLGregorianCalendar;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+\r
+public class JU_ChronoTest {\r
+\r
+ @Before\r
+ public void setUp() throws Exception {\r
+ }\r
+\r
+ @Test\r
+ public void testFormatter8601() {\r
+ Chrono.Formatter8601 formatter = new Chrono.Formatter8601();\r
+\r
+ LogRecord record = new LogRecord(Level.WARNING, "Log Record to test log formating");\r
+\r
+ Date date = new Date(118, 02, 02);\r
+ long time = date.getTime();\r
+\r
+ record.setMillis(time);\r
+\r
+ String expectedString = Chrono.dateFmt.format(date) + " " + record.getThreadID() + " " + record.getLevel()\r
+ + ": " + record.getMessage() + "\n";\r
+ assertEquals(expectedString, formatter.format(record));\r
+ }\r
+\r
+ @Test\r
+ public void testTimeStampWithDate() {\r
+ Date date = Calendar.getInstance().getTime();\r
+ XMLGregorianCalendar timeStamp = Chrono.timeStamp(date);\r
+\r
+ GregorianCalendar gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ XMLGregorianCalendar expectedCalendar = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(gc);\r
+\r
+ assertEquals(expectedCalendar, timeStamp);\r
+ }\r
+\r
+ @Test\r
+ public void testUTCStamp() {\r
+ final Date date = Calendar.getInstance().getTime();\r
+ String expectedUTCTime = Chrono.utcFmt.format(date);\r
+\r
+ String stamp = Chrono.utcStamp(date);\r
+\r
+ assertEquals(stamp, expectedUTCTime);\r
+\r
+ Date date1 = null;\r
+ assertEquals("", Chrono.utcStamp(date1));\r
+\r
+ GregorianCalendar gc = null;\r
+ assertEquals(Chrono.utcStamp(gc), "");\r
+ gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ assertEquals(Chrono.utcStamp(gc), expectedUTCTime);\r
+\r
+ XMLGregorianCalendar xgc = null;\r
+ assertEquals(Chrono.utcStamp(xgc), "");\r
+ xgc = Chrono.timeStamp(gc);\r
+ assertEquals(Chrono.utcStamp(xgc), expectedUTCTime);\r
+\r
+ }\r
+\r
+ @Test\r
+ public void testDateStamp() {\r
+ final Date date = Calendar.getInstance().getTime();\r
+ String expectedUTCTime = Chrono.dateFmt.format(date);\r
+\r
+ String stamp = Chrono.dateStamp(date);\r
+\r
+ assertEquals(stamp, expectedUTCTime);\r
+\r
+ Date date1 = null;\r
+ assertEquals("", Chrono.dateStamp(date1));\r
+\r
+ GregorianCalendar gc = null;\r
+ assertEquals(Chrono.dateStamp(gc), "");\r
+ gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ assertEquals(Chrono.dateStamp(gc), expectedUTCTime);\r
+\r
+ XMLGregorianCalendar xgc = null;\r
+ assertEquals(Chrono.dateStamp(xgc), "");\r
+ xgc = Chrono.timeStamp(gc);\r
+ assertEquals(Chrono.dateStamp(xgc), expectedUTCTime);\r
+ }\r
+\r
+ @Test\r
+ public void testDateTime() {\r
+ final Date date = Calendar.getInstance().getTime();\r
+ date.setTime(1525023883297L);\r
+\r
+ GregorianCalendar gc = null;\r
+ assertEquals(Chrono.dateTime(gc), "");\r
+ gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+\r
+ // String expectedDateTime = "2018-04-29T11:14:43.297" + sign + hourOffSet + ":"\r
+ // + minOffSet;\r
+\r
+ TimeZone tz = gc.getTimeZone();\r
+ int tz1 = (tz.getRawOffset() + tz.getDSTSavings()) / 0x8CA0;\r
+ int tz1abs = Math.abs(tz1);\r
+ String expectedDateTime = String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03d%c%02d:%02d",\r
+ gc.get(GregorianCalendar.YEAR), gc.get(GregorianCalendar.MONTH) + 1,\r
+ gc.get(GregorianCalendar.DAY_OF_MONTH), gc.get(GregorianCalendar.HOUR),\r
+ gc.get(GregorianCalendar.MINUTE), gc.get(GregorianCalendar.SECOND),\r
+ gc.get(GregorianCalendar.MILLISECOND), tz1 == tz1abs ? '+' : '-', tz1abs / 100,\r
+ ((tz1abs - (tz1abs / 100) * 100) * 6) / 10 // Get the "10s", then convert to mins (without losing int\r
+ // place)\r
+ );\r
+\r
+ String stamp = Chrono.dateTime(date);\r
+\r
+ assertEquals(stamp, expectedDateTime);\r
+\r
+ assertEquals(Chrono.dateTime(gc), expectedDateTime);\r
+\r
+ XMLGregorianCalendar xgc = null;\r
+ assertEquals(Chrono.dateTime(xgc), "");\r
+ xgc = Chrono.timeStamp(gc);\r
+ assertEquals(Chrono.dateTime(xgc), expectedDateTime);\r
+ }\r
+\r
+ @Test\r
+ public void testDateOnlyStamp() {\r
+ final Date date = Calendar.getInstance().getTime();\r
+ date.setTime(1525023883297L);\r
+\r
+ String expectedDateTime = Chrono.dateOnlyFmt.format(date);\r
+\r
+ String stamp = Chrono.dateOnlyStamp(date);\r
+\r
+ assertEquals(stamp, expectedDateTime);\r
+\r
+ Date date1 = null;\r
+ assertEquals("", Chrono.dateOnlyStamp(date1));\r
+\r
+ GregorianCalendar gc = null;\r
+ assertEquals(Chrono.dateOnlyStamp(gc), "");\r
+ gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ assertEquals(Chrono.dateOnlyStamp(gc), expectedDateTime);\r
+\r
+ XMLGregorianCalendar xgc = null;\r
+ assertEquals(Chrono.dateOnlyStamp(xgc), "");\r
+ xgc = Chrono.timeStamp(gc);\r
+ assertEquals(Chrono.dateOnlyStamp(xgc), expectedDateTime);\r
+ }\r
+\r
+ @Test\r
+ public void testNiceDateStamp() {\r
+ final Date date = Calendar.getInstance().getTime();\r
+ date.setTime(1525023883297L);\r
+\r
+ String expectedDateTime = Chrono.niceDateFmt.format(date);\r
+\r
+ String stamp = Chrono.niceDateStamp(date);\r
+\r
+ assertEquals(stamp, expectedDateTime);\r
+\r
+ Date date1 = null;\r
+ assertEquals("", Chrono.niceDateStamp(date1));\r
+\r
+ GregorianCalendar gc = null;\r
+ assertEquals(Chrono.niceDateStamp(gc), "");\r
+ gc = new GregorianCalendar();\r
+ gc.setTime(date);\r
+ assertEquals(Chrono.niceDateStamp(gc), expectedDateTime);\r
+\r
+ XMLGregorianCalendar xgc = null;\r
+ assertEquals(Chrono.niceDateStamp(xgc), "");\r
+ xgc = Chrono.timeStamp(gc);\r
+ assertEquals(Chrono.niceDateStamp(xgc), expectedDateTime);\r
+ }\r
+\r
+ @Test\r
+ public void testMoment() {\r
+ final Date date = Calendar.getInstance().getTime();\r
+ date.setTime(1525023883297L);\r
+\r
+ GregorianCalendar begin = new GregorianCalendar();\r
+ begin.setTimeInMillis(date.getTime());\r
+ begin.set(GregorianCalendar.HOUR, 0);\r
+ begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);\r
+ begin.set(GregorianCalendar.MINUTE, 0);\r
+ begin.set(GregorianCalendar.SECOND, 0);\r
+ begin.set(GregorianCalendar.MILLISECOND, 0);\r
+\r
+ long firstMoment = begin.getTimeInMillis();\r
+\r
+ begin.set(GregorianCalendar.HOUR, 11);\r
+ begin.set(GregorianCalendar.MINUTE, 59);\r
+ begin.set(GregorianCalendar.SECOND, 59);\r
+ begin.set(GregorianCalendar.MILLISECOND, 999);\r
+ begin.set(GregorianCalendar.AM_PM, GregorianCalendar.PM);\r
+\r
+ long lastMoment = begin.getTimeInMillis();\r
+\r
+ assertEquals(firstMoment, Chrono.firstMomentOfDay(date.getTime()));\r
+ assertEquals(lastMoment, Chrono.lastMomentOfDay(date.getTime()));\r
+\r
+ float timeInMillis = (lastMoment - firstMoment) / 1000000f;\r
+ assertEquals(timeInMillis, Chrono.millisFromNanos(firstMoment, lastMoment), 0);\r
+\r
+ }\r
+}\r
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.env.util;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import org.junit.Test;\r
+\r
+public class JU_SplitTest {\r
+\r
+ @Test\r
+ public void testSplit() {\r
+ String[] splits = Split.split('c', "character c to break string");\r
+\r
+ assertEquals(splits.length, 4);\r
+ assertEquals(splits[0], "");\r
+ assertEquals(splits[1], "hara");\r
+ assertEquals(splits[2], "ter ");\r
+ assertEquals(splits[3], " to break string");\r
+ }\r
+\r
+ @Test\r
+ public void testSplitTrim() {\r
+ String[] splits = Split.splitTrim('c', "character c to break string", 5);\r
+\r
+ assertEquals(splits.length, 5);\r
+ assertEquals(splits[0], "");\r
+ assertEquals(splits[1], "hara");\r
+ assertEquals(splits[2], "ter");\r
+ assertEquals(splits[3], "to break string");\r
+ assertEquals(splits[4], null);\r
+\r
+ splits = Split.splitTrim('c', " character ", 1);\r
+ assertEquals(splits.length, 1);\r
+ assertEquals(splits[0], "character");\r
+ }\r
+}\r
content = t;\r
}\r
});\r
+ Pool.Pooled<Integer> pooled = new Pool.Pooled<Integer>(new Integer(123), pool, LogTarget.SYSOUT);\r
+ Pool.Pooled<Integer> pooled1 = new Pool.Pooled<Integer>(new Integer(123), null, LogTarget.SYSOUT);\r
try {\r
// pool.drain();\r
assertEquals("Should return intial value", 0, pool.get().content);\r
\r
pool.drain();\r
assertEquals("Should remove last from pool", 17, pool.get(LogTarget.SYSOUT).content);\r
+ pool.setMaxRange(10);\r
+ assertEquals(10, pool.getMaxRange());\r
+ pooled.toss();\r
+ pooled1.toss();\r
} catch (APIException e) {\r
}\r
}\r
-\r
}\r
parsed.event = START_ARRAY;
parsed.name = name;
}
- } else if (DONE_ITERATOR.equals(iter)) {
- } else {
+ } else if (!DONE_ITERATOR.equals(iter)) {
ladder.ascend(); // look at field info
- Iterator<?> memIter = ladder.peek();
- ListIterator<S> mems = (ListIterator<S>)iter;
- S mem;
- if(memIter==null) {
- mem=mems.next();
- } else if(!DONE_ITERATOR.equals(memIter)) {
- mem=mems.peek();
- } else if(iter.hasNext()) {
- mem=null;
- ladder.push(null);
- } else {
- mem=null;
- }
-
- if(mem!=null)
- parsed = subMarshaller.parse(mem, parsed);
+ Iterator<?> memIter = ladder.peek();
+ ListIterator<S> mems = (ListIterator<S>)iter;
+ S mem;
+ if(memIter==null) {
+ mem=mems.next();
+ } else if(!DONE_ITERATOR.equals(memIter)) {
+ mem=mems.peek();
+ } else if(iter.hasNext()) {
+ mem=null;
+ ladder.push(null);
+ } else {
+ mem=null;
+ }
+
+ if(mem!=null)
+ parsed = subMarshaller.parse(mem, parsed);
ladder.descend();
if(mem==null) {
if(iter.hasNext()) {
} else {
ladder.push(DONE_ITERATOR);
}
- } else if (DONE_ITERATOR.equals(iter)) {
- } else {
+ } else if (!DONE_ITERATOR.equals(iter)) {
FieldsIterator fields = (FieldsIterator)iter;
ladder.ascend(); // look at field info
- Iterator<?> currFieldIter = ladder.peek();
- Marshal<T> marshal;
- if(currFieldIter==null) {
- marshal=fields.next();
- } else if(!DONE_ITERATOR.equals(currFieldIter)) {
- marshal=fields.peek();
- if(marshal==null && fields.hasNext())marshal=fields.next();
- } else if(fields.hasNext()) {
- marshal=fields.next();
- ladder.push(null);
- } else {
- marshal=null;
- }
-
- if(marshal!=null)
- parsed = marshal.parse(in, parsed);
+ Iterator<?> currFieldIter = ladder.peek();
+ Marshal<T> marshal;
+ if(currFieldIter==null) {
+ marshal=fields.next();
+ } else if(!DONE_ITERATOR.equals(currFieldIter)) {
+ marshal=fields.peek();
+ if(marshal==null && fields.hasNext())marshal=fields.next();
+ } else if(fields.hasNext()) {
+ marshal=fields.next();
+ ladder.push(null);
+ } else {
+ marshal=null;
+ }
+
+ if(marshal!=null)
+ parsed = marshal.parse(in, parsed);
ladder.descend();
if(marshal==null || parsed.event==NONE) {
parsed.event = END_OBJ;
go(jin, jout, "{\"id\":\"Me,[}[eg[)(:x,\\\" Myself\",\"date\":1353094689100}");
// TODO: Clean out AT&T specific data
- go(jin,jout, "{\"userid\":\"jg1555\",\"timestamp\":1353097388531,\"item\":[{\"tag\":\"color\",\"value\":\"Mauve\"},{\"tag\":\"shirtsize\",\"value\":\"Xtra Large\"}]}");
+ go(jin,jout, "{\"userid\":\"xk3233\",\"timestamp\":1353097388531,\"item\":[{\"tag\":\"color\",\"value\":\"Mauve\"},{\"tag\":\"shirtsize\",\"value\":\"Xtra Large\"}]}");
//go()
- //"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><vote xmlns=\"urn:poll.att.com\"><userid>jg1555</userid><timestamp>1353082669667</timestamp></vote>");
+ //"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><vote xmlns=\"urn:poll.att.com\"><userid>xk3233</userid><timestamp>1353082669667</timestamp></vote>");
// 3/11/2015 Jonathan found a case with missing comma
go(jin,jout, "{\"start\":\"2015-03-11T18:18:05.580-05:00\",\"end\":\"2015-09-11-05:00\",\"force\":\"false\",\"perm\":{\"type\":\"org.osaaf.myns.mytype\",\"instance\":\"myInstance\",\"action\":\"myAction\"}"
--- /dev/null
+function myFunction() {\r
+ document.getElementById("demo").innerHTML = "Paragraph changed.";\r
+}
\ No newline at end of file
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.xgen;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertNull;\r
+\r
+import java.io.IOException;\r
+import java.io.PrintWriter;\r
+\r
+import org.junit.Test;\r
+import org.onap.aaf.misc.env.APIException;\r
+import org.onap.aaf.misc.env.Env;\r
+import org.onap.aaf.misc.env.Trans;\r
+import org.onap.aaf.misc.xgen.html.HTML4Gen;\r
+import org.onap.aaf.misc.xgen.html.HTMLGen;\r
+import org.onap.aaf.misc.xgen.html.State;\r
+\r
+public class JU_DynamicCodeTest {\r
+\r
+ @Test\r
+ public void test() throws APIException, IOException {\r
+ final Cache<HTMLGen> cache1 = new Cache<HTMLGen>() {\r
+\r
+ @Override\r
+ public void dynamic(HTMLGen hgen, Code<HTMLGen> code) {\r
+ }\r
+ };\r
+\r
+ final HTMLGen xgen1 = new HTML4Gen(new PrintWriter(System.out));\r
+ DynamicCode<HTMLGen, State<Env>, Trans> g = new DynamicCode<HTMLGen, State<Env>, Trans>() {\r
+\r
+ @Override\r
+ public void code(State<Env> state, Trans trans, Cache<HTMLGen> cache, HTMLGen xgen)\r
+ throws APIException, IOException {\r
+ assertNull(state);\r
+ assertNull(trans);\r
+ assertEquals(cache, cache1);\r
+ assertEquals(xgen, xgen1);\r
+ }\r
+ };\r
+\r
+ g.code(cache1, xgen1);\r
+ }\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ============LICENSE_START====================================================\r
+ * org.onap.aaf\r
+ * ===========================================================================\r
+ * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.\r
+ * ===========================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END====================================================\r
+ *\r
+ */\r
+\r
+package org.onap.aaf.misc.xgen.html;\r
+\r
+import static org.junit.Assert.fail;\r
+import static org.mockito.Matchers.any;\r
+import static org.mockito.Mockito.times;\r
+import static org.mockito.Mockito.verify;\r
+import static org.mockito.Mockito.when;\r
+\r
+import java.io.IOException;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.mockito.Mock;\r
+import org.mockito.MockitoAnnotations;\r
+import org.onap.aaf.misc.env.util.IndentPrintWriter;\r
+import org.onap.aaf.misc.xgen.Back;\r
+import org.onap.aaf.misc.xgen.Mark;\r
+\r
+public class JU_JSGenTest {\r
+\r
+ @Mock\r
+ private HTMLGen hg;\r
+ @Mock\r
+ private Mark mark;\r
+ @Mock\r
+ private IndentPrintWriter writer;\r
+ @Mock\r
+ private Mark jm;\r
+\r
+ @Before\r
+ public void setup() {\r
+ MockitoAnnotations.initMocks(this);\r
+ }\r
+\r
+ @Test\r
+ public void testFileNotFoundException() {\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ try {\r
+ gen.inline("JSScript", 2);\r
+ fail("This file should not be found.");\r
+ } catch (Exception e) {\r
+\r
+ }\r
+ }\r
+\r
+ @Test\r
+ public void testJSRead() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.inline("./sampletest.js", 2);\r
+\r
+ verify(writer).print("function myFunction() {");\r
+ verify(writer).print("document.getElementById(\"demo\").innerHTML = \"Paragraph changed.\";");\r
+ verify(writer).print("}");\r
+ verify(writer, times(0)).println();\r
+ }\r
+\r
+ @Test\r
+ public void testJSReadPrettyPrint() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ hg.pretty = true;\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.inline("./sampletest.js", 2);\r
+\r
+ verify(writer).print("function myFunction() {");\r
+ verify(writer).print("document.getElementById(\"demo\").innerHTML = \"Paragraph changed.\";");\r
+ verify(writer).print("}");\r
+ verify(writer, times(3)).println();\r
+ verify(hg).setIndent(0);\r
+ }\r
+\r
+ @Test\r
+ public void testPst() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ when(hg.pushBack(any(Back.class))).thenReturn(3);\r
+ hg.pretty = true;\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.pst("line 1", "line 2");\r
+\r
+ verify(writer).append('(');\r
+ verify(writer).append("line 1");\r
+ verify(writer).print("line 2");\r
+ verify(writer, times(1)).print(", ");\r
+ }\r
+\r
+ @Test\r
+ public void testPstWithMark() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ when(hg.pushBack(any(Back.class))).thenReturn(3);\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.pst(jm, "line 1", "line 2");\r
+\r
+ verify(writer).append('(');\r
+ verify(writer).append("line 1");\r
+ verify(writer).print("line 2");\r
+ verify(writer, times(1)).print(", ");\r
+ }\r
+\r
+ @Test\r
+ public void testPstWithNoLines() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ when(hg.pushBack(any(Back.class))).thenReturn(3);\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.pst(jm);\r
+\r
+ verify(writer).append('(');\r
+ }\r
+\r
+ @Test\r
+ public void testLi() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ when(writer.getIndent()).thenReturn(3);\r
+\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.li("line 1", "line 2");\r
+\r
+ verify(writer).setIndent(3);\r
+ verify(writer).inc();\r
+ verify(writer).println();\r
+ verify(writer).print("line 1");\r
+ verify(writer).print("line 2");\r
+\r
+ hg.pretty = true;\r
+ gen.li("line 1", "line 2");\r
+ verify(writer, times(3)).println();\r
+ }\r
+\r
+ @Test\r
+ public void testText() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ hg.pretty = true;\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.text("line 1");\r
+\r
+ verify(writer).append("line 1");\r
+ verify(writer).println();\r
+\r
+ hg.pretty = false;\r
+ gen.text("line 1");\r
+\r
+ verify(writer, times(2)).append("line 1");\r
+ }\r
+\r
+ @Test\r
+ public void testFunction() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ when(hg.pushBack(any(Back.class))).thenReturn(3);\r
+ hg.pretty = true;\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.function("line 1", "line 2", "line 3");\r
+\r
+ verify(writer).print("function ");\r
+ verify(writer).print("line 1");\r
+ verify(writer).print('(');\r
+\r
+ verify(writer).print("line 2");\r
+ verify(writer).print("line 3");\r
+ verify(writer, times(1)).print(", ");\r
+ verify(writer).print(") {");\r
+ verify(writer).inc();\r
+ verify(writer).println();\r
+ }\r
+\r
+ @Test\r
+ public void testFunctionWithMark() throws IOException {\r
+ when(hg.getWriter()).thenReturn(writer);\r
+ when(hg.pushBack(any(Back.class))).thenReturn(3);\r
+ JSGen gen = new JSGen(mark, hg);\r
+\r
+ gen.function(jm, "line 1", "line 2", "line 3");\r
+\r
+ verify(writer).print("function ");\r
+ verify(writer).print("line 1");\r
+ verify(writer).print('(');\r
+\r
+ verify(writer).print("line 2");\r
+ verify(writer).print("line 3");\r
+ verify(writer, times(1)).print(", ");\r
+ verify(writer).print(") {");\r
+ verify(writer, times(0)).inc();\r
+ verify(writer, times(0)).println();\r
+ }\r
+\r
+}\r