index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1
Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/client/Provisioner.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.api.v1.client; import org.apache.fineract.cn.provisioner.api.v1.domain.Application; import org.apache.fineract.cn.provisioner.api.v1.domain.AssignedApplication; import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse; import org.apache.fineract.cn.provisioner.api.v1.domain.Client; import org.apache.fineract.cn.provisioner.api.v1.domain.IdentityManagerInitialization; import org.apache.fineract.cn.provisioner.api.v1.domain.PasswordPolicy; import org.apache.fineract.cn.provisioner.api.v1.domain.Tenant; import java.util.List; import javax.validation.Valid; import org.apache.fineract.cn.api.annotation.ThrowsException; import org.apache.fineract.cn.api.util.CustomFeignClientsConfiguration; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * @author Myrle Krantz */ @SuppressWarnings("unused") @FeignClient(path="/provisioner/v1", url="http://${kubernetes.provisioner.service.name}:${kubernetes.provisioner.server.port}", configuration=CustomFeignClientsConfiguration.class) public interface Provisioner { @RequestMapping( value = "/auth/token?grant_type=password", method = RequestMethod.POST, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ThrowsException(status = HttpStatus.NOT_FOUND, exception = InvalidProvisionerCredentialsException.class) AuthenticationResponse authenticate(@RequestParam("client_id") final String clientId, @RequestParam("username") final String username, @RequestParam("password") final String password); @RequestMapping( value = "/auth/user/{useridentifier}/password", method = RequestMethod.PUT, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) void updatePasswordPolicy(@PathVariable("useridentifier") final String userIdentifier, @RequestBody final PasswordPolicy passwordPolicy); @RequestMapping( value = "/clients", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) List<Client> getClients(); @RequestMapping( value = "/clients", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ThrowsException(status = HttpStatus.CONFLICT, exception = DuplicateIdentifierException.class) void createClient(@RequestBody @Valid final Client client); @RequestMapping( value = "/clients/{clientidentifier}", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) Client getClient(@PathVariable("clientidentifier") final String clientIdentifier); @RequestMapping( value = "/clients/{clientidentifier}", method = RequestMethod.DELETE, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) void deleteClient(@PathVariable("clientidentifier") final String clientIdentifier); @RequestMapping( value = "/tenants", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ThrowsException(status = HttpStatus.CONFLICT, exception = DuplicateIdentifierException.class) void createTenant(@RequestBody final Tenant tenant); @RequestMapping( value = "/tenants", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) List<Tenant> getTenants(); @RequestMapping( value = "/tenants/{tenantidentifier}", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) Tenant getTenant(@PathVariable("tenantidentifier") final String tenantIdentifier); @RequestMapping( value = "/tenants/{tenantidentifier}", method = RequestMethod.DELETE, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) void deleteTenant(@PathVariable("tenantidentifier") final String tenantIdentifier); @RequestMapping( value = "/applications", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ThrowsException(status = HttpStatus.CONFLICT, exception = DuplicateIdentifierException.class) void createApplication(@RequestBody final Application application); @RequestMapping( value = "/applications", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) List<Application> getApplications(); @RequestMapping( value = "/applications/{name}", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) Application getApplication(@PathVariable("name") final String name); @RequestMapping( value = "/applications/{name}", method = RequestMethod.DELETE, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) void deleteApplication(@PathVariable("name") final String name); @RequestMapping( value = "tenants/{tenantidentifier}/identityservice", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) IdentityManagerInitialization assignIdentityManager(@PathVariable("tenantidentifier") final String tenantIdentifier, @RequestBody final AssignedApplication assignedApplications); @RequestMapping( value = "tenants/{tenantidentifier}/applications", method = RequestMethod.PUT, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) void assignApplications(@PathVariable("tenantidentifier") final String tenantIdentifier, @RequestBody final List<AssignedApplication> assignedApplications); @RequestMapping( value = "tenants/{tenantidentifier}/applications", method = RequestMethod.GET, produces = {MediaType.ALL_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) List<AssignedApplication> getAssignedApplications( @PathVariable("tenantidentifier") final String tenantIdentifier); }
3,200
0
Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1
Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/client/InvalidProvisionerCredentialsException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.api.v1.client; /** * @author Myrle Krantz */ @SuppressWarnings("WeakerAccess") public class InvalidProvisionerCredentialsException extends RuntimeException { public InvalidProvisionerCredentialsException() { super(); } }
3,201
0
Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1
Create_ds/fineract-cn-provisioner/api/src/main/java/org/apache/fineract/cn/provisioner/api/v1/client/DuplicateIdentifierException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.api.v1.client; /** * @author Myrle Krantz */ @SuppressWarnings("WeakerAccess") public class DuplicateIdentifierException extends RuntimeException { }
3,202
0
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/GenerateRsaKeyPair.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner; import java.io.BufferedWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; public class GenerateRsaKeyPair { private GenerateRsaKeyPair() { super(); } public static void main(String[] args) throws Exception { final GenerateRsaKeyPair generateRsaKeyPair = new GenerateRsaKeyPair(); generateRsaKeyPair.createKeyPair(); } private void createKeyPair() throws Exception { final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); final KeyPair keyPair = keyPairGenerator.genKeyPair(); final RSAPublicKeySpec rsaPublicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class); final BufferedWriter bufferedWriterPubKey = Files.newBufferedWriter(Paths.get("/home/mage/system.pub")); bufferedWriterPubKey.write(rsaPublicKeySpec.getModulus().toString()); bufferedWriterPubKey.newLine(); bufferedWriterPubKey.write(rsaPublicKeySpec.getPublicExponent().toString()); bufferedWriterPubKey.flush(); bufferedWriterPubKey.close(); final RSAPrivateKeySpec rsaPrivateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class); final BufferedWriter bufferedWriterPrivateKey = Files.newBufferedWriter(Paths.get("/home/mage/system")); bufferedWriterPrivateKey.write(rsaPrivateKeySpec.getModulus().toString()); bufferedWriterPrivateKey.newLine(); bufferedWriterPrivateKey.write(rsaPrivateKeySpec.getPrivateExponent().toString()); bufferedWriterPrivateKey.flush(); bufferedWriterPrivateKey.close(); } }
3,203
0
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/config/SystemPropertiesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import java.util.ArrayList; import java.util.Collection; import org.apache.fineract.cn.lang.security.RsaKeyPairFactory; import org.apache.fineract.cn.test.domain.ValidationTest; import org.apache.fineract.cn.test.domain.ValidationTestCase; import org.junit.runners.Parameterized; /** * @author Myrle Krantz */ public class SystemPropertiesTest extends ValidationTest<SystemProperties> { private static final RsaKeyPairFactory.KeyPairHolder keyPairHolder = RsaKeyPairFactory.createKeyPair(); public SystemPropertiesTest(ValidationTestCase<SystemProperties> testCase) { super(testCase); } @Override protected SystemProperties createValidTestSubject() { final SystemProperties ret = new SystemProperties(); ret.getPrivateKey().setModulus(keyPairHolder.getPrivateKeyMod()); ret.getPrivateKey().setExponent(keyPairHolder.getPrivateKeyExp()); ret.getPublicKey().setTimestamp(keyPairHolder.getTimestamp()); ret.getPublicKey().setModulus(keyPairHolder.getPublicKeyMod()); ret.getPublicKey().setExponent(keyPairHolder.getPublicKeyExp()); return ret; } @Parameterized.Parameters public static Collection testCases() { final Collection<ValidationTestCase> ret = new ArrayList<>(); ret.add(new ValidationTestCase<SystemProperties>("basicCase") .adjustment(x -> {}) .valid(true)); ret.add(new ValidationTestCase<SystemProperties>("missing private modulus") .adjustment(x -> x.getPrivateKey().setModulus(null)) .valid(false)); ret.add(new ValidationTestCase<SystemProperties>("mismatched keys") .adjustment(x -> { final RsaKeyPairFactory.KeyPairHolder keyPairHolder = RsaKeyPairFactory.createKeyPair(); x.getPrivateKey().setModulus(keyPairHolder.getPrivateKeyMod()); x.getPrivateKey().setExponent(keyPairHolder.getPrivateKeyExp()); }) .valid(false)); ret.add(new ValidationTestCase<SystemProperties>("missing timestamp") .adjustment(x -> x.getPublicKey().setTimestamp(null)) .valid(false)); return ret; } }
3,204
0
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal/util/ContactPointUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; import com.datastax.driver.core.Cluster; import org.junit.Assert; import org.junit.Test; import java.net.InetSocketAddress; import java.util.List; public class ContactPointUtilsTest { public ContactPointUtilsTest() { super(); } @Test public void shouldAddSimpleContactPoints() { final String contactPoints = "127.0.0.1,127.0.0.2,127.0.0.3"; final Cluster.Builder clusterBuilder = Cluster.builder(); ContactPointUtils.process(clusterBuilder, contactPoints); final List<InetSocketAddress> addedClusterPoints = clusterBuilder.getContactPoints(); Assert.assertTrue(addedClusterPoints.size() == 3); for (final InetSocketAddress address : addedClusterPoints) { Assert.assertTrue(contactPoints.contains(address.getAddress().getHostAddress())); } } @Test public void shouldAddComplexContactPoints() { final String contactPoints = "127.0.0.1:1234,127.0.0.2:2345,127.0.0.3:3456"; final Cluster.Builder clusterBuilder = Cluster.builder(); ContactPointUtils.process(clusterBuilder, contactPoints); final List<InetSocketAddress> addedClusterPoints = clusterBuilder.getContactPoints(); Assert.assertTrue(addedClusterPoints.size() == 3); final InetSocketAddress firstAddress = addedClusterPoints.get(0); Assert.assertEquals("127.0.0.1", firstAddress.getAddress().getHostAddress()); Assert.assertEquals(1234, firstAddress.getPort()); final InetSocketAddress secondAddress = addedClusterPoints.get(1); Assert.assertEquals("127.0.0.2", secondAddress.getAddress().getHostAddress()); Assert.assertEquals(2345, secondAddress.getPort()); final InetSocketAddress thirdAddress = addedClusterPoints.get(2); Assert.assertEquals("127.0.0.3", thirdAddress.getAddress().getHostAddress()); Assert.assertEquals(3456, thirdAddress.getPort()); } }
3,205
0
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal/util/JdbcUrlBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; import org.junit.Assert; import org.junit.Test; public class JdbcUrlBuilderTest { private final static String POSTGRES_DB_JDBC_URL = "jdbc:postgresql:localhost:5432/comp_test"; public JdbcUrlBuilderTest() { super(); } @Test public void shouldCreatePostgresUrl() { final String postgresDbUrl = JdbcUrlBuilder .create(JdbcUrlBuilder.DatabaseType.POSTGRESQL) .host("localhost") .port("5432") .instanceName("comp_test") .build(); Assert.assertEquals(POSTGRES_DB_JDBC_URL, postgresDbUrl); } }
3,206
0
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal/util/DataStoreOptionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; import org.junit.Assert; import org.junit.Test; public class DataStoreOptionTest { public DataStoreOptionTest() { super(); } @Test public void givenAllShouldBeEnabled() { final DataStoreOption all = DataStoreOption.ALL; Assert.assertTrue(all.isEnabled(DataStoreOption.CASSANDRA)); Assert.assertTrue(all.isEnabled(DataStoreOption.RDBMS)); Assert.assertTrue(all.isEnabled(DataStoreOption.CASSANDRA)); } @Test public void shouldOnlyCassandraEnabled() { final DataStoreOption cassandra = DataStoreOption.CASSANDRA; Assert.assertTrue(cassandra.isEnabled(DataStoreOption.CASSANDRA)); Assert.assertFalse(cassandra.isEnabled(DataStoreOption.RDBMS)); Assert.assertFalse(cassandra.isEnabled(DataStoreOption.ALL)); } @Test public void shouldOnlyRdbmsEnabled() { final DataStoreOption rdbms = DataStoreOption.RDBMS; Assert.assertFalse(rdbms.isEnabled(DataStoreOption.CASSANDRA)); Assert.assertTrue(rdbms.isEnabled(DataStoreOption.RDBMS)); Assert.assertFalse(rdbms.isEnabled(DataStoreOption.ALL)); } @Test(expected = IllegalArgumentException.class) public void shouldFailUnknownType() { DataStoreOption.valueOf("unknown"); Assert.fail(); } }
3,207
0
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal/service
Create_ds/fineract-cn-provisioner/service/src/test/java/org/apache/fineract/cn/provisioner/internal/service/applications/IdentityServiceInitializerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service.applications; import org.apache.fineract.cn.provisioner.config.SystemProperties; import org.apache.fineract.cn.provisioner.internal.listener.IdentityListener; import org.apache.fineract.cn.anubis.api.v1.client.Anubis; import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint; import org.apache.fineract.cn.identity.api.v1.client.IdentityManager; import org.apache.fineract.cn.identity.api.v1.client.PermittableGroupAlreadyExistsException; import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup; import org.apache.fineract.cn.lang.AutoTenantContext; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.Logger; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; /** * @author Myrle Krantz */ public class IdentityServiceInitializerTest { private final PermittableEndpoint abcPost1 = new PermittableEndpoint("/a/b/c", "POST", "1"); private final PermittableEndpoint abcGet1 = new PermittableEndpoint("/a/b/c", "GET", "1"); private final PermittableEndpoint defGet1 = new PermittableEndpoint("/d/e/f", "POST", "1"); private final PermittableGroup group1 = new PermittableGroup("1", Arrays.asList(abcPost1, abcGet1, defGet1)); private final PermittableGroup reorderedGroup1 = new PermittableGroup("1", Arrays.asList(abcGet1, abcPost1, defGet1)); private final PermittableGroup changedGroup1 = new PermittableGroup("1", Arrays.asList(abcPost1, defGet1)); private final PermittableEndpoint abcPost2 = new PermittableEndpoint("/a/b/c", "POST", "2"); private final PermittableEndpoint abcGet2 = new PermittableEndpoint("/a/b/c", "GET", "2"); private final PermittableEndpoint defGet2 = new PermittableEndpoint("/d/e/f", "POST", "2"); private final PermittableGroup group2 = new PermittableGroup("2", Arrays.asList(abcPost2, abcGet2, defGet2)); private final PermittableEndpoint defGet3 = new PermittableEndpoint("/d/e/f", "POST", "3"); private final PermittableGroup group3 = new PermittableGroup("3", Collections.singletonList(defGet3)); @Test public void getPermittablesAnubisCallFails() throws Exception { final IdentityListener identityListenerMock = Mockito.mock(IdentityListener.class); final ApplicationCallContextProvider applicationCallContextProviderMock = Mockito.mock(ApplicationCallContextProvider.class); final Logger loggerMock = Mockito.mock(Logger.class); final Anubis anubisMock = Mockito.mock(Anubis.class); when(applicationCallContextProviderMock.getApplication(Anubis.class, "blah")).thenReturn(anubisMock); //noinspection unchecked when(anubisMock.getPermittableEndpoints()).thenThrow(IllegalStateException.class); final SystemProperties systemProperties = new SystemProperties(); final List<PermittableEndpoint> ret = new IdentityServiceInitializer(identityListenerMock, applicationCallContextProviderMock, null, loggerMock, systemProperties) .getPermittables("blah"); Assert.assertEquals(ret, Collections.emptyList()); verify(loggerMock).error(anyString(), anyString(), isA(IllegalStateException.class)); } @Test public void getPermittableGroups() throws Exception { final List<PermittableEndpoint> permittableEndpoints = Arrays.asList(abcPost1, abcGet1, defGet1, abcPost2, abcGet2, defGet2, defGet3); final List<PermittableGroup> ret = IdentityServiceInitializer.getPermittableGroups(permittableEndpoints).collect(Collectors.toList()); Assert.assertEquals(ret, Arrays.asList(group1, group2, group3)); } @Test public void getPermittableGroupsOnEmptyList() throws Exception { final List<PermittableGroup> ret = IdentityServiceInitializer.getPermittableGroups(Collections.emptyList()).collect(Collectors.toList()); Assert.assertEquals(ret, Collections.emptyList()); } @Test public void createOrFindPermittableGroupThatAlreadyExists() throws Exception { final IdentityListener identityListenerMock = Mockito.mock(IdentityListener.class); final Logger loggerMock = Mockito.mock(Logger.class); final IdentityManager identityServiceMock = Mockito.mock(IdentityManager.class); doThrow(PermittableGroupAlreadyExistsException.class).when(identityServiceMock).createPermittableGroup(group1); doReturn(reorderedGroup1).when(identityServiceMock).getPermittableGroup(group1.getIdentifier()); try (final AutoTenantContext ignored = new AutoTenantContext("blah")) { final SystemProperties systemProperties = new SystemProperties(); new IdentityServiceInitializer(identityListenerMock, null, null, loggerMock, systemProperties) .createOrFindPermittableGroup(identityServiceMock, group1); } } @Test public void createOrFindPermittableGroupThatAlreadyExistsDifferently() throws Exception { final IdentityListener identityListenerMock = Mockito.mock(IdentityListener.class); final Logger loggerMock = Mockito.mock(Logger.class); final IdentityManager identityServiceMock = Mockito.mock(IdentityManager.class); doThrow(PermittableGroupAlreadyExistsException.class).when(identityServiceMock).createPermittableGroup(group1); doReturn(changedGroup1).when(identityServiceMock).getPermittableGroup(group1.getIdentifier()); try (final AutoTenantContext ignored = new AutoTenantContext("blah")) { final SystemProperties systemProperties = new SystemProperties(); new IdentityServiceInitializer(identityListenerMock, null, null, loggerMock, systemProperties) .createOrFindPermittableGroup(identityServiceMock, group1); } verify(loggerMock).warn(anyString(), anyString(), anyString(), anyObject(), anyObject()); } @Test public void createOrFindPermittableGroupWhenIsisCallFails() throws Exception { final IdentityListener identityListenerMock = Mockito.mock(IdentityListener.class); final Logger loggerMock = Mockito.mock(Logger.class); final IdentityManager identityServiceMock = Mockito.mock(IdentityManager.class); doThrow(IllegalStateException.class).when(identityServiceMock).createPermittableGroup(group1); doReturn(changedGroup1).when(identityServiceMock).getPermittableGroup(group1.getIdentifier()); try (final AutoTenantContext ignored = new AutoTenantContext("blah")) { final SystemProperties systemProperties = new SystemProperties(); new IdentityServiceInitializer(identityListenerMock, null, null, loggerMock, systemProperties) .createOrFindPermittableGroup(identityServiceMock, group1); } verify(loggerMock).error(anyString(), anyString(), anyString(), isA(IllegalStateException.class)); } }
3,208
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/ProvisionerApplication.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner; import org.apache.fineract.cn.provisioner.config.ProvisionerServiceConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProvisionerApplication { public ProvisionerApplication() { super(); } public static void main(String[] args) { SpringApplication.run(ProvisionerServiceConfig.class, args); } }
3,209
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/ProvisionerProperties.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import org.apache.fineract.cn.provisioner.internal.util.DataStoreOption; import org.springframework.boot.context.properties.ConfigurationProperties; import javax.validation.Valid; /** * @author Myrle Krantz */ @ConfigurationProperties(prefix = "provisioner") public class ProvisionerProperties { @Valid private DataStoreOption dataStoreOption = DataStoreOption.ALL; public DataStoreOption getDataStoreOption() { return dataStoreOption; } public void setDataStoreOption(DataStoreOption dataStoreOption) { this.dataStoreOption = dataStoreOption; } }
3,210
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/ProvisionerServiceConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import org.apache.fineract.cn.provisioner.internal.util.TokenProvider; import org.apache.activemq.jms.pool.PooledConnectionFactory; import org.apache.activemq.spring.ActiveMQConnectionFactory; import org.apache.fineract.cn.anubis.config.EnableAnubis; import org.apache.fineract.cn.anubis.token.SystemAccessTokenSerializer; import org.apache.fineract.cn.api.util.ApiFactory; import org.apache.fineract.cn.async.config.EnableAsync; import org.apache.fineract.cn.cassandra.config.EnableCassandra; import org.apache.fineract.cn.crypto.config.EnableCrypto; import org.apache.fineract.cn.lang.config.EnableApplicationName; import org.apache.fineract.cn.lang.config.EnableServiceException; import org.apache.fineract.cn.postgresql.config.EnablePostgreSQL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerContainerFactory; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableAutoConfiguration @ComponentScan({ "org.apache.fineract.cn.provisioner.internal.service", "org.apache.fineract.cn.provisioner.internal.listener", "org.apache.fineract.cn.provisioner.internal.service.applications", "org.apache.fineract.cn.provisioner.internal.repository", "org.apache.fineract.cn.provisioner.rest.controller", }) @EnableCrypto @EnableAsync @EnableAnubis(provideSignatureRestController = false) @EnablePostgreSQL @EnableCassandra @EnableServiceException @EnableApplicationName @EnableConfigurationProperties({ProvisionerActiveMQProperties.class, ProvisionerProperties.class, SystemProperties.class}) public class ProvisionerServiceConfig extends WebMvcConfigurerAdapter { public ProvisionerServiceConfig() { super(); } @Bean(name = ProvisionerConstants.LOGGER_NAME) public Logger logger() { return LoggerFactory.getLogger(ProvisionerConstants.LOGGER_NAME); } @Bean(name = "tokenProvider") public TokenProvider tokenProvider(final SystemProperties systemProperties, @SuppressWarnings("SpringJavaAutowiringInspection") final SystemAccessTokenSerializer tokenSerializer, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger) { final String timestamp = systemProperties.getPublicKey().getTimestamp(); logger.info("Provisioner key timestamp: " + timestamp); return new TokenProvider( timestamp, systemProperties.getPrivateKey().getModulus(), systemProperties.getPrivateKey().getExponent(), tokenSerializer); } @Bean public ApiFactory apiFactory(@Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger) { return new ApiFactory(logger); } @Override public void configurePathMatch(final PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch(Boolean.FALSE); } @Bean public PooledConnectionFactory jmsFactory(final ProvisionerActiveMQProperties activeMQProperties) { final PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(); final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(); activeMQConnectionFactory.setBrokerURL(activeMQProperties.getBrokerUrl()); pooledConnectionFactory.setConnectionFactory(activeMQConnectionFactory); return pooledConnectionFactory; } @Bean public JmsListenerContainerFactory jmsListenerContainerFactory(final PooledConnectionFactory jmsFactory, final ProvisionerActiveMQProperties activeMQProperties) { final DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setPubSubDomain(true); factory.setConnectionFactory(jmsFactory); factory.setConcurrency(activeMQProperties.getConcurrency()); return factory; } }
3,211
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/ProvisionerConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; public interface ProvisionerConstants { String LOGGER_NAME = "provisioner-logger"; String INITIAL_PWD = "oS/0IiAME/2unkN1momDrhAdNKOhGykYFH/mJN20"; String CONFIG_INTERNAL = "org.apache.fineract.cn.provisioner.internal"; int ITERATION_COUNT = 4096; int HASH_LENGTH = 256; }
3,212
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/SystemProperties.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.Range; import org.springframework.boot.context.properties.ConfigurationProperties; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.math.BigInteger; /** * @author Myrle Krantz */ @KeysValid @ConfigurationProperties(prefix = "system") public class SystemProperties { @NotEmpty private String domain = "fineract.apache.org"; @Valid private final Token token = new Token(); @Valid private final PublicKey publicKey = new PublicKey(); @Valid private final PrivateKey privateKey = new PrivateKey(); public static class Token { @Range(min = 1) private int ttl = 60; public int getTtl() { return ttl; } public void setTtl(int ttl) { this.ttl = ttl; } } public static class PublicKey { @NotEmpty private String timestamp; @NotNull private BigInteger modulus; @NotNull private BigInteger exponent; public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public BigInteger getModulus() { return modulus; } public void setModulus(BigInteger modulus) { this.modulus = modulus; } public BigInteger getExponent() { return exponent; } public void setExponent(BigInteger exponent) { this.exponent = exponent; } } public static class PrivateKey { @NotNull private BigInteger modulus; @NotNull private BigInteger exponent; public BigInteger getModulus() { return modulus; } public void setModulus(BigInteger modulus) { this.modulus = modulus; } public BigInteger getExponent() { return exponent; } public void setExponent(BigInteger exponent) { this.exponent = exponent; } } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public Token getToken() { return token; } public PublicKey getPublicKey() { return publicKey; } public PrivateKey getPrivateKey() { return privateKey; } }
3,213
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/KeysValid.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * @author Myrle Krantz */ @SuppressWarnings("unused") @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Constraint( validatedBy = {CheckKeysValid.class} ) public @interface KeysValid { String message() default "Public and private keys must be valid and matching."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
3,214
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/ProvisionerActiveMQProperties.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author Myrle Krantz */ @ConfigurationProperties(prefix = "activemq") public class ProvisionerActiveMQProperties { @SuppressWarnings("unused") final public static String ACTIVEMQ_BROKER_URL_PROP = "activemq.brokerUrl"; @SuppressWarnings("unused") final public static String ACTIVEMQ_CONCURRENCY_PROP = "activemq.concurrency"; @SuppressWarnings("WeakerAccess") final public static String ACTIVEMQ_BROKER_URL_DEFAULT = "vm://localhost?broker.persistent=false"; @SuppressWarnings("WeakerAccess") final public static String ACTIVEMQ_CONCURRENCY_DEFAULT = "3-10"; private String brokerUrl = ACTIVEMQ_BROKER_URL_DEFAULT; private String concurrency = ACTIVEMQ_CONCURRENCY_DEFAULT; public ProvisionerActiveMQProperties() { } public String getBrokerUrl() { return brokerUrl; } public void setBrokerUrl(String brokerUrl) { this.brokerUrl = brokerUrl; } public String getConcurrency() { return concurrency; } public void setConcurrency(String concurrency) { this.concurrency = concurrency; } }
3,215
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/config/CheckKeysValid.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.config; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; /** * @author Myrle Krantz */ public class CheckKeysValid implements ConstraintValidator<KeysValid, SystemProperties> { @Override public void initialize(KeysValid constraintAnnotation) { } @Override public boolean isValid(final SystemProperties value, final ConstraintValidatorContext context) { if (value.getPrivateKey().getModulus() == null || value.getPrivateKey().getExponent() == null || value.getPublicKey().getModulus() == null ||value.getPublicKey().getExponent() == null) return false; try { final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(value.getPrivateKey().getModulus(), value.getPrivateKey().getExponent()); final PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec); final RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(value.getPublicKey().getModulus(), value.getPublicKey().getExponent()); final PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec); final Signature signature = Signature.getInstance("NONEwithRSA"); signature.initSign(privateKey); final byte[] signed = signature.sign(); signature.initVerify(publicKey); return signature.verify(signed); } catch (final NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException e) { return false; } } }
3,216
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/ConfigEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; @SuppressWarnings("unused") @Table(name = ConfigEntity.TABLE_NAME) public class ConfigEntity { static final String TABLE_NAME = "config"; static final String NAME_COLUMN = "name"; static final String SECRET_COLUMN = "secret"; @PartitionKey @Column(name = NAME_COLUMN) private String name; @Column(name = SECRET_COLUMN) private byte[] secret; public ConfigEntity() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getSecret() { return secret; } public void setSecret(byte[] secret) { this.secret = secret; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfigEntity that = (ConfigEntity) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } }
3,217
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/TenantCassandraRepository.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.core.AuthProvider; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.DataType; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.AlreadyExistsException; import com.datastax.driver.core.schemabuilder.SchemaBuilder; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.MappingManager; import com.datastax.driver.mapping.Result; import org.apache.fineract.cn.provisioner.internal.util.ContactPointUtils; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import javax.annotation.Nonnull; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.cassandra.core.ReplicationStrategyResolver; import org.apache.fineract.cn.cassandra.util.CassandraConnectorConstants; import org.apache.fineract.cn.lang.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; /** * @author Myrle Krantz */ @Component public class TenantCassandraRepository { private final Environment environment; private final CassandraSessionProvider cassandraSessionProvider; private MappingManager mappingManager; @Autowired public TenantCassandraRepository( final Environment environment, final @Nonnull CassandraSessionProvider cassandraSessionProvider) { super(); this.environment = environment; this.cassandraSessionProvider = cassandraSessionProvider; } public Optional<TenantEntity> get(final @Nonnull String tenantIdentifier) { final Mapper<TenantEntity> tenantEntityMapper = this.getMappingManager().mapper(TenantEntity.class); return Optional.ofNullable(tenantEntityMapper.get(tenantIdentifier)); } public void adjust(final @Nonnull String tenantIdentifier, final @Nonnull Consumer<TenantEntity> adjustment) { final Mapper<TenantEntity> tenantEntityMapper = this.getMappingManager().mapper(TenantEntity.class); final TenantEntity tenantEntity = tenantEntityMapper.get(tenantIdentifier); if (tenantEntity == null) { throw ServiceException.notFound("Tenant {0} not found!", tenantIdentifier); } adjustment.accept(tenantEntity); tenantEntityMapper.save(tenantEntity); } public List<TenantEntity> fetchAll() { final ResultSet resultSet = this.cassandraSessionProvider.getAdminSession().execute(" SELECT * FROM tenants"); final Mapper<TenantEntity> tenantEntityMapper = this.getMappingManager().mapper(TenantEntity.class); final Result<TenantEntity> map = tenantEntityMapper.map(resultSet); return map.all(); } public void delete(final @Nonnull String identifier) { final Mapper<TenantEntity> tenantEntityMapper = this.getMappingManager().mapper(TenantEntity.class); final TenantEntity tenantEntity = tenantEntityMapper.get(identifier); if (tenantEntity != null) { final Session session = this.getCluster(tenantEntity).connect(); // drop org.apache.fineract.cn.provisioner.tenant keyspace session.execute("DROP KEYSPACE " + tenantEntity.getKeyspaceName()); session.close(); tenantEntityMapper.delete(identifier); } } public void create(final @Nonnull TenantEntity tenant) { final Mapper<TenantEntity> tenantEntityMapper = this.getMappingManager().mapper(TenantEntity.class); if (tenantEntityMapper.get(tenant.getIdentifier()) != null) { throw ServiceException.conflict("Tenant {0} already exists!", tenant.getIdentifier()); } final Session session = this.getCluster(tenant).connect(); try { session.execute("CREATE KEYSPACE " + tenant.getKeyspaceName() + " WITH REPLICATION = " + ReplicationStrategyResolver.replicationStrategy( tenant.getReplicationType(), tenant.getReplicas())); } catch (final AlreadyExistsException e) { throw ServiceException.badRequest("Tenant keyspace {0} already exists!", tenant.getKeyspaceName()); } final String createCommandSourceTable = SchemaBuilder.createTable(tenant.getKeyspaceName(), "command_source") .addPartitionKey("source", DataType.text()) .addPartitionKey("bucket", DataType.text()) .addClusteringColumn("created_on", DataType.timestamp()) .addColumn("command", DataType.text()) .addColumn("processed", DataType.cboolean()) .addColumn("failed", DataType.cboolean()) .addColumn("failure_message", DataType.text()) .buildInternal(); session.execute(createCommandSourceTable); session.close(); tenantEntityMapper.save(tenant); } private Cluster getCluster(final @Nonnull TenantEntity tenantEntity) { final Cluster.Builder clusterBuilder = Cluster .builder() .withClusterName(tenantEntity.getClusterName()); if (this.environment.containsProperty(CassandraConnectorConstants.CLUSTER_USER_PROP)) { final String user = this.environment.getProperty(CassandraConnectorConstants.CLUSTER_USER_PROP); final String pwd = this.environment.getProperty(CassandraConnectorConstants.CLUSTER_PASSWORD_PROP); final AuthProvider authProvider = new PlainTextAuthProvider(user, pwd); clusterBuilder.withAuthProvider(authProvider); } ContactPointUtils.process(clusterBuilder, tenantEntity.getContactPoints()); return clusterBuilder.build(); } private MappingManager getMappingManager() { if (this.mappingManager == null) { this.mappingManager = new MappingManager(this.cassandraSessionProvider.getAdminSession()); } return this.mappingManager; } }
3,218
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/ClientEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; @Table(name = ClientEntity.TABLE_NAME) public class ClientEntity { static final String TABLE_NAME = "clients"; static final String NAME_COLUMN = "name"; static final String DESCRIPTION_COLUMN = "description"; static final String REDIRECT_URI_COLUMN = "redirect_uri"; static final String VENDOR_COLUMN = "vendor"; static final String HOMEPAGE_COLUMN = "homepage"; @PartitionKey @Column(name = NAME_COLUMN) private String name; @Column(name = DESCRIPTION_COLUMN) private String description; @Column(name = REDIRECT_URI_COLUMN) private String redirectUri; @Column(name = VENDOR_COLUMN) private String vendor; @Column(name = HOMEPAGE_COLUMN) private String homepage; public ClientEntity() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRedirectUri() { return redirectUri; } public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public String getHomepage() { return homepage; } public void setHomepage(String homepage) { this.homepage = homepage; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientEntity that = (ClientEntity) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } }
3,219
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/TenantEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; @Table(name = TenantEntity.TABLE_NAME) public class TenantEntity { static final String TABLE_NAME = "tenants"; static final String IDENTIFIER_COLUMN = "identifier"; static final String CLUSTER_NAME_COLUMN = "cluster_name"; static final String CONTACT_POINTS_COLUMN = "contact_points"; static final String KEYSPACE_NAME_COLUMN = "keyspace_name"; static final String REPLICATION_TYPE_COLUMN = "replication_type"; static final String REPLICAS_COLUMN = "replicas"; static final String NAME_COLUMN = "name"; static final String DESCRIPTION_COLUMN = "description"; static final String IDENTITY_MANAGER_APPLICATION_NAME_COLUMN = "identity_manager_application_name"; static final String IDENTITY_MANAGER_APPLICATION_URI_COLUMN = "identity_manager_application_uri"; @PartitionKey @Column(name = IDENTIFIER_COLUMN) private String identifier; @Column(name = CLUSTER_NAME_COLUMN) private String clusterName; @Column(name = CONTACT_POINTS_COLUMN) private String contactPoints; @Column(name = KEYSPACE_NAME_COLUMN) private String keyspaceName; @Column(name = REPLICATION_TYPE_COLUMN) private String replicationType; @Column(name = REPLICAS_COLUMN) private String replicas; @Column(name = NAME_COLUMN) private String name; @Column(name = DESCRIPTION_COLUMN) private String description; @Column(name = IDENTITY_MANAGER_APPLICATION_NAME_COLUMN) private String identityManagerApplicationName; @Column(name = IDENTITY_MANAGER_APPLICATION_URI_COLUMN) private String identityManagerApplicationUri; public TenantEntity() { super(); } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getContactPoints() { return contactPoints; } public void setContactPoints(String contactPoints) { this.contactPoints = contactPoints; } public String getKeyspaceName() { return keyspaceName; } public void setKeyspaceName(String keyspaceName) { this.keyspaceName = keyspaceName; } public String getReplicationType() { return replicationType; } public void setReplicationType(String replicationType) { this.replicationType = replicationType; } public String getReplicas() { return replicas; } public void setReplicas(String replicas) { this.replicas = replicas; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIdentityManagerApplicationName() { return identityManagerApplicationName; } public void setIdentityManagerApplicationName(String identityManagerApplicationName) { this.identityManagerApplicationName = identityManagerApplicationName; } public String getIdentityManagerApplicationUri() { return identityManagerApplicationUri; } public void setIdentityManagerApplicationUri(String identityManagerApplicationUri) { this.identityManagerApplicationUri = identityManagerApplicationUri; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TenantEntity that = (TenantEntity) o; return identifier.equals(that.identifier); } @Override public int hashCode() { return identifier.hashCode(); } }
3,220
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/ApplicationEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; @Table(name = ApplicationEntity.TABLE_NAME) public class ApplicationEntity { static final String TABLE_NAME = "applications"; static final String NAME_COLUMN = "name"; static final String DESCRIPTION_COLUMN = "description"; static final String VENDOR_COLUMN = "vendor"; static final String HOMEPAGE_COLUMN = "homepage"; @PartitionKey @Column(name = NAME_COLUMN) private String name; @Column(name = DESCRIPTION_COLUMN) private String description; @Column(name = VENDOR_COLUMN) private String vendor; @Column(name = HOMEPAGE_COLUMN) private String homepage; public ApplicationEntity() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public String getHomepage() { return homepage; } public void setHomepage(String homepage) { this.homepage = homepage; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ApplicationEntity that = (ApplicationEntity) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } }
3,221
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/UserEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import java.util.Date; @SuppressWarnings("unused") @Table(name = UserEntity.TABLE_NAME) public class UserEntity { static final java.lang.String TABLE_NAME = "users"; static final String NAME_COLUMN = "name"; static final String PASSWORD_COLUMN = "passwordWord"; static final String SALT_COLUMN = "salt"; static final String ITERATION_COUNT_COLUMN = "iteration_count"; static final String EXPIRES_IN_DAYS_COLUMN = "expires_in_days"; static final String PASSWORD_RESET_ON_COLUMN = "password_reset_on"; @PartitionKey @Column(name = NAME_COLUMN) private String name; @Column(name = PASSWORD_COLUMN) private byte[] password; @Column(name = SALT_COLUMN) private byte[] salt; @Column(name = ITERATION_COUNT_COLUMN) private int iterationCount; @Column(name = EXPIRES_IN_DAYS_COLUMN) private int expiresInDays; @Column(name = PASSWORD_RESET_ON_COLUMN) private Date passwordResetOn; public UserEntity() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getPassword() { return password; } public void setPassword(byte[] password) { this.password = password; } public byte[] getSalt() { return salt; } public void setSalt(byte[] salt) { this.salt = salt; } public int getIterationCount() { return iterationCount; } public void setIterationCount(int iterationCount) { this.iterationCount = iterationCount; } public int getExpiresInDays() { return expiresInDays; } public void setExpiresInDays(int expiresInDays) { this.expiresInDays = expiresInDays; } public Date getPasswordResetOn() { return passwordResetOn; } public void setPasswordResetOn(Date passwordResetOn) { this.passwordResetOn = passwordResetOn; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserEntity that = (UserEntity) o; return name.equals(that.name); } @Override public int hashCode() { return name.hashCode(); } }
3,222
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/TenantDAO.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import org.apache.fineract.cn.postgresql.util.PostgreSQLConstants; import org.apache.fineract.cn.provisioner.api.v1.domain.DatabaseConnectionInfo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Optional; @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"}) public class TenantDAO { private static final class Builder { private final ResultSet resultSet; private Builder(final ResultSet resultSet) { super(); this.resultSet = resultSet; } Optional<TenantDAO> build() throws SQLException { if (this.resultSet.next()) { final TenantDAO tenantDAO = new TenantDAO(); tenantDAO.setIdentifier(this.resultSet.getString("identifier")); tenantDAO.setDriverClass(this.resultSet.getString("driver_class")); tenantDAO.setDatabaseName(this.resultSet.getString("database_name")); tenantDAO.setHost(this.resultSet.getString("host")); tenantDAO.setPort(this.resultSet.getString("port")); tenantDAO.setUser(this.resultSet.getString("a_user")); tenantDAO.setPassword(this.resultSet.getString("pwd")); return Optional.of(tenantDAO); } else { return Optional.empty(); } } List<TenantDAO> collect() throws SQLException { final ArrayList<TenantDAO> tenantDAOs = new ArrayList<>(); while (this.resultSet.next()) { final TenantDAO tenantDAO = new TenantDAO(); tenantDAOs.add(tenantDAO); tenantDAO.setIdentifier(this.resultSet.getString("identifier")); tenantDAO.setDriverClass(this.resultSet.getString("driver_class")); tenantDAO.setDatabaseName(this.resultSet.getString("database_name")); tenantDAO.setHost(this.resultSet.getString("host")); tenantDAO.setPort(this.resultSet.getString("port")); tenantDAO.setUser(this.resultSet.getString("a_user")); tenantDAO.setPassword(this.resultSet.getString("pwd")); } return tenantDAOs; } } private static final int INDEX_IDENTIFIER = 1; private static final int INDEX_DRIVER_CLASS = 2; private static final int INDEX_DATABASE_NAME = 3; private static final int INDEX_HOST = 4; private static final int INDEX_PORT = 5; private static final int INDEX_USER = 6; private static final int INDEX_PASSWORD = 7; private static final String TABLE_NAME = "tenants"; private static final String FETCH_ALL_STMT = " SELECT * FROM " + TenantDAO.TABLE_NAME; private static final String FIND_ONE_STMT = " SELECT * FROM " + TenantDAO.TABLE_NAME + " WHERE identifier = ?"; private static final String INSERT_STMT = " INSERT INTO " + TenantDAO.TABLE_NAME + " (identifier, driver_class, database_name, host, port, a_user, pwd) " + " values " + " (?, ?, ?, ?, ?, ?, ?) "; private static final String DELETE_STMT = " DELETE FROM " + TenantDAO.TABLE_NAME + " WHERE identifier = ? "; private String identifier; private String driverClass; private String databaseName; private String host; private String port; private String user; private String password; public TenantDAO() { super(); } private static Builder create(final ResultSet resultSet) { return new Builder(resultSet); } public static Optional<TenantDAO> find(final Connection connection, final String identifier) throws SQLException { try (final PreparedStatement findOneTenantStatement = connection.prepareStatement(TenantDAO.FIND_ONE_STMT)) { findOneTenantStatement.setString(INDEX_IDENTIFIER, identifier); try (final ResultSet resultSet = findOneTenantStatement.executeQuery()) { return TenantDAO.create(resultSet).build(); } } } public static List<TenantDAO> fetchAll(final Connection connection) throws SQLException { try (final Statement fetchAllTenantsStatement = connection.createStatement()) { try (final ResultSet resultSet = fetchAllTenantsStatement.executeQuery(TenantDAO.FETCH_ALL_STMT)) { return TenantDAO.create(resultSet).collect(); } } } public static void delete(final Connection connection, final String identifier) throws SQLException { try (final PreparedStatement deleteTenantStatement = connection.prepareStatement(TenantDAO.DELETE_STMT)) { deleteTenantStatement.setString(INDEX_IDENTIFIER, identifier); deleteTenantStatement.execute(); } } public void insert(final Connection connection) throws SQLException { try (final PreparedStatement insertTenantStatement = connection.prepareStatement(TenantDAO.INSERT_STMT)) { insertTenantStatement.setString(INDEX_IDENTIFIER, this.getIdentifier()); insertTenantStatement.setString(INDEX_DRIVER_CLASS, this.getDriverClass()); insertTenantStatement.setString(INDEX_DATABASE_NAME, this.getDatabaseName()); insertTenantStatement.setString(INDEX_HOST, this.getHost()); insertTenantStatement.setString(INDEX_PORT, this.getPort()); insertTenantStatement.setString(INDEX_USER, this.getUser()); insertTenantStatement.setString(INDEX_PASSWORD, this.getPassword()); insertTenantStatement.execute(); } } public DatabaseConnectionInfo map() { final DatabaseConnectionInfo databaseConnectionInfo = new DatabaseConnectionInfo(); databaseConnectionInfo.setDriverClass(this.getDriverClass()); databaseConnectionInfo.setDatabaseName(this.getDatabaseName()); databaseConnectionInfo.setHost(this.getHost()); databaseConnectionInfo.setPort(this.getPort()); databaseConnectionInfo.setUser(this.getUser()); databaseConnectionInfo.setPassword(this.getPassword()); return databaseConnectionInfo; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } private String getDriverClass() { return driverClass; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } private String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } private String getHost() { return host; } public void setHost(String host) { this.host = host; } private String getPort() { return port; } public void setPort(String port) { this.port = port; } private String getUser() { return user; } public void setUser(String user) { this.user = user; } private String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3,223
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/TenantDAOHackEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import javax.persistence.*; /** See https://github.com/spring-projects/spring-boot/issues/6314 */ @SuppressWarnings("unused") //To remove exception that persistence unit is missing. @Entity @Table(name = "tenants") public class TenantDAOHackEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private String id; @Column(name = "identifier") private String identifier; @Column(name = "driver_class") private String driverClass; @Column(name = "database_name") private String databaseName; @Column(name = "host") private String host; @Column(name = "port") private String port; @Column(name = "a_user") private String user; @Column(name = "pwd") private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getDriverClass() { return driverClass; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3,224
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/ProvisionerInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.DataType; import com.datastax.driver.core.Session; import com.datastax.driver.core.schemabuilder.SchemaBuilder; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.internal.util.DataSourceUtils; import java.nio.ByteBuffer; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import java.util.UUID; import javax.annotation.PostConstruct; import org.apache.commons.lang.StringUtils; import org.apache.fineract.cn.api.util.ApiConstants; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.cassandra.util.CassandraConnectorConstants; import org.apache.fineract.cn.crypto.HashGenerator; import org.apache.fineract.cn.crypto.SaltGenerator; import org.apache.fineract.cn.postgresql.util.PostgreSQLConstants; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.security.crypto.util.EncodingUtils; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; @SuppressWarnings({"SqlNoDataSourceInspection", "SqlDialectInspection", "unused"}) @Component public class ProvisionerInitializer { private final Environment environment; private final Logger logger; private final CassandraSessionProvider cassandraSessionProvider; private final SaltGenerator saltGenerator; private final HashGenerator hashGenerator; private final String initialClientId; private String metaKeySpaceName; @Autowired public ProvisionerInitializer(final Environment environment, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final CassandraSessionProvider cassandraSessionProvider, final SaltGenerator saltGenerator, final HashGenerator hashGenerator, @Value("${system.initialclientid}") final String initialClientId) { super(); this.environment = environment; this.logger = logger; this.cassandraSessionProvider = cassandraSessionProvider; this.saltGenerator = saltGenerator; this.hashGenerator = hashGenerator; this.initialClientId = initialClientId; } @PostConstruct public void initialize() { try { metaKeySpaceName = this.environment.getProperty( CassandraConnectorConstants.KEYSPACE_PROP, CassandraConnectorConstants.KEYSPACE_PROP_DEFAULT); this.initializeCassandra(); this.initializeDatabase(PostgreSQLConstants.POSTGRESQL_DATABASE_NAME_DEFAULT); this.createTableTenants(); } catch (final Exception ex) { throw new IllegalStateException("Could not initialize service!", ex); } } private void initializeCassandra() throws Exception { final Session session = this.cassandraSessionProvider.getAdminSession(); if (session.getCluster().getMetadata().getKeyspace(metaKeySpaceName).getTable(ConfigEntity.TABLE_NAME) == null) { //create config family final String createConfigTableStatement = SchemaBuilder.createTable(ConfigEntity.TABLE_NAME) .addPartitionKey(ConfigEntity.NAME_COLUMN, DataType.text()) .addColumn(ConfigEntity.SECRET_COLUMN, DataType.blob()) .buildInternal(); session.execute(createConfigTableStatement); final byte[] secret = this.saltGenerator.createRandomSalt(); final BoundStatement configBoundStatement = session.prepare("INSERT INTO config (name, secret) VALUES (?, ?)").bind(); configBoundStatement.setString("name", ProvisionerConstants.CONFIG_INTERNAL); configBoundStatement.setBytes("secret", ByteBuffer.wrap(secret)); session.execute(configBoundStatement); //create users family final String createUsersTableStatement = SchemaBuilder.createTable(UserEntity.TABLE_NAME) .addPartitionKey(UserEntity.NAME_COLUMN, DataType.text()) .addColumn(UserEntity.PASSWORD_COLUMN, DataType.blob()) .addColumn(UserEntity.SALT_COLUMN, DataType.blob()) .addColumn(UserEntity.ITERATION_COUNT_COLUMN, DataType.cint()) .addColumn(UserEntity.EXPIRES_IN_DAYS_COLUMN, DataType.cint()) .addColumn(UserEntity.PASSWORD_RESET_ON_COLUMN, DataType.timestamp()) .buildInternal(); session.execute(createUsersTableStatement); final String username = ApiConstants.SYSTEM_SU; final byte[] hashedPassword = Base64Utils.decodeFromString(ProvisionerConstants.INITIAL_PWD); final byte[] variableSalt = this.saltGenerator.createRandomSalt(); final BoundStatement userBoundStatement = session.prepare("INSERT INTO users (name, passwordWord, salt, iteration_count, password_reset_on) VALUES (?, ?, ?, ?, ?)").bind(); userBoundStatement.setString("name", username); userBoundStatement.setBytes("passwordWord", ByteBuffer.wrap( this.hashGenerator.hash(Base64Utils.encodeToString(hashedPassword), EncodingUtils.concatenate(variableSalt, secret), ProvisionerConstants.ITERATION_COUNT, ProvisionerConstants.HASH_LENGTH))); userBoundStatement.setBytes("salt", ByteBuffer.wrap(variableSalt)); userBoundStatement.setInt("iteration_count", ProvisionerConstants.ITERATION_COUNT); userBoundStatement.setTimestamp("password_reset_on", new Date()); session.execute(userBoundStatement); //create tenants family final String createTenantsTableStatement = SchemaBuilder.createTable(TenantEntity.TABLE_NAME) .addPartitionKey(TenantEntity.IDENTIFIER_COLUMN, DataType.text()) .addColumn(TenantEntity.CLUSTER_NAME_COLUMN, DataType.text()) .addColumn(TenantEntity.CONTACT_POINTS_COLUMN, DataType.text()) .addColumn(TenantEntity.KEYSPACE_NAME_COLUMN, DataType.text()) .addColumn(TenantEntity.REPLICATION_TYPE_COLUMN, DataType.text()) .addColumn(TenantEntity.REPLICAS_COLUMN, DataType.text()) .addColumn(TenantEntity.NAME_COLUMN, DataType.text()) .addColumn(TenantEntity.DESCRIPTION_COLUMN, DataType.text()) .addColumn(TenantEntity.IDENTITY_MANAGER_APPLICATION_NAME_COLUMN, DataType.text()) .addColumn(TenantEntity.IDENTITY_MANAGER_APPLICATION_URI_COLUMN, DataType.text()) .buildInternal(); session.execute(createTenantsTableStatement); //create services family final String createApplicationsTableStatement = SchemaBuilder.createTable(ApplicationEntity.TABLE_NAME) .addPartitionKey(ApplicationEntity.NAME_COLUMN, DataType.text()) .addColumn(ApplicationEntity.DESCRIPTION_COLUMN, DataType.text()) .addColumn(ApplicationEntity.VENDOR_COLUMN, DataType.text()) .addColumn(ApplicationEntity.HOMEPAGE_COLUMN, DataType.text()) .buildInternal(); session.execute(createApplicationsTableStatement); //create org.apache.fineract.cn.provisioner.tenant services family final String createTenantApplicationsTableStatement = SchemaBuilder.createTable(TenantApplicationEntity.TABLE_NAME) .addPartitionKey(TenantApplicationEntity.TENANT_IDENTIFIER_COLUMN, DataType.text()) .addColumn(TenantApplicationEntity.ASSIGNED_APPLICATIONS_COLUMN, DataType.set(DataType.text())) .buildInternal(); session.execute(createTenantApplicationsTableStatement); //create clients family final String createClientsTableStatement = SchemaBuilder.createTable(ClientEntity.TABLE_NAME) .addPartitionKey(ClientEntity.NAME_COLUMN, DataType.text()) .addColumn(ClientEntity.DESCRIPTION_COLUMN, DataType.text()) .addColumn(ClientEntity.REDIRECT_URI_COLUMN, DataType.text()) .addColumn(ClientEntity.VENDOR_COLUMN, DataType.text()) .addColumn(ClientEntity.HOMEPAGE_COLUMN, DataType.text()) .buildInternal(); session.execute(createClientsTableStatement); final String clientId = StringUtils.isEmpty(initialClientId) ? UUID.randomUUID().toString() : initialClientId; this.logger.info(clientId); final BoundStatement clientBoundStatement = session.prepare("INSERT INTO clients (name, description, vendor, homepage) VALUES (?, ?, ?, ?)").bind(); clientBoundStatement.setString("name", clientId); clientBoundStatement.setString("description", "REST Console"); clientBoundStatement.setString("vendor", "The Apache Software Foundation"); clientBoundStatement.setString("homepage", "https://fineract.apache.org"); session.execute(clientBoundStatement); } } private void initializeDatabase(String metaDatabaseName) throws Exception { this.logger.info("Creating meta database {} ", metaDatabaseName); try ( final Connection connection = DataSourceUtils.createProvisionerConnection(this.environment, "postgres"); final Statement testStatement = connection.createStatement(); final Statement statement = connection.createStatement() ) { final ResultSet validityQuery = testStatement.executeQuery("SELECT 1"); if (validityQuery.next()){ this.logger.info("Connection to database postgres established"); final ResultSet findDB = statement.executeQuery("SELECT datname FROM pg_database WHERE datname = '" + metaDatabaseName + "'"); if (!findDB.next()) { this.logger.info("Database {} does not exists, creating the database {} now.", metaDatabaseName); statement.execute("CREATE DATABASE " + metaDatabaseName); } else { this.logger.info("Database {} already exists.", metaDatabaseName); } } else { this.logger.warn("Could not connect to database postgres"); throw new IllegalMonitorStateException("Could not connect to database postgres"); } } } private void createTableTenants() throws SQLException { final String databaseName = PostgreSQLConstants.POSTGRESQL_DATABASE_NAME_DEFAULT; this.logger.info("Create tenants table in database {} if it does not exists", databaseName); try ( final Connection provisionerConnection = DataSourceUtils.createProvisionerConnection(this.environment, databaseName); final Statement testStatement = provisionerConnection.createStatement(); final Statement findSeshatStatement = provisionerConnection.createStatement() ) { final ResultSet validityQuery = testStatement.executeQuery("SELECT 1"); if (validityQuery.next()) { this.logger.info("Connection to database {} established", databaseName); final ResultSet resultSet = findSeshatStatement.executeQuery("SELECT datname FROM pg_database where datname = '"+ databaseName +"'"); if (resultSet.next()) { this.logger.info("Database {} exists !", databaseName); this.logger.info("Creating table tenants now"); findSeshatStatement.execute("CREATE TABLE IF NOT EXISTS tenants (identifier VARCHAR(32) NOT NULL, driver_class VARCHAR(255) NOT NULL, database_name VARCHAR(32) NOT NULL, host VARCHAR(512) NOT NULL, port VARCHAR(5) NOT NULL, a_user VARCHAR(32) NOT NULL, pwd VARCHAR(32) NOT NULL, PRIMARY KEY (identifier))"); } else { this.logger.warn("Database {} does not exists !", databaseName); } } else { this.logger.warn("Could not connect to database seshat"); throw new IllegalMonitorStateException("Could not connect to database seshat"); } } catch (SQLException sqlex) { this.logger.error(sqlex.getMessage(), sqlex); throw new IllegalStateException("Could not create table tenants"); } } }
3,225
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/repository/TenantApplicationEntity.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.repository; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import java.util.Set; @Table(name = TenantApplicationEntity.TABLE_NAME) public class TenantApplicationEntity { static final String TABLE_NAME = "tenant_applications"; static final String TENANT_IDENTIFIER_COLUMN = "tenant_identifier"; static final String ASSIGNED_APPLICATIONS_COLUMN = "assigned_applications"; @PartitionKey @Column(name = TENANT_IDENTIFIER_COLUMN) private String tenantIdentifier; @Column(name = ASSIGNED_APPLICATIONS_COLUMN) private Set<String> applications; public TenantApplicationEntity() { super(); } public String getTenantIdentifier() { return tenantIdentifier; } public void setTenantIdentifier(String tenantIdentifier) { this.tenantIdentifier = tenantIdentifier; } public Set<String> getApplications() { return applications; } public void setApplications(Set<String> applications) { this.applications = applications; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TenantApplicationEntity that = (TenantApplicationEntity) o; return tenantIdentifier.equals(that.tenantIdentifier); } @Override public int hashCode() { return tenantIdentifier.hashCode(); } }
3,226
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/listener/IdentityListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.listener; import static org.apache.fineract.cn.identity.api.v1.events.EventConstants.OPERATION_POST_PERMITTABLE_GROUP; import static org.apache.fineract.cn.identity.api.v1.events.EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE; import com.google.gson.Gson; import org.apache.fineract.cn.identity.api.v1.events.ApplicationSignatureEvent; import org.apache.fineract.cn.identity.api.v1.events.EventConstants; import org.apache.fineract.cn.lang.config.TenantHeaderFilter; import org.apache.fineract.cn.lang.listening.EventExpectation; import org.apache.fineract.cn.lang.listening.EventKey; import org.apache.fineract.cn.lang.listening.TenantedEventListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; /** * @author Myrle Krantz */ @Component public class IdentityListener { private final Gson gson; private final TenantedEventListener eventListener = new TenantedEventListener(); @Autowired public IdentityListener(final Gson gson) { this.gson = gson; } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_POST_PERMITTABLE_GROUP ) public void onCreatePermittableGroup( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenantIdentifier, final String payload) throws Exception { eventListener.notify(new EventKey(tenantIdentifier, OPERATION_POST_PERMITTABLE_GROUP, payload)); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_PUT_APPLICATION_SIGNATURE ) public void onSetApplicationSignature( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenantIdentifier, final String payload) throws Exception { final ApplicationSignatureEvent event = gson.fromJson(payload, ApplicationSignatureEvent.class); eventListener.notify(new EventKey(tenantIdentifier, OPERATION_PUT_APPLICATION_SIGNATURE, event)); } public EventExpectation expectPermittableGroupCreation(final String tenantIdentifier, final String permittableGroupIdentifier) { return eventListener.expect(new EventKey(tenantIdentifier, OPERATION_POST_PERMITTABLE_GROUP, permittableGroupIdentifier)); } public EventExpectation expectApplicationSignatureSet(final String tenantIdentifier, final String applicationIdentifier, final String keyTimestamp) { final ApplicationSignatureEvent expectedEvent = new ApplicationSignatureEvent(applicationIdentifier, keyTimestamp); return eventListener.expect(new EventKey(tenantIdentifier, OPERATION_PUT_APPLICATION_SIGNATURE, expectedEvent)); } public void withdrawExpectation(final EventExpectation eventExpectation) { eventListener.withdrawExpectation(eventExpectation); } }
3,227
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/util/DataSourceUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; import org.apache.fineract.cn.postgresql.util.PostgreSQLConstants; import org.springframework.core.env.Environment; import org.apache.fineract.cn.postgresql.util.JdbcUrlBuilder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.fineract.cn.provisioner.api.v1.domain.DatabaseConnectionInfo; public class DataSourceUtils { private DataSourceUtils() { super(); } public static Connection create(final DatabaseConnectionInfo databaseConnectionInfo) { try { Class.forName(databaseConnectionInfo.getDriverClass()); } catch (ClassNotFoundException cnfex) { throw new IllegalArgumentException(cnfex.getMessage(), cnfex); } final String jdbcUrl = JdbcUrlBuilder .create(JdbcUrlBuilder.DatabaseType.POSTGRESQL) .host(databaseConnectionInfo.getHost()) .port(databaseConnectionInfo.getPort()) .instanceName(databaseConnectionInfo.getDatabaseName()) .build(); try { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } final Connection connection = DriverManager.getConnection(jdbcUrl, databaseConnectionInfo.getUser(), databaseConnectionInfo.getPassword()); connection.setAutoCommit(true); return connection; } catch (SQLException sqlex) { throw new IllegalStateException(sqlex.getMessage(), sqlex); } } public static Connection createProvisionerConnection(final Environment environment, String databaseName) { final DatabaseConnectionInfo databaseConnectionInfo = new DatabaseConnectionInfo(); databaseConnectionInfo.setDriverClass(environment.getProperty("postgresql.driverClass")); if (databaseName != null) { databaseConnectionInfo.setDatabaseName(databaseName); } databaseConnectionInfo.setHost(environment.getProperty("postgresql.host")); databaseConnectionInfo.setPort(environment.getProperty("postgresql.port")); databaseConnectionInfo.setUser(environment.getProperty("postgresql.user")); databaseConnectionInfo.setPassword(environment.getProperty("postgresql.password")); try { final Connection connection = DataSourceUtils.create(databaseConnectionInfo); connection.setAutoCommit(true); return connection; } catch (SQLException error) { throw new IllegalStateException(error.getMessage(), error); } } }
3,228
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/util/ContactPointUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; import com.datastax.driver.core.Cluster; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; public class ContactPointUtils { private ContactPointUtils() { super(); } public static void process(final Cluster.Builder clusterBuilder, final String contactPoints) { final String[] splitContactPoints = contactPoints.split(","); for (final String contactPoint : splitContactPoints) { if (contactPoint.contains(":")) { final String[] address = contactPoint.split(":"); clusterBuilder.addContactPointsWithPorts( new InetSocketAddress(address[0].trim(), Integer.valueOf(address[1].trim()))); } else { try { clusterBuilder.addContactPoints(InetAddress.getByName(contactPoint.trim())); } catch (final UnknownHostException uhex) { throw new IllegalArgumentException("Host not found!", uhex); } } } } }
3,229
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/util/DataStoreOption.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; public enum DataStoreOption { ALL, CASSANDRA, RDBMS; public boolean isEnabled(final DataStoreOption dataStoreOption) { return this == ALL || this == dataStoreOption; } }
3,230
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/util/TokenProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; import java.math.BigInteger; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.RSAPrivateKeySpec; import java.util.concurrent.TimeUnit; import org.apache.fineract.cn.anubis.api.v1.RoleConstants; import org.apache.fineract.cn.anubis.token.SystemAccessTokenSerializer; import org.apache.fineract.cn.anubis.token.TokenSerializationResult; public class TokenProvider { private final String keyTimestamp; private final PrivateKey privateKey; private final SystemAccessTokenSerializer tokenSerializer; public TokenProvider( final String keyTimestamp, final BigInteger privateKeyModulus, final BigInteger privateKeyExponent, final SystemAccessTokenSerializer tokenSerializer) { super(); this.tokenSerializer = tokenSerializer; try { this.keyTimestamp = keyTimestamp; final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(privateKeyModulus, privateKeyExponent); this.privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec); } catch (final Exception ex) { throw new IllegalStateException("Could not read RSA key pair!", ex); } } public TokenSerializationResult createToken( final String subject, final String audience, final long ttl, final TimeUnit timeUnit) { SystemAccessTokenSerializer.Specification specification = new SystemAccessTokenSerializer.Specification(); specification.setKeyTimestamp(keyTimestamp); specification.setTenant(subject); specification.setTargetApplicationName(audience); specification.setSecondsToLive(timeUnit.toSeconds(ttl)); specification.setRole(RoleConstants.SYSTEM_ADMIN_ROLE_IDENTIFIER); specification.setPrivateKey(privateKey); return this.tokenSerializer.build(specification); } }
3,231
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/util/JdbcUrlBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.util; final class JdbcUrlBuilder { enum DatabaseType { POSTGRESQL("jdbc:postgresql:"); private final String prefix; DatabaseType(final String prefix) { this.prefix = prefix; } String prefix() { return this.prefix; } } private final DatabaseType type; private String host; private String port; private String instanceName; private JdbcUrlBuilder(final DatabaseType type) { super(); this.type = type; } static JdbcUrlBuilder create(final DatabaseType type) { return new JdbcUrlBuilder(type); } JdbcUrlBuilder host(final String host) { this.host = host; return this; } JdbcUrlBuilder port(final String port) { this.port = port; return this; } JdbcUrlBuilder instanceName(final String instanceName) { this.instanceName = instanceName; return this; } String build() { switch (this.type) { case POSTGRESQL: return this.type.prefix() + this.host + ":" + this.port + (this.instanceName != null ? "/" + this.instanceName : ""); default: throw new IllegalArgumentException("Unknown database type '" + this.type.name() + "'"); } } }
3,232
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/ClientService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service; import com.datastax.driver.core.ResultSet; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import org.apache.fineract.cn.provisioner.internal.repository.ClientEntity; import java.util.ArrayList; import java.util.List; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.lang.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ClientService { private final CassandraSessionProvider cassandraSessionProvider; @Autowired public ClientService(final CassandraSessionProvider cassandraSessionProvider) { super(); this.cassandraSessionProvider = cassandraSessionProvider; } public List<ClientEntity> fetchAll() { final ArrayList<ClientEntity> result = new ArrayList<>(); final ResultSet clientResult = this.cassandraSessionProvider.getAdminSession().execute("SELECT * FROM clients"); final Mapper<ClientEntity> clientEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ClientEntity.class); final Result<ClientEntity> mappedClientEntities = clientEntityMapper.map(clientResult); if (mappedClientEntities != null) { result.addAll(mappedClientEntities.all()); } return result; } public void create(final ClientEntity clientEntity) { final Mapper<ClientEntity> clientEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ClientEntity.class); if (clientEntityMapper.get(clientEntity.getName()) != null) { throw ServiceException.conflict("Client {0} already exists!", clientEntity.getName()); } clientEntityMapper.save(clientEntity); } public void delete(final String name) { final Mapper<ClientEntity> clientEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ClientEntity.class); clientEntityMapper.delete(name); } public ClientEntity findByName(final String name) { final Mapper<ClientEntity> clientEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ClientEntity.class); final ClientEntity clientEntity = clientEntityMapper.get(name); if (clientEntity == null) { throw ServiceException.notFound("Client {0} not found!", name); } return clientEntity; } }
3,233
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/TenantApplicationService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service; import com.datastax.driver.core.ResultSet; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.internal.repository.ApplicationEntity; import org.apache.fineract.cn.provisioner.internal.repository.TenantApplicationEntity; import org.apache.fineract.cn.provisioner.internal.repository.TenantCassandraRepository; import org.apache.fineract.cn.provisioner.internal.repository.TenantEntity; import org.apache.fineract.cn.provisioner.internal.service.applications.AnubisInitializer; import org.apache.fineract.cn.provisioner.internal.service.applications.IdentityServiceInitializer; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet; import org.apache.fineract.cn.anubis.config.TenantSignatureRepository; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.lang.AutoTenantContext; import org.apache.fineract.cn.lang.ServiceException; import org.apache.fineract.cn.lang.listening.EventExpectation; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.util.Assert; @Component public class TenantApplicationService { private final CassandraSessionProvider cassandraSessionProvider; private final AnubisInitializer anubisInitializer; private final IdentityServiceInitializer identityServiceInitializer; private final TenantSignatureRepository tenantSignatureRepository; private final TenantCassandraRepository tenantCassandraRepository; private final Logger logger; @Autowired public TenantApplicationService(final CassandraSessionProvider cassandraSessionProvider, final AnubisInitializer anubisInitializer, final IdentityServiceInitializer identityServiceInitializer, @SuppressWarnings("SpringJavaAutowiringInspection") final TenantSignatureRepository tenantSignatureRepository, final TenantCassandraRepository tenantCassandraRepository, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger) { super(); this.cassandraSessionProvider = cassandraSessionProvider; this.anubisInitializer = anubisInitializer; this.identityServiceInitializer = identityServiceInitializer; this.tenantSignatureRepository = tenantSignatureRepository; this.tenantCassandraRepository = tenantCassandraRepository; this.logger = logger; } @Async public void assign(final @Nonnull TenantApplicationEntity tenantApplicationEntity, final @Nonnull Map<String, String> appNameToUriMap) { Assert.notNull(tenantApplicationEntity); Assert.notNull(appNameToUriMap); final TenantEntity tenantEntity = tenantCassandraRepository.get(tenantApplicationEntity.getTenantIdentifier()) .orElseThrow(() -> ServiceException .notFound("Tenant {0} not found.", tenantApplicationEntity.getTenantIdentifier())); checkApplicationsExist(tenantApplicationEntity.getApplications()); saveTenantApplicationAssignment(tenantApplicationEntity); final Set<ApplicationNameToUriPair> applicationNameToUriPairs = getApplicationNameToUriPairs(tenantApplicationEntity, appNameToUriMap); final Optional<ApplicationSignatureSet> latestIdentityManagerSignatureSet = getLatestIdentityManagerSignatureSet(tenantEntity); latestIdentityManagerSignatureSet.ifPresent(y -> { try { initializeSecurity(tenantEntity, y, applicationNameToUriPairs); } catch (final InterruptedException e) { logger.error("Because of interruption, started but didn't finish application assignment for {} in tenant {}.", appNameToUriMap.keySet(), tenantApplicationEntity.getTenantIdentifier(), e); } }); if (!latestIdentityManagerSignatureSet.isPresent()) { logger.warn("No identity manager signature is available, so security is not initialized for applications {}", appNameToUriMap.keySet()); } } private void initializeSecurity(final TenantEntity tenantEntity, final ApplicationSignatureSet identityManagerSignatureSet, final Set<ApplicationNameToUriPair> applicationNameToUriPairs) throws InterruptedException { final String tenantIdentifier = tenantEntity.getIdentifier(); final String identityManagerApplicationName = tenantEntity.getIdentityManagerApplicationName(); final String identityManagerApplicationUri = tenantEntity.getIdentityManagerApplicationUri(); //Permittable groups must be posted before resource initialization occurs because resource initialization //may request callback from another service. For example, Services X, Y, and Identity. // X.initializeResources -> Y.requestCallback at X.address // Y.requestCallback -> Identity.requestPermission to call X.address // Therefore Identity must know of the permittable group for X.address before X.initializeResources is called. final Stream<EventExpectation> eventExpectations = applicationNameToUriPairs.stream().flatMap(x -> identityServiceInitializer.postApplicationPermittableGroups( tenantIdentifier, identityManagerApplicationName, identityManagerApplicationUri, x.uri).stream()); for (final EventExpectation eventExpectation : eventExpectations.collect(Collectors.toList())) { if (!eventExpectation.waitForOccurrence(5, TimeUnit.SECONDS)) { logger.warn("Expected action in identity didn't complete {}.", eventExpectation); } } applicationNameToUriPairs.forEach(x -> { final ApplicationSignatureSet applicationSignatureSet = anubisInitializer.createSignatureSet(tenantIdentifier, x.name, x.uri, identityManagerSignatureSet.getTimestamp(), identityManagerSignatureSet.getIdentityManagerSignature()); identityServiceInitializer.postApplicationDetails( tenantIdentifier, identityManagerApplicationName, identityManagerApplicationUri, x.name, x.uri, applicationSignatureSet); //InitializeResources on the service being added should occur last, for two reasons: // 1.) When the initialization event is put on the queue for this app/tenant combo, the app is fully ready for business. // 2.) If the app depends on the provisioning of identitypermissions in its initialization, those resources will be there. anubisInitializer.initializeResources(tenantIdentifier, x.name, x.uri); }); } private void saveTenantApplicationAssignment(final @Nonnull TenantApplicationEntity tenantApplicationEntity) { final Mapper<TenantApplicationEntity> tenantApplicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(TenantApplicationEntity.class); tenantApplicationEntityMapper.save(tenantApplicationEntity); } private Set<ApplicationNameToUriPair> getApplicationNameToUriPairs( final @Nonnull TenantApplicationEntity tenantApplicationEntity, final @Nonnull Map<String, String> appNameToUriMap) { return tenantApplicationEntity.getApplications().stream() .map(x -> new TenantApplicationService.ApplicationNameToUriPair(x, appNameToUriMap.get(x))) .collect(Collectors.toSet()); } private static class ApplicationNameToUriPair { String name; String uri; ApplicationNameToUriPair(String name, String uri) { this.name = name; this.uri = uri; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ApplicationNameToUriPair that = (ApplicationNameToUriPair) o; return Objects.equals(name, that.name) && Objects.equals(uri, that.uri); } @Override public int hashCode() { return Objects.hash(name, uri); } } private Optional<ApplicationSignatureSet> getLatestIdentityManagerSignatureSet(final @Nonnull TenantEntity tenantEntity) { try (final AutoTenantContext ignored = new AutoTenantContext(tenantEntity.getIdentifier())) { return tenantSignatureRepository.getLatestSignatureSet(); } } public TenantApplicationEntity find(final String tenantIdentifier) { checkTenant(tenantIdentifier); final Mapper<TenantApplicationEntity> tenantApplicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(TenantApplicationEntity.class); return tenantApplicationEntityMapper.get(tenantIdentifier); } void deleteTenant(final String tenantIdentifier) { final Mapper<TenantApplicationEntity> tenantApplicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(TenantApplicationEntity.class); tenantApplicationEntityMapper.delete(tenantIdentifier); } void removeApplication(final String name) { final ResultSet tenantApplicationResultSet = this.cassandraSessionProvider.getAdminSession().execute("SELECT * FROM tenant_applications"); if (tenantApplicationResultSet != null) { final Mapper<TenantApplicationEntity> tenantApplicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(TenantApplicationEntity.class); final Result<TenantApplicationEntity> mappedTenantApplications = tenantApplicationEntityMapper.map(tenantApplicationResultSet); for (TenantApplicationEntity tenantApplicationEntity : mappedTenantApplications) { if (tenantApplicationEntity.getApplications().contains(name)) { tenantApplicationEntity.getApplications().remove(name); tenantApplicationEntityMapper.save(tenantApplicationEntity); } } } } private void checkApplicationsExist(final Set<String> applications) { final Mapper<ApplicationEntity> applicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ApplicationEntity.class); for (final String name : applications) { if (applicationEntityMapper.get(name) == null) { throw ServiceException.badRequest("Application {0} not found!", name); } } } private void checkTenant(final @Nonnull String tenantIdentifier) { final Optional<TenantEntity> tenantEntity = tenantCassandraRepository.get(tenantIdentifier); tenantEntity.orElseThrow(() -> ServiceException.notFound("Tenant {0} not found.", tenantIdentifier)); } }
3,234
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/TenantService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service; import org.apache.fineract.cn.postgresql.util.PostgreSQLConstants; import org.apache.fineract.cn.provisioner.api.v1.domain.CassandraConnectionInfo; import org.apache.fineract.cn.provisioner.api.v1.domain.DatabaseConnectionInfo; import org.apache.fineract.cn.provisioner.api.v1.domain.Tenant; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.config.ProvisionerProperties; import org.apache.fineract.cn.provisioner.internal.repository.TenantCassandraRepository; import org.apache.fineract.cn.provisioner.internal.repository.TenantDAO; import org.apache.fineract.cn.provisioner.internal.repository.TenantEntity; import org.apache.fineract.cn.provisioner.internal.service.applications.IdentityServiceInitializer; import org.apache.fineract.cn.provisioner.internal.util.DataSourceUtils; import org.apache.fineract.cn.provisioner.internal.util.DataStoreOption; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.Nonnull; import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet; import org.apache.fineract.cn.anubis.repository.TenantAuthorizationDataRepository; import org.apache.fineract.cn.lang.AutoTenantContext; import org.apache.fineract.cn.lang.ServiceException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @SuppressWarnings({"SqlNoDataSourceInspection", "SqlDialectInspection"}) @Component public class TenantService { private static final String META_KEYSPACE = PostgreSQLConstants.POSTGRESQL_DATABASE_NAME_DEFAULT; private final Logger logger; private final Environment environment; private final TenantApplicationService tenantApplicationService; private final TenantAuthorizationDataRepository tenantAuthorizationDataRepository; private final TenantCassandraRepository tenantCassandraRepository; private final IdentityServiceInitializer identityServiceInitializer; private final ProvisionerProperties provisionerProperties; @Autowired public TenantService(@Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final Environment environment, final TenantApplicationService tenantApplicationService, @SuppressWarnings("SpringJavaAutowiringInspection") final TenantAuthorizationDataRepository tenantAuthorizationDataRepository, final TenantCassandraRepository tenantCassandraRepository, final IdentityServiceInitializer identityServiceInitializer, final ProvisionerProperties provisionerProperties) { super(); this.logger = logger; this.environment = environment; this.tenantApplicationService = tenantApplicationService; this.tenantAuthorizationDataRepository = tenantAuthorizationDataRepository; this.tenantCassandraRepository = tenantCassandraRepository; this.identityServiceInitializer = identityServiceInitializer; this.provisionerProperties = provisionerProperties; } public void create(final Tenant tenant) { this.initializeKeyspace(tenant); this.initializeDatabase(tenant); } private void initializeKeyspace(final @Nonnull Tenant tenant) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.CASSANDRA)) { final CassandraConnectionInfo cassandraConnectionInfo = tenant.getCassandraConnectionInfo(); final TenantEntity tenantEntity = new TenantEntity(); tenantEntity.setIdentifier(tenant.getIdentifier()); tenantEntity.setClusterName(cassandraConnectionInfo.getClusterName()); tenantEntity.setContactPoints(cassandraConnectionInfo.getContactPoints()); tenantEntity.setKeyspaceName(cassandraConnectionInfo.getKeyspace()); tenantEntity.setReplicationType(cassandraConnectionInfo.getReplicationType()); tenantEntity.setReplicas(cassandraConnectionInfo.getReplicas()); tenantEntity.setName(tenant.getName()); tenantEntity.setDescription(tenant.getDescription()); tenantEntity.setIdentityManagerApplicationName(null); //Identity manager can't be spun up till the org.apache.fineract.cn.provisioner.tenant is provisioned. tenantEntity.setIdentityManagerApplicationUri(null); //Identity manager can't be spun up till the org.apache.fineract.cn.provisioner.tenant is provisioned. tenantCassandraRepository.create(tenantEntity); } } public Optional<String> assignIdentityManager( final String tenantIdentifier, final String identityManagerAppName, final String identityManagerUri) { tenantCassandraRepository.adjust(tenantIdentifier, x -> { x.setIdentityManagerApplicationName(identityManagerAppName); x.setIdentityManagerApplicationUri(identityManagerUri); }); IdentityServiceInitializer.IdentityServiceInitializationResult identityServiceInitializationResult = identityServiceInitializer.initializeIsis(tenantIdentifier, identityManagerAppName, identityManagerUri); final ApplicationSignatureSet identityServiceTenantSignatureSet = identityServiceInitializationResult.getSignatureSet(); try (final AutoTenantContext ignored = new AutoTenantContext(tenantIdentifier)) { tenantAuthorizationDataRepository.createSignatureSet(identityServiceTenantSignatureSet.getTimestamp(), identityServiceTenantSignatureSet.getIdentityManagerSignature()); } return identityServiceInitializationResult.getAdminPassword(); } public List<Tenant> fetchAll() { final ArrayList<Tenant> result = new ArrayList<>(); this.fetchAllCassandra(result); this.fetchAllDatabase(result); return result; } private void fetchAllCassandra(final @Nonnull List<Tenant> tenants) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.CASSANDRA)) { List<TenantEntity> tenantEntities = tenantCassandraRepository.fetchAll(); for (final TenantEntity tenantEntity : tenantEntities) { final Tenant tenant = new Tenant(); tenants.add(tenant); tenant.setIdentifier(tenantEntity.getIdentifier()); tenant.setName(tenantEntity.getName()); tenant.setDescription(tenantEntity.getDescription()); tenant.setCassandraConnectionInfo(getCassandraConnectionInfoFromTenantEntity(tenantEntity)); } } } @SuppressWarnings("UnnecessaryLocalVariable") public Optional<Tenant> find(final @Nonnull String identifier) { final Optional<Tenant> tenantInCassandra = this.findCassandra(identifier); final Optional<Tenant> tenantInDatabase = tenantInCassandra.map(x -> this.findInDatabase(x, identifier)); return tenantInDatabase; } public void delete(final String identifier) { this.deleteFromCassandra(identifier); this.deleteDatabase(identifier); } private void fetchAllDatabase(final ArrayList<Tenant> tenants) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.RDBMS)) { if (tenants.size() > 0) { try (final Connection connection = DataSourceUtils.createProvisionerConnection(this.environment, META_KEYSPACE)) { for (final Tenant tenant : tenants) { final Optional<TenantDAO> optionalTenantDAO = TenantDAO.find(connection, tenant.getIdentifier()); optionalTenantDAO.ifPresent(tenantDAO -> tenant.setDatabaseConnectionInfo(tenantDAO.map())); } } catch (final SQLException sqlex) { this.logger.error(sqlex.getMessage(), sqlex); throw new IllegalStateException("Could not load org.apache.fineract.cn.provisioner.tenant data!"); } } else { try (final Connection connection = DataSourceUtils.createProvisionerConnection(this.environment, META_KEYSPACE)) { final List<TenantDAO> tenantDAOs = TenantDAO.fetchAll(connection); for (final TenantDAO tenantDAO : tenantDAOs) { final Tenant tenant = new Tenant(); tenants.add(tenant); tenant.setIdentifier(tenantDAO.getIdentifier()); tenant.setDatabaseConnectionInfo(tenantDAO.map()); } } catch (final SQLException sqlex) { this.logger.error(sqlex.getMessage(), sqlex); throw new IllegalStateException("Could not load org.apache.fineract.cn.provisioner.tenant data!"); } } } } private Optional<Tenant> findCassandra(final String identifier) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.CASSANDRA)) { return tenantCassandraRepository.get(identifier).map(x -> { final Tenant tenant = new Tenant(); tenant.setIdentifier(x.getIdentifier()); tenant.setName(x.getName()); tenant.setDescription(x.getDescription()); tenant.setCassandraConnectionInfo(getCassandraConnectionInfoFromTenantEntity(x)); return tenant; } ); } return Optional.empty(); } private Tenant findInDatabase(final @Nonnull Tenant tenant, final @Nonnull String identifier) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.RDBMS)) { try (final Connection connection = DataSourceUtils.createProvisionerConnection(this.environment, META_KEYSPACE)) { final Optional<TenantDAO> optionalTenantDAO = TenantDAO.find(connection, identifier); if (optionalTenantDAO.isPresent()) { tenant.setDatabaseConnectionInfo(optionalTenantDAO.get().map()); return tenant; } } catch (final SQLException sqlex) { this.logger.error(sqlex.getMessage(), sqlex); throw new IllegalStateException("Could not load org.apache.fineract.cn.provisioner.tenant data!"); } } return tenant; } private void initializeDatabase(final Tenant tenant) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.RDBMS)) { try ( final Connection provisionerConnection = DataSourceUtils.createProvisionerConnection(this.environment, META_KEYSPACE); final Statement statement = provisionerConnection.createStatement() ) { final ResultSet resultSet = statement.executeQuery( " SELECT * FROM tenants WHERE identifier = '" + tenant.getIdentifier() + "' "); if (resultSet.next()) { this.logger.warn("Tenant {} already exists !", tenant.getIdentifier()); throw ServiceException.conflict("Tenant {0} already exists!", tenant.getIdentifier()); } else { final DatabaseConnectionInfo databaseConnectionInfo = tenant.getDatabaseConnectionInfo(); this.logger.info("Create database for tenant {}", tenant.getIdentifier()); statement.execute("CREATE DATABASE " + databaseConnectionInfo.getDatabaseName().toLowerCase()); final TenantDAO tenantDAO = new TenantDAO(); tenantDAO.setIdentifier(tenant.getIdentifier()); tenantDAO.setDriverClass(databaseConnectionInfo.getDriverClass()); tenantDAO.setDatabaseName(databaseConnectionInfo.getDatabaseName()); tenantDAO.setHost(databaseConnectionInfo.getHost()); tenantDAO.setPort(databaseConnectionInfo.getPort()); tenantDAO.setUser(databaseConnectionInfo.getUser()); tenantDAO.setPassword(databaseConnectionInfo.getPassword()); tenantDAO.insert(provisionerConnection); } } catch (SQLException sqlex) { this.logger.error(sqlex.getMessage(), sqlex); throw new IllegalStateException("Could not provision database for tenant {}" + tenant.getIdentifier(), sqlex); } } else { this.logger.warn("Datastore option not chosen, Tenant in PostgreSQL RDBMS not created"); } } private void deleteFromCassandra(final @Nonnull String identifier) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.CASSANDRA)) { final Optional<TenantEntity> tenantEntity = tenantCassandraRepository.get(identifier); tenantEntity.ifPresent(x -> { tenantCassandraRepository.delete(identifier); this.tenantApplicationService.deleteTenant(identifier); }); } } private void deleteDatabase(final String identifier) { final DataStoreOption dataStoreOption = provisionerProperties.getDataStoreOption(); if (dataStoreOption.isEnabled(DataStoreOption.RDBMS)) { try (final Connection provisionerConnection = DataSourceUtils.createProvisionerConnection(this.environment, META_KEYSPACE)) { final Optional<TenantDAO> optionalTenantDAO = TenantDAO.find(provisionerConnection, identifier); if (optionalTenantDAO.isPresent()) { final DatabaseConnectionInfo databaseConnectionInfo = optionalTenantDAO.get().map(); try ( final Connection connection = DataSourceUtils.create(databaseConnectionInfo); final Statement dropStatement = connection.createStatement() ) { dropStatement.execute("DROP DATABASE " + databaseConnectionInfo.getDatabaseName()); } TenantDAO.delete(provisionerConnection, identifier); } } catch (final SQLException sqlex) { this.logger.error(sqlex.getMessage(), sqlex); throw new IllegalStateException("Could not delete database {}!" + identifier); } } else { this.logger.warn("Datastore option not chosen, Tenant in PostgreSQL RDBMS not created"); } } private static CassandraConnectionInfo getCassandraConnectionInfoFromTenantEntity(final TenantEntity tenantEntity) { final CassandraConnectionInfo cassandraConnectionInfo = new CassandraConnectionInfo(); cassandraConnectionInfo.setClusterName(tenantEntity.getClusterName()); cassandraConnectionInfo.setContactPoints(tenantEntity.getContactPoints()); cassandraConnectionInfo.setKeyspace(tenantEntity.getKeyspaceName()); cassandraConnectionInfo.setReplicationType(tenantEntity.getReplicationType()); cassandraConnectionInfo.setReplicas(tenantEntity.getReplicas()); return cassandraConnectionInfo; } }
3,235
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/AuthenticationService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.datastax.driver.core.utils.Bytes; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.MappingManager; import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse; import org.apache.fineract.cn.provisioner.api.v1.domain.PasswordPolicy; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.config.SystemProperties; import org.apache.fineract.cn.provisioner.internal.repository.ClientEntity; import org.apache.fineract.cn.provisioner.internal.repository.ConfigEntity; import org.apache.fineract.cn.provisioner.internal.repository.UserEntity; import org.apache.fineract.cn.provisioner.internal.util.TokenProvider; import java.nio.ByteBuffer; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import org.apache.fineract.cn.anubis.token.TokenSerializationResult; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.crypto.HashGenerator; import org.apache.fineract.cn.lang.ServiceException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.util.EncodingUtils; import org.springframework.stereotype.Service; import org.springframework.util.Base64Utils; @Service public class AuthenticationService { @Value("${spring.application.name}") private String applicationName; private final Integer ttl; private final Logger logger; private final CassandraSessionProvider cassandraSessionProvider; private final HashGenerator hashGenerator; private final TokenProvider tokenProvider; @Autowired public AuthenticationService(@Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final CassandraSessionProvider cassandraSessionProvider, final HashGenerator hashGenerator, final TokenProvider tokenProvider, final SystemProperties systemProperties) { super(); this.ttl = systemProperties.getToken().getTtl(); this.logger = logger; this.cassandraSessionProvider = cassandraSessionProvider; this.hashGenerator = hashGenerator; this.tokenProvider = tokenProvider; } public AuthenticationResponse authenticate( final @Nonnull String clientId, final @Nonnull String username, final @Nonnull String password) { final Session session = this.cassandraSessionProvider.getAdminSession(); final MappingManager mappingManager = new MappingManager(session); final Mapper<ClientEntity> clientEntityMapper = mappingManager.mapper(ClientEntity.class); if (clientEntityMapper.get(clientId) == null) { this.logger.warn("Authentication attempt with unknown client: " + clientId); throw ServiceException.notFound("Requested resource not found!"); } final Mapper<UserEntity> userEntityMapper = mappingManager.mapper(UserEntity.class); final Statement userQuery = userEntityMapper.getQuery(username); final ResultSet userResult = session.execute(userQuery); final Row userRow = userResult.one(); if (userRow == null) { this.logger.warn("Authentication attempt with unknown user: " + username); throw ServiceException.notFound("Requested resource not found!"); } final byte[] storedPassword = Bytes.getArray(userRow.getBytes(1)); final byte[] salt = Bytes.getArray(userRow.getBytes(2)); final int iterationCount = userRow.getInt(3); final int expiresInDays = userRow.getInt(4); final Date passwordResetOn = userRow.getTimestamp(5); final Mapper<ConfigEntity> configEntityMapper = mappingManager.mapper(ConfigEntity.class); final Statement configQuery = configEntityMapper.getQuery(ProvisionerConstants.CONFIG_INTERNAL); final ResultSet configResult = session.execute(configQuery); final Row configRow = configResult.one(); final byte[] secret = Bytes.getArray(configRow.getBytes(1)); if (this.hashGenerator.isEqual( storedPassword, Base64Utils.decodeFromString(password), secret, salt, iterationCount, 256)) { if (expiresInDays > 0) { final LocalDate ld = passwordResetOn.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); final LocalDate expiresOn = ld.plusDays(expiresInDays); if (LocalDate.now().isAfter(expiresOn)) { throw ServiceException.badRequest("Password expired"); } } final TokenSerializationResult authToken = this.tokenProvider.createToken(username, this.applicationName, this.ttl, TimeUnit.MINUTES); return new AuthenticationResponse(authToken.getToken(), dateTimeToString(authToken.getExpiration())); } else { throw ServiceException.notFound("Requested resource not found!"); } } private String dateTimeToString(final LocalDateTime dateTime) { return dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } public void updatePasswordPolicy(final String username, final PasswordPolicy passwordPolicy) { try { final Session session = this.cassandraSessionProvider.getAdminSession(); final MappingManager mappingManager = new MappingManager(session); final Mapper<UserEntity> userEntityMapper = mappingManager.mapper(UserEntity.class); final Statement userQuery = userEntityMapper.getQuery(username); final ResultSet userResult = session.execute(userQuery); final Row userRow = userResult.one(); if (userRow == null) { this.logger.warn("Authentication attempt with unknown user: " + username); throw ServiceException.notFound("Requested resource not found!"); } final byte[] salt = Bytes.getArray(userRow.getBytes(2)); final int iterationCount = userRow.getInt(3); final Mapper<ConfigEntity> configEntityMapper = mappingManager.mapper(ConfigEntity.class); final Statement configQuery = configEntityMapper.getQuery(ProvisionerConstants.CONFIG_INTERNAL); final ResultSet configResult = session.execute(configQuery); final Row configRow = configResult.one(); final byte[] secret = Bytes.getArray(configRow.getBytes(1)); if (passwordPolicy.getNewPassword() != null) { final byte[] newPasswordHash = this.hashGenerator.hash(passwordPolicy.getNewPassword(), EncodingUtils.concatenate(salt, secret), iterationCount, ProvisionerConstants.HASH_LENGTH); final BoundStatement updateStatement = session.prepare( "UPDATE users SET passwordWord = ?, password_reset_on = ? WHERE name = ?").bind(); updateStatement.setBytes(0, ByteBuffer.wrap(newPasswordHash)); updateStatement.setTimestamp(1, new Date()); updateStatement.setString(2, username); session.execute(updateStatement); } if (passwordPolicy.getExpiresInDays() != null) { final BoundStatement updateStatement = session.prepare( "UPDATE users SET expires_in_days = ? WHERE name = ?").bind(); updateStatement.setInt(0, passwordPolicy.getExpiresInDays()); updateStatement.setString(1, username); session.execute(updateStatement); } } catch (final Exception ex) { this.logger.error("Error updating password policy!", ex); throw ServiceException.internalError(ex.getMessage()); } } }
3,236
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/ApplicationService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service; import com.datastax.driver.core.ResultSet; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.internal.repository.ApplicationEntity; import java.util.ArrayList; import java.util.List; import org.apache.fineract.cn.cassandra.core.CassandraSessionProvider; import org.apache.fineract.cn.lang.ServiceException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class ApplicationService { private final Logger logger; private final CassandraSessionProvider cassandraSessionProvider; private final TenantApplicationService tenantApplicationService; @Autowired public ApplicationService(@Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final CassandraSessionProvider cassandraSessionProvider, final TenantApplicationService tenantApplicationService) { super(); this.logger = logger; this.cassandraSessionProvider = cassandraSessionProvider; this.tenantApplicationService = tenantApplicationService; } public void create(final ApplicationEntity applicationEntity) { final Mapper<ApplicationEntity> applicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ApplicationEntity.class); if (applicationEntityMapper.get(applicationEntity.getName()) != null) { this.logger.warn("Tried to create duplicate application {}!", applicationEntity.getName()); throw ServiceException.conflict("Application {0} already exists!", applicationEntity.getName()); } applicationEntityMapper.save(applicationEntity); } public ApplicationEntity find(final String name) { final Mapper<ApplicationEntity> applicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ApplicationEntity.class); final ApplicationEntity applicationEntity = applicationEntityMapper.get(name); if (applicationEntity == null) { this.logger.warn("Tried to find unknown application {}!", name); throw ServiceException.notFound("Application {0} not found!", name); } return applicationEntity; } public List<ApplicationEntity> fetchAll() { final ArrayList<ApplicationEntity> applicationEntities = new ArrayList<>(); final ResultSet resultSet = this.cassandraSessionProvider.getAdminSession().execute(" SELECT * FROM applications "); final Mapper<ApplicationEntity> applicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ApplicationEntity.class); if (resultSet != null) { final Result<ApplicationEntity> mappedApplicationEntities = applicationEntityMapper.map(resultSet); applicationEntities.addAll(mappedApplicationEntities.all()); } return applicationEntities; } public void delete(final String name) { final Mapper<ApplicationEntity> applicationEntityMapper = this.cassandraSessionProvider.getAdminSessionMappingManager().mapper(ApplicationEntity.class); applicationEntityMapper.delete(name); this.tenantApplicationService.removeApplication(name); } }
3,237
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/applications/AnubisInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service.applications; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import javax.annotation.Nonnull; import org.apache.fineract.cn.anubis.api.v1.client.Anubis; import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet; import org.apache.fineract.cn.anubis.api.v1.domain.Signature; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; /** * @author Myrle Krantz */ @Component public class AnubisInitializer { private final ApplicationCallContextProvider applicationCallContextProvider; private final Logger logger; @Autowired public AnubisInitializer( final ApplicationCallContextProvider applicationCallContextProvider, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger) { this.applicationCallContextProvider = applicationCallContextProvider; this.logger = logger; } public void initializeResources(@Nonnull String tenantIdentifier, @Nonnull String applicationName, @Nonnull String uri) { try (final AutoCloseable ignored = this.applicationCallContextProvider.getApplicationCallContext(tenantIdentifier, applicationName)) { final Anubis anubis = this.applicationCallContextProvider.getApplication(Anubis.class, uri); anubis.initializeResources(); logger.info("Anubis initializeResources for tenant '{}' and application '{}' succeeded.", tenantIdentifier, applicationName); } catch (final Exception e) { throw new IllegalStateException(e); } } public ApplicationSignatureSet createSignatureSet(@Nonnull String tenantIdentifier, @Nonnull String applicationName, @Nonnull String uri, @Nonnull String keyTimestamp, @Nonnull Signature signature) { try (final AutoCloseable ignored = this.applicationCallContextProvider.getApplicationCallContext(tenantIdentifier, applicationName)) { final Anubis anubis = this.applicationCallContextProvider.getApplication(Anubis.class, uri); final ApplicationSignatureSet applicationSignatureSet = anubis.createSignatureSet(keyTimestamp, signature); logger.info("Anubis createSignatureSet for tenant '{}' and application '{}' succeeded with signature set '{}'.", tenantIdentifier, applicationName, applicationSignatureSet); return applicationSignatureSet; } catch (final Exception e) { throw new IllegalStateException(e); } } }
3,238
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/applications/IdentityServiceInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service.applications; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.config.SystemProperties; import org.apache.fineract.cn.provisioner.internal.listener.IdentityListener; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import org.apache.finearct.cn.permittedfeignclient.api.v1.client.ApplicationPermissionRequirements; import org.apache.finearct.cn.permittedfeignclient.api.v1.domain.ApplicationPermission; import org.apache.fineract.cn.anubis.api.v1.client.Anubis; import org.apache.fineract.cn.anubis.api.v1.domain.AllowedOperation; import org.apache.fineract.cn.anubis.api.v1.domain.ApplicationSignatureSet; import org.apache.fineract.cn.anubis.api.v1.domain.PermittableEndpoint; import org.apache.fineract.cn.api.util.InvalidTokenException; import org.apache.fineract.cn.crypto.HashGenerator; import org.apache.fineract.cn.identity.api.v1.client.ApplicationPermissionAlreadyExistsException; import org.apache.fineract.cn.identity.api.v1.client.CallEndpointSetAlreadyExistsException; import org.apache.fineract.cn.identity.api.v1.client.IdentityManager; import org.apache.fineract.cn.identity.api.v1.client.PermittableGroupAlreadyExistsException; import org.apache.fineract.cn.identity.api.v1.domain.CallEndpointSet; import org.apache.fineract.cn.identity.api.v1.domain.Permission; import org.apache.fineract.cn.identity.api.v1.domain.PermittableGroup; import org.apache.fineract.cn.lang.ServiceException; import org.apache.fineract.cn.lang.TenantContextHolder; import org.apache.fineract.cn.lang.listening.EventExpectation; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; /** * @author Myrle Krantz */ @Component public class IdentityServiceInitializer { private final IdentityListener identityListener; private final ApplicationCallContextProvider applicationCallContextProvider; private final HashGenerator hashGenerator; private final Logger logger; private final SystemProperties systemProperties; public class IdentityServiceInitializationResult { private final ApplicationSignatureSet signatureSet; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private final Optional<String> adminPassword; private IdentityServiceInitializationResult(final ApplicationSignatureSet signatureSet, final String adminPassword) { this.signatureSet = signatureSet; this.adminPassword = Optional.of(adminPassword); } public ApplicationSignatureSet getSignatureSet() { return signatureSet; } public Optional<String> getAdminPassword() { return adminPassword; } } @Autowired public IdentityServiceInitializer( final IdentityListener identityListener, final ApplicationCallContextProvider applicationCallContextProvider, final HashGenerator hashGenerator, @Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final SystemProperties systemProperties) { this.identityListener = identityListener; this.applicationCallContextProvider = applicationCallContextProvider; this.hashGenerator = hashGenerator; this.logger = logger; this.systemProperties = systemProperties; } public IdentityServiceInitializationResult initializeIsis( final @Nonnull String tenantIdentifier, final @Nonnull String applicationName, final @Nonnull String identityManagerUri) { try (final AutoCloseable ignored = applicationCallContextProvider.getApplicationCallContext(tenantIdentifier, applicationName)) { final IdentityManager identityService = applicationCallContextProvider.getApplication(IdentityManager.class, identityManagerUri); // When running behind a gateway, calls to provisioner can be repeated multiple times. This leads // to repeated regeneration of the password, when only one password is returned. As a result the // real password gets replaced with a wrong one with a high probability. Provisioning scripts then // fail when they try to log in to identity for further provisioning. For this reason, return a // constant password, and change it immediately in the provisioning script. final String nonRandomPassword = "ChangeThisPassword"; this.logger.debug("Initial password for tenant super user '{}' is '{}'. This should be changed immediately.", tenantIdentifier, nonRandomPassword); final byte[] salt = Base64Utils.encode(("antony" + tenantIdentifier + this.systemProperties.getDomain()).getBytes()); final String encodedPassword = Base64Utils.encodeToString(nonRandomPassword.getBytes()); final byte[] hash = this.hashGenerator.hash(encodedPassword, salt, ProvisionerConstants.ITERATION_COUNT, ProvisionerConstants.HASH_LENGTH); final String encodedPasswordHash = Base64Utils.encodeToString(hash); final ApplicationSignatureSet signatureSet = identityService.initialize(encodedPasswordHash); logger.info("Isis initialization for org.apache.fineract.cn.provisioner.tenant '{}' succeeded with signature set '{}'.", tenantIdentifier, signatureSet); return new IdentityServiceInitializationResult(signatureSet, encodedPasswordHash); } catch (final InvalidTokenException e) { logger.warn("The given identity instance didn't recognize the system token as valid.", e); throw ServiceException .conflict("The given identity instance didn't recognize the system token as valid. " + "Perhaps the system keys for the provisioner or for the identity manager are misconfigured?"); } catch (final Exception e) { logger.error("An unexpected error occured while initializing identity.", e); throw new IllegalStateException(e); } } public List<EventExpectation> postApplicationPermittableGroups( final @Nonnull String tenantIdentifier, final @Nonnull String identityManagerApplicationName, final @Nonnull String identityManagerApplicationUri, final @Nonnull String applicationUri) { final List<PermittableEndpoint> permittables; try (final AutoCloseable ignored = applicationCallContextProvider.getApplicationCallGuestContext(tenantIdentifier)) { permittables = getPermittables(applicationUri); } catch (final Exception e) { throw new IllegalStateException(e); } try (final AutoCloseable ignored = applicationCallContextProvider.getApplicationCallContext(tenantIdentifier, identityManagerApplicationName)) { final IdentityManager identityService = applicationCallContextProvider.getApplication(IdentityManager.class, identityManagerApplicationUri); final Stream<PermittableGroup> permittableGroups = getPermittableGroups(permittables); //You might look at this and wonder: "Why isn't she returning a stream here? She's just turning it back into //a stream on the other side..." //The answer is that you need the createOrFindPermittableGroup to be executed in the proper tenant context. If you //return the stream, the call to createOrFindPermittableGroup will be executed when the stream is iterated over. return permittableGroups.map(x -> createOrFindPermittableGroup(identityService, x)).collect(Collectors.toList()); } catch (final Exception e) { throw new IllegalStateException(e); } } public void postApplicationDetails( final @Nonnull String tenantIdentifier, final @Nonnull String identityManagerApplicationName, final @Nonnull String identityManagerApplicationUri, final @Nonnull String applicationName, final @Nonnull String applicationUri, final @Nonnull ApplicationSignatureSet applicationSignatureSet) { final List<ApplicationPermission> applicationPermissionRequirements; try (final AutoCloseable ignored = applicationCallContextProvider.getApplicationCallGuestContext(tenantIdentifier)) { applicationPermissionRequirements = getApplicationPermissionRequirements(applicationName, applicationUri); logger.info("Application permission requirements for {} contain {}.", applicationName, applicationPermissionRequirements); } catch (final Exception e) { throw new IllegalStateException(e); } try (final AutoCloseable ignored = applicationCallContextProvider.getApplicationCallContext(tenantIdentifier, identityManagerApplicationName)) { final IdentityManager identityService = applicationCallContextProvider.getApplication(IdentityManager.class, identityManagerApplicationUri); final EventExpectation eventExpectation = identityListener.expectApplicationSignatureSet(tenantIdentifier, applicationName, applicationSignatureSet.getTimestamp()); identityService.setApplicationSignature(applicationName, applicationSignatureSet.getTimestamp(), applicationSignatureSet.getApplicationSignature()); if (!eventExpectation.waitForOccurrence(5, TimeUnit.SECONDS)) { logger.warn("Expected action in identity didn't complete {}.", eventExpectation); } applicationPermissionRequirements.forEach(x -> createOrFindApplicationPermission(identityService, applicationName, x)); final Stream<CallEndpointSet> callEndpoints = getCallEndpointSets(applicationPermissionRequirements); callEndpoints.forEach(x -> createOrFindApplicationCallEndpointSet(identityService, applicationName, x)); } catch (final Exception e) { throw new IllegalStateException(e); } } List<PermittableEndpoint> getPermittables(final @Nonnull String applicationUri) { try { final Anubis anubis = this.applicationCallContextProvider.getApplication(Anubis.class, applicationUri); return anubis.getPermittableEndpoints(); } catch (final RuntimeException unexpected) { logger.error("Request for permittable endpoints to '{}' failed.", applicationUri, unexpected); return Collections.emptyList(); } } private List<ApplicationPermission> getApplicationPermissionRequirements(final @Nonnull String applicationName, final @Nonnull String applicationUri) { try { final ApplicationPermissionRequirements anput = this.applicationCallContextProvider.getApplication(ApplicationPermissionRequirements.class, applicationUri); return anput.getRequiredPermissions(); } catch (final RuntimeException unexpected) { logger.info("Get Required Permissions from application '{}' failed.", applicationName); return Collections.emptyList(); } } static Stream<PermittableGroup> getPermittableGroups(final @Nonnull List<PermittableEndpoint> permittables) { final Map<String, Set<PermittableEndpoint>> groupedPermittables = new HashMap<>(); permittables.forEach(x -> groupedPermittables.computeIfAbsent(x.getGroupId(), y -> new LinkedHashSet<>()).add(x)); return groupedPermittables.entrySet().stream() .map(entry -> new PermittableGroup(entry.getKey(), new ArrayList<PermittableEndpoint>(entry.getValue()))); } private static Stream<CallEndpointSet> getCallEndpointSets( final @Nonnull List<ApplicationPermission> applicationPermissionRequirements) { final Map<String, List<String>> permissionsGroupedByEndpointSet = applicationPermissionRequirements.stream() .collect(Collectors.groupingBy(ApplicationPermission::getEndpointSetIdentifier, Collectors.mapping(x -> x.getPermission().getPermittableEndpointGroupIdentifier(), Collectors.toList()))); return permissionsGroupedByEndpointSet.entrySet().stream().map(entry -> { final CallEndpointSet ret = new CallEndpointSet(); ret.setIdentifier(entry.getKey()); ret.setPermittableEndpointGroupIdentifiers(entry.getValue()); return ret; }); } EventExpectation createOrFindPermittableGroup( final @Nonnull IdentityManager identityService, final @Nonnull PermittableGroup permittableGroup) { final EventExpectation eventExpectation = identityListener.expectPermittableGroupCreation(TenantContextHolder.checkedGetIdentifier(), permittableGroup.getIdentifier()); try { identityService.createPermittableGroup(permittableGroup); logger.info("Group '{}' creation successfully requested in identity service for tenant {}.", permittableGroup.getIdentifier(), TenantContextHolder.checkedGetIdentifier()); } catch (final PermittableGroupAlreadyExistsException groupAlreadyExistsException) { identityListener.withdrawExpectation(eventExpectation); //if the group already exists, read out and compare. If the group is the same, there is nothing left to do. final PermittableGroup existingGroup = identityService.getPermittableGroup(permittableGroup.getIdentifier()); if (!existingGroup.getIdentifier().equals(permittableGroup.getIdentifier())) { logger.error("Group '{}' already exists for tenant {}, but has a different name {} (strange).", permittableGroup.getIdentifier(), TenantContextHolder.checkedGetIdentifier(), existingGroup.getIdentifier()); } //Compare as sets because I'm not going to get into a hissy fit over order. final Set<PermittableEndpoint> existingGroupPermittables = new HashSet<>(existingGroup.getPermittables()); final Set<PermittableEndpoint> newGroupPermittables = new HashSet<>(permittableGroup.getPermittables()); if (!existingGroupPermittables.equals(newGroupPermittables)) { logger.warn("Group '{}' already exists for tenant {}, but has different contents. " + "Needed contents are '{}', existing contents are '{}'", permittableGroup.getIdentifier(), TenantContextHolder.checkedGetIdentifier(), newGroupPermittables, existingGroupPermittables); } } catch (final RuntimeException unexpected) { identityListener.withdrawExpectation(eventExpectation); logger.error("Creating group '{}' for tenant {} failed.", permittableGroup.getIdentifier(), TenantContextHolder.checkedGetIdentifier(), unexpected); } return eventExpectation; } private void createOrFindApplicationPermission( final @Nonnull IdentityManager identityService, final @Nonnull String applicationName, final @Nonnull ApplicationPermission applicationPermission) { try { identityService.createApplicationPermission(applicationName, applicationPermission.getPermission()); logger.info("Application permission '{}.{}' created.", applicationName, applicationPermission.getPermission().getPermittableEndpointGroupIdentifier()); } catch (final ApplicationPermissionAlreadyExistsException alreadyExistsException) { //if exists, read out and compare. If is the same, there is nothing left to do. final Permission existing = identityService.getApplicationPermission( applicationName, applicationPermission.getPermission().getPermittableEndpointGroupIdentifier()); if (!existing.getPermittableEndpointGroupIdentifier().equals(applicationPermission.getPermission().getPermittableEndpointGroupIdentifier())) { logger.error("Application permission '{}' already exists, but has a different name {} (strange).", applicationPermission.getPermission().getPermittableEndpointGroupIdentifier(), existing.getPermittableEndpointGroupIdentifier()); } final Set<AllowedOperation> existingAllowedOperations = existing.getAllowedOperations(); final Set<AllowedOperation> newAllowedOperations = applicationPermission.getPermission().getAllowedOperations(); if (!existingAllowedOperations.equals(newAllowedOperations)) { logger.error("Permission '{}' already exists, but has different contents.", applicationPermission.getPermission().getPermittableEndpointGroupIdentifier()); } } catch (final RuntimeException unexpected) { logger.error("Creating permission '{}' failed.", applicationPermission.getPermission().getPermittableEndpointGroupIdentifier(), unexpected); } } private void createOrFindApplicationCallEndpointSet( final @Nonnull IdentityManager identityService, final @Nonnull String applicationName, final @Nonnull CallEndpointSet callEndpointSet) { try { identityService.createApplicationCallEndpointSet(applicationName, callEndpointSet); } catch (final CallEndpointSetAlreadyExistsException alreadyExistsException) { //if already exists, read out and compare. If is the same, there is nothing left to do. final CallEndpointSet existing = identityService.getApplicationCallEndpointSet( applicationName, callEndpointSet.getIdentifier()); if (!existing.getIdentifier().equals(callEndpointSet.getIdentifier())) { logger.error("Application call endpoint set '{}' already exists, but has a different name {} (strange).", callEndpointSet.getIdentifier(), existing.getIdentifier()); } //Compare as sets because I'm not going to get into a hissy fit over order. final Set<String> existingPermittableEndpoints = new HashSet<>(existing.getPermittableEndpointGroupIdentifiers()); final Set<String> newPermittableEndpoints = new HashSet<>(callEndpointSet.getPermittableEndpointGroupIdentifiers()); if (!existingPermittableEndpoints.equals(newPermittableEndpoints)) { logger.error("Application call endpoint set '{}' already exists, but has different contents.", callEndpointSet.getIdentifier()); } } catch (final RuntimeException unexpected) { logger.error("Creating application call endpoint set '{}' failed.", callEndpointSet.getIdentifier(), unexpected); } } }
3,239
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/internal/service/applications/ApplicationCallContextProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.internal.service.applications; import org.apache.fineract.cn.provisioner.internal.util.TokenProvider; import org.apache.fineract.cn.anubis.api.v1.RoleConstants; import org.apache.fineract.cn.anubis.api.v1.TokenConstants; import org.apache.fineract.cn.api.context.AutoSeshat; import org.apache.fineract.cn.api.context.AutoUserContext; import org.apache.fineract.cn.api.util.ApiFactory; import org.apache.fineract.cn.lang.AutoTenantContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @SuppressWarnings("WeakerAccess") @Component public class ApplicationCallContextProvider { private final ApiFactory apiFactory; private final TokenProvider tokenProvider; static private class ApplicationCallContext implements AutoCloseable { private final AutoTenantContext tenantContext; private final AutoUserContext userContext; private ApplicationCallContext(final AutoTenantContext tenantContext, final AutoUserContext userContext) { this.tenantContext = tenantContext; this.userContext = userContext; } @Override public void close() { tenantContext.close(); userContext.close(); } } @Autowired public ApplicationCallContextProvider(final ApiFactory apiFactory, final TokenProvider tokenProvider) { super(); this.apiFactory = apiFactory; this.tokenProvider = tokenProvider; } public AutoCloseable getApplicationCallContext(final String tenantIdentifier, final String applicationName) { final String token = this.tokenProvider.createToken(tenantIdentifier, applicationName, 2L, TimeUnit.MINUTES).getToken(); final AutoTenantContext tenantContext = new AutoTenantContext(tenantIdentifier); final AutoUserContext userContext = new AutoSeshat(token); return new ApplicationCallContext(tenantContext, userContext); } public AutoCloseable getApplicationCallGuestContext(final String tenantIdentifier) { final AutoTenantContext tenantContext = new AutoTenantContext(tenantIdentifier); final AutoUserContext userContext = new AutoUserContext(RoleConstants.GUEST_USER_IDENTIFIER, TokenConstants.NO_AUTHENTICATION); return new ApplicationCallContext(tenantContext, userContext); } public <T> T getApplication(final Class<T> clazz, final String applicationUri) { return this.apiFactory.create(clazz, applicationUri); } }
3,240
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest/mapper/ClientMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.rest.mapper; import org.apache.fineract.cn.provisioner.api.v1.domain.Client; import org.apache.fineract.cn.provisioner.internal.repository.ClientEntity; public class ClientMapper { private ClientMapper() { super(); } public static Client map(final ClientEntity clientEntity) { final Client client = new Client(); client.setName(clientEntity.getName()); client.setDescription(clientEntity.getDescription()); client.setRedirectUri(clientEntity.getRedirectUri()); client.setVendor(clientEntity.getVendor()); client.setHomepage(clientEntity.getHomepage()); return client; } public static ClientEntity map(final Client client) { final ClientEntity clientEntity = new ClientEntity(); clientEntity.setName(client.getName()); clientEntity.setDescription(client.getDescription()); clientEntity.setRedirectUri(client.getRedirectUri()); clientEntity.setVendor(client.getVendor()); clientEntity.setHomepage(client.getHomepage()); return clientEntity; } }
3,241
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest/mapper/ApplicationMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.rest.mapper; import org.apache.fineract.cn.provisioner.api.v1.domain.Application; import org.apache.fineract.cn.provisioner.internal.repository.ApplicationEntity; public final class ApplicationMapper { private ApplicationMapper() { super(); } public static Application map(final ApplicationEntity applicationEntity) { final Application application = new Application(); application.setName(applicationEntity.getName()); application.setDescription(applicationEntity.getDescription()); application.setVendor(applicationEntity.getVendor()); application.setHomepage(applicationEntity.getHomepage()); return application; } public static ApplicationEntity map(final Application application) { final ApplicationEntity applicationEntity = new ApplicationEntity(); applicationEntity.setName(application.getName()); applicationEntity.setDescription(application.getDescription()); applicationEntity.setVendor(application.getVendor()); applicationEntity.setHomepage(application.getHomepage()); return applicationEntity; } }
3,242
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest/mapper/AssignedApplicationMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.rest.mapper; import org.apache.fineract.cn.provisioner.api.v1.domain.AssignedApplication; import org.apache.fineract.cn.provisioner.internal.repository.TenantApplicationEntity; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; public class AssignedApplicationMapper { private AssignedApplicationMapper() { super(); } public static TenantApplicationEntity map(final String identifier, final List<AssignedApplication> assignedApplications) { final TenantApplicationEntity tenantApplicationEntity = new TenantApplicationEntity(); tenantApplicationEntity.setTenantIdentifier(identifier); final HashSet<String> applicationNames = new HashSet<>(); tenantApplicationEntity.setApplications(applicationNames); applicationNames.addAll(assignedApplications .stream().map(AssignedApplication::getName) .collect(Collectors.toList())); return tenantApplicationEntity; } public static List<AssignedApplication> map(final TenantApplicationEntity tenantApplicationEntity) { final ArrayList<AssignedApplication> assignedApplications = new ArrayList<>(); if (tenantApplicationEntity != null) { for (final String name : tenantApplicationEntity.getApplications()) { final AssignedApplication assignedApplication = new AssignedApplication(); assignedApplications.add(assignedApplication); assignedApplication.setName(name); } } return assignedApplications; } }
3,243
0
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest
Create_ds/fineract-cn-provisioner/service/src/main/java/org/apache/fineract/cn/provisioner/rest/controller/ProvisionerRestController.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.provisioner.rest.controller; import org.apache.fineract.cn.provisioner.api.v1.domain.Application; import org.apache.fineract.cn.provisioner.api.v1.domain.AssignedApplication; import org.apache.fineract.cn.provisioner.api.v1.domain.AuthenticationResponse; import org.apache.fineract.cn.provisioner.api.v1.domain.Client; import org.apache.fineract.cn.provisioner.api.v1.domain.IdentityManagerInitialization; import org.apache.fineract.cn.provisioner.api.v1.domain.PasswordPolicy; import org.apache.fineract.cn.provisioner.api.v1.domain.Tenant; import org.apache.fineract.cn.provisioner.config.ProvisionerConstants; import org.apache.fineract.cn.provisioner.internal.repository.ClientEntity; import org.apache.fineract.cn.provisioner.internal.repository.TenantApplicationEntity; import org.apache.fineract.cn.provisioner.internal.service.ApplicationService; import org.apache.fineract.cn.provisioner.internal.service.AuthenticationService; import org.apache.fineract.cn.provisioner.internal.service.ClientService; import org.apache.fineract.cn.provisioner.internal.service.TenantApplicationService; import org.apache.fineract.cn.provisioner.internal.service.TenantService; import org.apache.fineract.cn.provisioner.rest.mapper.ApplicationMapper; import org.apache.fineract.cn.provisioner.rest.mapper.AssignedApplicationMapper; import org.apache.fineract.cn.provisioner.rest.mapper.ClientMapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.validation.Valid; import org.apache.fineract.cn.anubis.annotation.AcceptedTokenType; import org.apache.fineract.cn.anubis.annotation.Permittable; import org.apache.fineract.cn.lang.ServiceException; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @SuppressWarnings("unused") @RestController @RequestMapping("/") public class ProvisionerRestController { private final Logger logger; private final AuthenticationService authenticationService; private final ClientService clientService; private final TenantService tenantService; private final ApplicationService applicationService; private final TenantApplicationService tenantApplicationService; @Autowired public ProvisionerRestController(@Qualifier(ProvisionerConstants.LOGGER_NAME) final Logger logger, final AuthenticationService authenticationService, final ClientService clientService, final TenantService tenantService, final ApplicationService applicationService, final TenantApplicationService tenantApplicationService) { super(); this.logger = logger; this.authenticationService = authenticationService; this.clientService = clientService; this.tenantService = tenantService; this.applicationService = applicationService; this.tenantApplicationService = tenantApplicationService; } @Permittable(AcceptedTokenType.GUEST) @RequestMapping( value = "/auth/token", method = RequestMethod.POST, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<AuthenticationResponse> authenticate(@RequestParam("grant_type") final String grantType, @RequestParam("client_id") final String clientId, @RequestParam("username") final String username, @RequestParam("password") final String password) { if (!grantType.equals("password")) { this.logger.info("Authentication attempt with unknown grant type: " + grantType); throw ServiceException .badRequest("Authentication attempt with unknown grant type: {0}", grantType); } return ResponseEntity.ok(this.authenticationService.authenticate(clientId, username, password)); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/auth/user/{useridentifier}/password", method = RequestMethod.PUT, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> updatePasswordPolicy(@PathVariable("useridentifier") final String username, @RequestBody final PasswordPolicy passwordPolicy) { this.authenticationService.updatePasswordPolicy(username, passwordPolicy); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/clients", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<List<Client>> getClients() { final ArrayList<Client> result = new ArrayList<>(); final List<ClientEntity> clientEntities = this.clientService.fetchAll(); result.addAll(clientEntities .stream().map(ClientMapper::map) .collect(Collectors.toList())); return ResponseEntity.ok(result); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/clients", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> createClient(@RequestBody @Valid final Client client) { this.clientService.create(ClientMapper.map(client)); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/clients/{clientidentifier}", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Client> getClient(@PathVariable("clientidentifier") final String clientIdentifier) { return ResponseEntity.ok(ClientMapper.map(this.clientService.findByName(clientIdentifier))); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/clients/{clientidentifier}", method = RequestMethod.DELETE, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> deleteClient(@PathVariable("clientidentifier") final String clientIdentifier) { this.clientService.delete(clientIdentifier); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/tenants", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> createTenant(@RequestBody final Tenant tenant) { this.tenantService.create(tenant); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/tenants", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<List<Tenant>> getTenants() { return ResponseEntity.ok(this.tenantService.fetchAll()); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/tenants/{tenantidentifier}", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Tenant> getTenant(@PathVariable("tenantidentifier") final String tenantIdentifier) { final Optional<Tenant> result = this.tenantService.find(tenantIdentifier); if (result.isPresent()) { return ResponseEntity.ok(result.get()); } else { throw ServiceException.notFound("Tenant {0} not found!", tenantIdentifier); } } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/tenants/{tenantidentifier}", method = RequestMethod.DELETE, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> deleteTenant(@PathVariable("tenantidentifier") final String tenantIdentifier) { this.tenantService.delete(tenantIdentifier); return ResponseEntity.accepted().build(); } @RequestMapping( value = "tenants/{tenantidentifier}/identityservice", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE} ) ResponseEntity<IdentityManagerInitialization> assignIdentityManager(@PathVariable("tenantidentifier") final String tenantIdentifier, @RequestBody final AssignedApplication assignedApplication) { logger.info("Assigning identity manager for tenant '{}'.", tenantIdentifier); final String identityManagerUri = applicationService.find(assignedApplication.getName()).getHomepage(); final Optional<String> adminPassword = tenantService.assignIdentityManager( tenantIdentifier, assignedApplication.getName(), identityManagerUri); final IdentityManagerInitialization ret = new IdentityManagerInitialization(); ret.setAdminPassword(adminPassword.orElse("")); return ResponseEntity.ok(ret); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/applications", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> createApplication(@RequestBody final Application application) { this.applicationService.create(ApplicationMapper.map(application)); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/applications", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<List<Application>> getApplications() { return ResponseEntity.ok( this.applicationService.fetchAll() .stream().map(ApplicationMapper::map) .collect(Collectors.toList())); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/applications/{name}", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Application> getApplication(@PathVariable("name") final String name) { return ResponseEntity.ok(ApplicationMapper.map(this.applicationService.find(name))); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "/applications/{name}", method = RequestMethod.DELETE, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> deleteApplication(@PathVariable("name") final String name) { this.applicationService.delete(name); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "tenants/{tenantidentifier}/applications", method = RequestMethod.PUT, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<Void> assignApplications(@PathVariable("tenantidentifier") final String tenantIdentifier, @RequestBody final List<AssignedApplication> assignedApplications) { final TenantApplicationEntity tenantApplicationEntity = AssignedApplicationMapper.map(tenantIdentifier, assignedApplications); final Map<String, String> appNameToUriMap = new HashMap<>(); tenantApplicationEntity.getApplications().forEach( appName -> appNameToUriMap.put(appName, applicationService.find(appName).getHomepage())); tenantApplicationService.assign(tenantApplicationEntity, appNameToUriMap); return ResponseEntity.accepted().build(); } @Permittable(AcceptedTokenType.SYSTEM) @RequestMapping( value = "tenants/{tenantidentifier}/applications", method = RequestMethod.GET, consumes = {MediaType.ALL_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} ) public @ResponseBody ResponseEntity<List<AssignedApplication>> getAssignedApplications(@PathVariable("tenantidentifier") final String tenantIdentifier) { final TenantApplicationEntity tenantApplicationEntity = this.tenantApplicationService.find(tenantIdentifier); return ResponseEntity.ok(AssignedApplicationMapper.map(tenantApplicationEntity)); } }
3,244
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/org/omg/stub/java
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/org/omg/stub/java/rmi/_Remote_Stub.java
package org.omg.stub.java.rmi; import javax.rmi.CORBA.Stub; import java.rmi.Remote; public class _Remote_Stub extends Stub implements Remote { private static final String[] _type_ids = {}; public String[] _ids() { return _type_ids; } }
3,245
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/org/apache/yoko/rmispec
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/org/apache/yoko/rmispec/util/UtilLoader.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmispec.util; import org.apache.yoko.osgi.ProviderLocator; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.util.logging.Logger; import java.util.logging.Level; public class UtilLoader { static final Logger logger = Logger.getLogger(UtilLoader.class.getName()); // Note: this field must be declared before the static intializer that calls Util.loadClass // since that method will call loadClass0 which uses this field... if it is below the static // initializer the _secman field will be null private static final SecMan _secman = getSecMan(); static public Class<?> loadServiceClass(String delegateName, String delegateKey) throws ClassNotFoundException { try { Class<?> cls = ProviderLocator.getServiceClass(delegateKey, null, null); if (cls != null) { return cls; } } catch (ClassNotFoundException e){ // skip } return loadClass0(delegateName, null, null); } static public Class loadClass(String name, String codebase, ClassLoader loader) throws ClassNotFoundException { try { return ProviderLocator.loadClass(name, null, loader); } catch (ClassNotFoundException e) { //skip } return loadClass0(name, codebase, loader); } private static Class<?> loadClass0(String name, String codebase, ClassLoader loader) throws ClassNotFoundException { Class result = null; ClassLoader stackLoader = null; ClassLoader thisLoader = UtilLoader.class.getClassLoader(); Class[] stack = _secman.getClassContext(); for (int i = 1; i < stack.length; i++) { ClassLoader testLoader = stack[i].getClassLoader(); if (testLoader != null && testLoader != thisLoader) { stackLoader = thisLoader; break; } } if (stackLoader != null) { try { logger.finer("trying stack loader"); result = stackLoader.loadClass(name); } catch (ClassNotFoundException ex) { // skip // } if (result != null) { return result; } } // try loading using our loader, just in case we really were loaded // using the same classloader the delegate is in. if (thisLoader != null) { try { logger.finer("trying UtilLoader loader"); result = thisLoader.loadClass(name); } catch (ClassNotFoundException ex) { // skip // } if (result != null) { return result; } } if (codebase != null && !"".equals(codebase) && !Boolean.getBoolean("java.rmi.server.useCodeBaseOnly")) { try { logger.finer("trying RMIClassLoader"); URLClassLoader url_loader = new URLClassLoader( new URL[]{new URL(codebase)}, loader); result = url_loader.loadClass(name); // log.info("SUCESSFUL class download "+name+" from "+codebase, // new Throwable("TRACE")); } catch (ClassNotFoundException ex) { logger.log(Level.FINER, "RMIClassLoader says " + ex.getMessage(), ex); // log.info("FAILED class download "+name+" from "+codebase, // ex); // skip // } catch (MalformedURLException ex) { logger.log(Level.FINER, "RMIClassLoader says " + ex.getMessage(), ex); logger.finer("FAILED class download " + name + " from " + codebase + " " + ex.getMessage()); // skip // } catch (RuntimeException ex) { logger.log(Level.FINER, "FAILED class download " + name + " from " + codebase + " " + ex.getMessage(), ex); } if (result != null) { return result; } } else { codebase = (String) AccessController.doPrivileged(new GetSystemPropertyAction("java.rmi.server.codebase")); if (codebase != null) { try { result = java.rmi.server.RMIClassLoader.loadClass(codebase, name); } catch (ClassNotFoundException ex) { // skip // } catch (MalformedURLException ex) { // skip // } if (result != null) { return result; } } } if (loader == null) { loader = getContextClassLoader(); } if (loader != null) { try { logger.finer("trying local loader"); result = loader.loadClass(name); } catch (ClassNotFoundException ex) { logger.log(Level.FINER, "LocalLoader says " + ex.getMessage(), ex); } } if (result != null) { return result; } throw new ClassNotFoundException(name); } static ClassLoader getContextClassLoader() { return (ClassLoader) AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return Thread.currentThread().getContextClassLoader(); } }); } static class SecMan extends java.rmi.RMISecurityManager { public Class[] getClassContext() { return super.getClassContext(); } } private static SecMan getSecMan() { try { return (SecMan) AccessController .doPrivileged(new java.security.PrivilegedExceptionAction() { public Object run() { return new SecMan(); } }); } catch (PrivilegedActionException e) { throw new RuntimeException(e); } } }
3,246
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/org/apache/yoko/rmispec
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/org/apache/yoko/rmispec/util/GetSystemPropertyAction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmispec.util; import java.security.PrivilegedAction; /** * Simple utility class for retrieving a system property * value using the AccessController. */ public class GetSystemPropertyAction implements PrivilegedAction { // property name to retrieve String name; // potential default value String defaultValue = null; /** * Retrive a value using the name with no default value. * * @param name The property name. */ public GetSystemPropertyAction(String name) { this.name = name; this.defaultValue = null; } /** * Retrieve a property using a name and a specified default value. * * @param name The property name. * @param defaultValue * The default value if the property has not been set. */ public GetSystemPropertyAction(String name, String defaultValue) { this.name = name; this.defaultValue = defaultValue; } /** * Perform the AccessController action of retrieving the system property. * * @return The retrieved property. Returns either null or the * specified default value if this has not been set. */ public java.lang.Object run() { if (defaultValue == null) { return System.getProperty(name); } else { return System.getProperty(name, defaultValue); } } }
3,247
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/PortableRemoteObject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.NoSuchObjectException; import java.security.AccessController; import javax.rmi.CORBA.PortableRemoteObjectDelegate; import javax.rmi.CORBA.Util; import javax.rmi.CORBA.UtilDelegate; import org.apache.yoko.rmispec.util.GetSystemPropertyAction; import org.apache.yoko.rmispec.util.UtilLoader; public class PortableRemoteObject { private static PortableRemoteObjectDelegate delegate = null; private static final String defaultDelegate = "org.apache.yoko.rmi.impl.PortableRemoteObjectImpl"; private static final String DELEGATEKEY = "javax.rmi.CORBA.PortableRemoteObjectClass"; static { // Initialize delegate String delegateName = (String)AccessController.doPrivileged(new GetSystemPropertyAction(DELEGATEKEY, defaultDelegate)); try { delegate = (PortableRemoteObjectDelegate)UtilLoader.loadServiceClass(delegateName, DELEGATEKEY).newInstance(); } catch (Throwable e) { org.omg.CORBA.INITIALIZE ex = new org.omg.CORBA.INITIALIZE("Can not create PortableRemoteObject delegate: "+delegateName); ex.initCause(e); throw ex; } } protected PortableRemoteObject() throws RemoteException { // Register object exportObject((Remote)this); } public static void connect(Remote target, Remote source) throws RemoteException { delegate.connect(target, source); } public static void exportObject(Remote o) throws RemoteException { delegate.exportObject(o); } public static Object narrow(Object from, Class to) throws ClassCastException { return delegate.narrow(from, to); } public static Remote toStub(Remote o) throws NoSuchObjectException { return delegate.toStub(o); } public static void unexportObject(Remote o) throws NoSuchObjectException { delegate.unexportObject(o); } }
3,248
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/ValueHandlerMultiFormat.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.io.Serializable; import org.omg.CORBA.portable.OutputStream; public interface ValueHandlerMultiFormat extends ValueHandler { byte getMaximumStreamFormatVersion(); void writeValue(OutputStream os, Serializable val, byte streamVer); }
3,249
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/UtilDelegate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.NoSuchObjectException; import org.omg.CORBA.ORB; import org.omg.CORBA.SystemException; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; public interface UtilDelegate { Object copyObject(Object o, ORB orb) throws RemoteException; Object[] copyObjects(Object[] objs, ORB orb) throws RemoteException; ValueHandler createValueHandler(); String getCodebase(@SuppressWarnings("rawtypes") Class clz); Tie getTie(Remote t); boolean isLocal(Stub s) throws RemoteException; @SuppressWarnings("rawtypes") Class loadClass(String name, String codebase, ClassLoader loader) throws ClassNotFoundException; RemoteException mapSystemException(SystemException e); Object readAny(InputStream is); void registerTarget(Tie tie, Remote target); void unexportObject(Remote target) throws NoSuchObjectException; RemoteException wrapException(Throwable obj); void writeAbstractObject(OutputStream os, Object o); void writeAny(OutputStream os, Object o); void writeRemoteObject(OutputStream os, Object o); }
3,250
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/Util.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.NoSuchObjectException; import java.security.AccessController; import org.omg.CORBA.ORB; import org.omg.CORBA.SystemException; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; import org.apache.yoko.rmispec.util.GetSystemPropertyAction; import org.apache.yoko.rmispec.util.UtilLoader; public class Util { private static UtilDelegate delegate = null; private static final String defaultDelegate = "org.apache.yoko.rmi.impl.UtilImpl"; private static final String DELEGATEKEY = "javax.rmi.CORBA.UtilClass"; // To hide the default constructor we should implement empty private constructor private Util() {} static { // Initialize delegate String delegateName = (String)AccessController.doPrivileged(new GetSystemPropertyAction(DELEGATEKEY, defaultDelegate)); try { // this is a little bit recursive, but this will use the full default search order for locating // this. delegate = (UtilDelegate)UtilLoader.loadServiceClass(delegateName, DELEGATEKEY).newInstance(); } catch (Throwable e) { org.omg.CORBA.INITIALIZE ex = new org.omg.CORBA.INITIALIZE("Can not create Util delegate: "+delegateName); ex.initCause(e); throw ex; } } public static Object copyObject(Object o, ORB orb) throws RemoteException { return delegate.copyObject(o, orb); } public static Object[] copyObjects(Object[] objs, ORB orb) throws RemoteException { return delegate.copyObjects(objs, orb); } public static ValueHandler createValueHandler() { return delegate.createValueHandler(); } public static String getCodebase(Class clz) { return delegate.getCodebase(clz); } public static Tie getTie(Remote t) { return delegate.getTie(t); } public static boolean isLocal(Stub s) throws RemoteException { return delegate.isLocal(s); } public static Class loadClass(String name, String codebase, ClassLoader loader) throws ClassNotFoundException { if (delegate != null) { return delegate.loadClass(name, codebase, loader); } // Things get a little recursive here. We still need to use the full defined search order for loading // classes even when attempting to load the UtilDelegate itself. So, we're going to use the default // implementation for the bootstrapping. return UtilLoader.loadClass(name, codebase, loader); } public static RemoteException mapSystemException(SystemException e) { return delegate.mapSystemException(e); } public static Object readAny(InputStream is) { return delegate.readAny(is); } public static void registerTarget(Tie tie, Remote target) { delegate.registerTarget(tie, target); } public static void unexportObject(Remote t) throws NoSuchObjectException { delegate.unexportObject(t); } public static RemoteException wrapException(Throwable e) { return delegate.wrapException(e); } public static void writeAbstractObject(OutputStream os, Object o) { delegate.writeAbstractObject(os, o); } public static void writeAny(OutputStream os, Object o) { delegate.writeAny(os, o); } public static void writeRemoteObject(OutputStream os, Object o) { delegate.writeRemoteObject(os, o); } }
3,251
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/Stub.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.rmi.RemoteException; import java.security.AccessController; import org.apache.yoko.rmispec.util.GetSystemPropertyAction; import org.apache.yoko.rmispec.util.UtilLoader; import org.omg.CORBA.ORB; import org.omg.CORBA_2_3.portable.ObjectImpl; public abstract class Stub extends ObjectImpl implements Serializable { static final long serialVersionUID = 1087775603798577179L; private transient StubDelegate delegate = null; private static final String defaultDelegate = "org.apache.yoko.rmi.impl.StubImpl"; private static final String DELEGATEKEY = "javax.rmi.CORBA.StubClass"; // the class we use to create delegates. This is loaded once, private static Class delegateClass = null; static { // Initialize delegate String delegateName = (String)AccessController.doPrivileged(new GetSystemPropertyAction(DELEGATEKEY, defaultDelegate)); try { delegateClass = UtilLoader.loadServiceClass(delegateName, DELEGATEKEY); } catch (Exception e) { org.omg.CORBA.INITIALIZE ex = new org.omg.CORBA.INITIALIZE("Can not create Stub delegate: " + delegateName); ex.initCause(e); throw ex; } } public Stub() { super(); initializeDelegate(); } public void connect(ORB orb) throws RemoteException { initializeDelegate(); delegate.connect(this, orb); } public boolean equals(Object o) { initializeDelegate(); return delegate.equals(this, o); } public int hashCode() { initializeDelegate(); return delegate.hashCode(this); } public String toString() { initializeDelegate(); return delegate.toString(this); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { initializeDelegate(); delegate.readObject(this, ois); } private void writeObject(ObjectOutputStream oos) throws IOException { initializeDelegate(); delegate.writeObject(this, oos); } /** * Lazy initialization routine for the Stub delegate. Normally, you'd do this * in the constructor. Unfortunately, Java serialization will not call the * constructor for Serializable classes, so we need to ensure we have one * regardless of how/when we are called. */ private void initializeDelegate() { if (delegate == null) { try { delegate = (StubDelegate)delegateClass.newInstance(); } catch (Exception e) { throw (org.omg.CORBA.INITIALIZE)new org.omg.CORBA.INITIALIZE( "Can not create Stub delegate: " + delegateClass.getName()).initCause(e); } } } }
3,252
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/Tie.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.rmi.Remote; import java.rmi.NoSuchObjectException; import org.omg.CORBA.ORB; import org.omg.CORBA.portable.InvokeHandler; public interface Tie extends InvokeHandler { void deactivate() throws NoSuchObjectException; Remote getTarget(); ORB orb(); void orb(ORB orb); void setTarget(Remote target); org.omg.CORBA.Object thisObject(); }
3,253
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/ClassDesc.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.io.Serializable; public class ClassDesc implements Serializable { private String repid; private String codebase; }
3,254
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/StubDelegate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; import java.rmi.RemoteException; import org.omg.CORBA.ORB; public interface StubDelegate { void connect(Stub self, ORB orb) throws RemoteException; boolean equals(Stub self, Object o); int hashCode(Stub self); void readObject(Stub self, ObjectInputStream ois) throws IOException, ClassNotFoundException; String toString(Stub self); void writeObject(Stub self, ObjectOutputStream oos) throws IOException; }
3,255
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/ValueHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.io.Serializable; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; import org.omg.SendingContext.RunTime; public interface ValueHandler { String getRMIRepositoryID(Class clz); RunTime getRunTimeCodeBase(); boolean isCustomMarshaled(Class clz); Serializable readValue(InputStream is, int off, Class clz, String repID, RunTime sender); Serializable writeReplace(Serializable val); void writeValue(OutputStream os, Serializable val); }
3,256
0
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi
Create_ds/geronimo-yoko/yoko-rmi-spec/src/main/java/javax/rmi/CORBA/PortableRemoteObjectDelegate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.rmi.CORBA; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.NoSuchObjectException; public interface PortableRemoteObjectDelegate { void connect(Remote t, Remote s) throws RemoteException; void exportObject(Remote o) throws RemoteException; Object narrow(Object from, Class to) throws ClassCastException; Remote toStub(Remote o) throws NoSuchObjectException; void unexportObject(Remote o) throws NoSuchObjectException; }
3,257
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/TypeRepository.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.Externalizable; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.rmi.Remote; import java.rmi.RemoteException; import java.sql.Date; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.rmi.CORBA.ClassDesc; import org.apache.yoko.rmi.util.SearchKey; import org.apache.yoko.rmi.util.WeakKey; import org.omg.CORBA.MARSHAL; import org.omg.CORBA.ValueDefPackage.FullValueDescription; import org.omg.CORBA.portable.IDLEntity; import org.omg.SendingContext.CodeBase; import org.omg.SendingContext.CodeBaseHelper; import org.omg.SendingContext.RunTime; import org.apache.yoko.rmi.impl.TypeDescriptor.FullKey; import org.apache.yoko.rmi.impl.TypeDescriptor.SimpleKey; public class TypeRepository { static final Logger logger = Logger.getLogger(TypeRepository.class.getName()); private static final class TypeDescriptorCache { private final ConcurrentMap<WeakKey<FullKey>, WeakReference<TypeDescriptor>> map = new ConcurrentHashMap<>(); private final ReferenceQueue<FullKey> staleKeys = new ReferenceQueue<>(); public TypeDescriptor get(String repid) { cleanStaleKeys(); WeakReference<TypeDescriptor> ref = map.get(new SearchKey<SimpleKey>(new SimpleKey(repid))); return (null == ref) ? null : ref.get(); } public TypeDescriptor get(String repid, Class<?> localType) { cleanStaleKeys(); WeakReference<TypeDescriptor> ref = map.get(new SearchKey<FullKey>(new FullKey(repid, localType))); return (null == ref) ? null : ref.get(); } public void put(TypeDescriptor typeDesc) { cleanStaleKeys(); final WeakReference<TypeDescriptor> value = new WeakReference<>(typeDesc); map.putIfAbsent(new WeakKey<FullKey>(typeDesc.getKey(), staleKeys), value); } private void cleanStaleKeys() { for (Reference<? extends Object> staleKey = staleKeys.poll(); staleKey != null; staleKey = staleKeys.poll()) { map.remove(staleKey); } } } private static final class LocalDescriptors extends ClassValue<TypeDescriptor> { private static final class Raw extends ClassValue<TypeDescriptor> { private static final List<Class<?>> staticAnyTypes = Collections.unmodifiableList( Arrays.asList(Object.class, Externalizable.class, Serializable.class, Remote.class)); private final TypeRepository repo; Raw(TypeRepository repo) { this.repo = repo; } @Override protected TypeDescriptor computeValue(Class<?> type) { if (type.isPrimitive()) { return primitiveDescriptor(type); } else if (type == String.class) { return new StringDescriptor(repo); } else if (type == Class.class) { return new ClassDescriptor(repo); } else if (type == ClassDesc.class) { return new ClassDescDescriptor(repo); } else if (type == java.util.Date.class) { return new DateValueDescriptor(repo); } else if (staticAnyTypes.contains(type)) { return new AnyDescriptor(type, repo); } else if ((IDLEntity.class.isAssignableFrom(type)) && isIDLEntity(type)) { return new IDLEntityDescriptor(type, repo); } else if (Throwable.class.isAssignableFrom(type)) { return new ExceptionDescriptor(type, repo); } else if (Enum.class == type) { return new EnumDescriptor(type, repo); } else if (Enum.class.isAssignableFrom(type)) { Class<?> enumType = EnumSubclassDescriptor.getEnumType(type); return ((enumType == type) ? new EnumSubclassDescriptor(type, repo) : get(enumType)); } else if (type.isArray()) { return ArrayDescriptor.get(type, repo); } else if (Remote.class.isAssignableFrom(type)) { if (type.isInterface()) { return new RemoteInterfaceDescriptor(type, repo); } else { return new RemoteClassDescriptor(type, repo); } } else if (!type.isInterface() && Serializable.class.isAssignableFrom(type)) { return new ValueDescriptor(type, repo); } else if (Object.class.isAssignableFrom(type)) { if (isAbstractInterface(type)) { logger.finer("encoding " + type + " as abstract interface"); return new AbstractObjectDescriptor(type, repo); } else { logger.finer("encoding " + type + " as a abstract value"); return new ValueDescriptor(type, repo); } } else { throw new RuntimeException("cannot handle class " + type.getName()); } } private TypeDescriptor primitiveDescriptor(Class<?> type) { if (type == Boolean.TYPE) { return new BooleanDescriptor(repo); } else if (type == Byte.TYPE) { return new ByteDescriptor(repo); } else if (type == Short.TYPE) { return new ShortDescriptor(repo); } else if (type == Character.TYPE) { return new CharDescriptor(repo); } else if (type == Integer.TYPE) { return new IntegerDescriptor(repo); } else if (type == Long.TYPE) { return new LongDescriptor(repo); } else if (type == Float.TYPE) { return new FloatDescriptor(repo); } else if (type == Double.TYPE) { return new DoubleDescriptor(repo); } else if (type == Void.TYPE) { return new VoidDescriptor(repo); } else { throw new RuntimeException("internal error: " + type); } } private static boolean isIDLEntity(Class<?> type) { for (Class<?> intf : type.getInterfaces()) { if (intf.equals(IDLEntity.class)) return true; } return false; } private static boolean isAbstractInterface(Class<?> type) { if (!type.isInterface()) return false; for (Class<?> intf : type.getInterfaces()) { if (!isAbstractInterface(intf)) return false; } for (Method method : type.getDeclaredMethods()) { if (!isRemoteMethod(method)) return false; } return true; } private static boolean isRemoteMethod(java.lang.reflect.Method m) { for (Class<?> exceptionType : m.getExceptionTypes()) { if (exceptionType.isAssignableFrom(RemoteException.class)) return true; } return false; } } private final Raw rawValues; private final TypeDescriptorCache repIdDescriptors; LocalDescriptors(TypeRepository repo, TypeDescriptorCache repIdDescriptors) { rawValues = new Raw(repo); this.repIdDescriptors = repIdDescriptors; } @Override protected TypeDescriptor computeValue(Class<?> type) { final TypeDescriptor desc = rawValues.get(type); desc.init(); repIdDescriptors.put(desc); return desc; } } private static final class FvdRepIdDescriptorMaps extends ClassValue<ConcurrentMap<String,ValueDescriptor>> { @Override protected ConcurrentMap<String,ValueDescriptor> computeValue( Class<?> type) { return new ConcurrentHashMap<String,ValueDescriptor>(1); } } private final TypeDescriptorCache repIdDescriptors; private final LocalDescriptors localDescriptors; private final FvdRepIdDescriptorMaps fvdDescMaps = new FvdRepIdDescriptorMaps(); private final ConcurrentMap<String,ValueDescriptor> noTypeDescMap = new ConcurrentHashMap<String,ValueDescriptor>(); private static final Set<Class<?>> initTypes; static { initTypes = createClassSet(Object.class, String.class, ClassDesc.class, Date.class, Externalizable.class, Serializable.class, Remote.class); } private static Set<Class<?>> createClassSet(Class<?>...types) { return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(types))); } private TypeRepository() { repIdDescriptors = new TypeDescriptorCache(); localDescriptors = new LocalDescriptors(this, repIdDescriptors); for (Class<?> type: initTypes) { localDescriptors.get(type); } } private static enum RepoHolder { ; static final TypeRepository value = new TypeRepository(); } public static TypeRepository get() { return RepoHolder.value; } public String getRepositoryID(Class<?> type) { return getDescriptor(type).getRepositoryID(); } public RemoteInterfaceDescriptor getRemoteInterface(Class<?> type) { return getDescriptor(type).getRemoteInterface(); } public TypeDescriptor getDescriptor(Class<?> type) { if (logger.isLoggable(Level.FINE)) logger.fine(String.format("Requesting type descriptor for class \"%s\"", type.getName())); final TypeDescriptor desc = localDescriptors.get(type); if (logger.isLoggable(Level.FINE)) logger.fine(String.format("Class \"%s\" resolves to %s", type.getName(), desc)); return desc; } public TypeDescriptor getDescriptor(String repId) { if (logger.isLoggable(Level.FINE)) logger.fine(String.format("Requesting type descriptor for repId \"%s\"", repId)); final TypeDescriptor desc = repIdDescriptors.get(repId); if (logger.isLoggable(Level.FINE)) logger.fine(String.format("RepId \"%s\" resolves to %s", repId, desc)); return desc; } /** * @param clz (local) class we are interested in * @param repid repository id from GIOP input for the remote class * @param runtime way to look up the complete remote descriptor * @return ValueDescriptor * @throws ClassNotFoundException something might go wrong. */ public ValueDescriptor getDescriptor(Class<?> clz, String repid, RunTime runtime) throws ClassNotFoundException { if (repid == null) { return (ValueDescriptor) getDescriptor(clz); } ValueDescriptor clzdesc = (ValueDescriptor) repIdDescriptors.get(repid, clz); if (clzdesc != null) { return clzdesc; } if (clz != null) { logger.fine("Requesting type descriptor for class " + clz.getName() + " with repid " + repid); // special handling for array value types. if (clz.isArray()) { //TODO don't we need to look up the FVD for the array element? return (ValueDescriptor) localDescriptors.get(clz); } clzdesc = (ValueDescriptor) getDescriptor(clz); String localID = clzdesc.getRepositoryID(); if (repid.equals(localID)) { return clzdesc; } //One might think that java serialization compatibility (same SerialVersionUID) would mean corba //serialization compatibility. However, one implementation might have a writeObject method and the //other implementation not. This is recorded only in the isCustomMarshall of the source value //descriptor, so we have to fetch it to find out. A custom marshall value has a couple extra bytes // and padding and these can't be reliably identified without this remote info. cf YOKO-434. } logger.fine("Requesting type descriptor for repid " + repid); CodeBase codebase = CodeBaseHelper.narrow(runtime); if (codebase == null) { throw new MARSHAL("cannot locate RunTime CodeBase"); } FullValueDescription fvd = codebase.meta(repid); ValueDescriptor super_desc = null; if (!"".equals(fvd.base_value)) { super_desc = getDescriptor(clz == null? null: clz.getSuperclass(), fvd.base_value, codebase); } final ValueDescriptor newDesc; if ((super_desc != null) && super_desc.isEnum()) { newDesc = new FVDEnumSubclassDescriptor(fvd, clz, this, repid, super_desc); } else if (fvd.id.startsWith("RMI:java.lang.Enum:")) { newDesc = new FVDEnumDescriptor(fvd, clz, this, repid, super_desc); } else { newDesc = new FVDValueDescriptor(fvd, clz, this, repid, super_desc); } ConcurrentMap<String, ValueDescriptor> remoteDescMap = (clz == null) ? noTypeDescMap : fvdDescMaps.get(clz); clzdesc = remoteDescMap.putIfAbsent(newDesc.getRepositoryID(), newDesc); if (clzdesc == null) { clzdesc = newDesc; repIdDescriptors.put(clzdesc); } return clzdesc; } }
3,258
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ClosedObjectReader.java
package org.apache.yoko.rmi.impl; import java.io.Externalizable; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputValidation; import java.rmi.Remote; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Logger; import org.omg.CORBA.portable.IndirectionException; class ClosedObjectReader extends ObjectReader { private static final Logger LOGGER = Logger.getLogger(ClosedObjectReader.class.getName()); public static final ClosedObjectReader INSTANCE = AccessController.doPrivileged(new PrivilegedAction<ClosedObjectReader>() { @Override public ClosedObjectReader run() { try { return new ClosedObjectReader(); } catch (IOException e) { LOGGER.severe("Unable to create ClosedObjectInputStream singleton instance: " + e); return null; } } }); private ClosedObjectReader() throws IOException { } private IllegalStateException newException() { return new IllegalStateException("Stream already closed"); } public void close() { } ////////////////////////////////////// // ONLY DELEGATE METHODS BELOW HERE // ////////////////////////////////////// public int read(byte[] b) { throw newException(); } public long skip(long n) { throw newException(); } public void mark(int readlimit) { throw newException(); } public void reset() { throw newException(); } public boolean markSupported() { throw newException(); } public Object readUnshared() { throw newException(); } public void defaultReadObject() { throw newException(); } public GetField readFields() { throw newException(); } public void registerValidation(ObjectInputValidation obj, int prio) { throw newException(); } public int read() { throw newException(); } public int read(byte[] buf, int off, int len) { throw newException(); } public int available() { throw newException(); } public boolean readBoolean() { throw newException(); } public byte readByte() { throw newException(); } public int readUnsignedByte() { throw newException(); } public char readChar() { throw newException(); } public short readShort() { throw newException(); } public int readUnsignedShort() { throw newException(); } public int readInt() { throw newException(); } public long readLong() { throw newException(); } public float readFloat() { throw newException(); } public double readDouble() { throw newException(); } public void readFully(byte[] buf) { throw newException(); } public void readFully(byte[] buf, int off, int len) { throw newException(); } public int skipBytes(int len) { throw newException(); } public String readLine() { throw newException(); } public String readUTF() { throw newException(); } // ObjectReader methods void _startValue() { throw newException(); } void _endValue() { throw newException(); } void setCurrentValueDescriptor(ValueDescriptor desc) { throw newException(); } Object readAbstractObject() { throw newException(); } Object readAny() { throw newException(); } Object readValueObject() { throw newException(); } Object readValueObject(Class<?> clz) { throw newException(); } org.omg.CORBA.Object readCorbaObject(Class<?> type) { throw newException(); } Remote readRemoteObject(Class<?> type) { throw newException(); } void readExternal(Externalizable ext) { throw newException(); } @Override protected final Object readObjectOverride() { throw newException(); } }
3,259
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/DateValueDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.util.Date; /** * @author krab * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of type * comments go to Window>Preferences>Java>Code Generation. */ class DateValueDescriptor extends ValueDescriptor { /** * Constructor for DateValueDescriptor. * * @param repository */ public DateValueDescriptor(TypeRepository repository) { super(Date.class, repository); } Object copyObject(Object orig, CopyState state) { Date result = (Date) (((Date) orig).clone()); state.put(orig, result); return result; } }
3,260
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RunTimeCodeBaseImpl.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.omg.CORBA.ValueDefPackage.FullValueDescription; class RunTimeCodeBaseImpl extends org.omg.SendingContext.CodeBasePOA { ValueHandlerImpl valueHandler; RunTimeCodeBaseImpl(ValueHandlerImpl handler) { valueHandler = handler; } public String implementation(String id) { return valueHandler.getImplementation(id); } public String[] implementations(String[] ids) { return valueHandler.getImplementations(ids); } public String[] bases(String id) { return valueHandler.getBases(id); } public org.omg.CORBA.Repository get_ir() { throw new org.omg.CORBA.NO_IMPLEMENT(); } public org.omg.CORBA.ValueDefPackage.FullValueDescription meta(String id) { return valueHandler.meta(id); } public org.omg.CORBA.ValueDefPackage.FullValueDescription[] metas(String id) { String[] bases = bases(id); org.omg.CORBA.ValueDefPackage.FullValueDescription[] descriptors = new org.omg.CORBA.ValueDefPackage.FullValueDescription[bases.length]; for (int i = bases.length - 1; i >= 0; i--) { descriptors[i] = meta(bases[i]); } return descriptors; } public String implementationx(String arg0) { // TODO Auto-generated method stub return null; } public FullValueDescription[] metas(String[] arg0) { // TODO Auto-generated method stub return null; } }
3,261
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIServant.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.lang.reflect.Method; import java.util.logging.Logger; import java.util.logging.Level; import org.omg.CORBA.OBJECT_NOT_EXIST; import org.omg.CORBA.portable.Delegate; import org.omg.PortableServer.POA; import org.omg.PortableServer.POAHelper; public class RMIServant extends org.omg.PortableServer.Servant implements javax.rmi.CORBA.Tie { static final Logger logger = Logger.getLogger(RMIServant.class.getName()); RMIState _state; RemoteDescriptor _descriptor; byte[] _id; Class getJavaClass() { return _descriptor.type; } RMIState getRMIState() { return _state; } public RMIServant(RMIState state) { _state = state; } private java.rmi.Remote _target = null; /** this implements the sole missing method in javax.rmi.CORBA.Tie */ public String[] _all_interfaces(final org.omg.PortableServer.POA poa, final byte[] objectId) { return _descriptor.all_interfaces(); } static String debug_name(Method m) { return m.getDeclaringClass().getName() + "." + m.getName(); } /** * this implements the sole missing method in * org.omg.CORBA.portable.InvokeHandler */ public org.omg.CORBA.portable.OutputStream _invoke(java.lang.String opName, org.omg.CORBA.portable.InputStream _input, org.omg.CORBA.portable.ResponseHandler response) throws org.omg.CORBA.SystemException { MethodDescriptor method = _descriptor.getMethod(opName); if (method == null) { _descriptor.debugMethodMap(); throw new org.omg.CORBA.BAD_OPERATION(opName); } java.lang.reflect.Method m = method.getReflectedMethod(); logger.finer(debug_name(m) + ": invoking on " + _id); try { Object[] args = method.readArguments(_input); Object result = invoke_method(m, args); org.omg.CORBA.portable.OutputStream _out = response.createReply(); method.writeResult(_out, result); logger.finer(debug_name(m) + ": returning normally"); return _out; } catch (org.omg.CORBA.SystemException ex) { logger.throwing(RMIServant.class.getName(), "_invoke", ex); logger.warning(ex.getMessage()); throw ex; } catch (java.lang.reflect.UndeclaredThrowableException ex) { logger.throwing(RMIServant.class.getName(), "_invoke", ex .getUndeclaredThrowable()); throw new org.omg.CORBA.portable.UnknownException(ex .getUndeclaredThrowable()); } catch (RuntimeException ex) { logger.log(Level.FINER, debug_name(m) + ": RuntimeException " + ex.getMessage(), ex); return method.writeException(response, ex); } catch (java.rmi.RemoteException ex) { logger.log(Level.FINER, debug_name(m) + ": RemoteException " + ex.getMessage(), ex); // return method.writeException (response, ex); throw UtilImpl.mapRemoteException(ex); } catch (Throwable ex) { logger.log(Level.FINER, debug_name(m) + ": Throwable " + ex.getMessage(), ex); return method.writeException(response, ex); } finally { // PortableRemoteObjectExt.popState(); } } /* package */ Object invoke_method(java.lang.reflect.Method m, Object[] args) throws java.rmi.RemoteException, Throwable { if (_target != null) { try { return m.invoke(_target, args); } catch (java.lang.reflect.InvocationTargetException ex) { logger.log(Level.FINER, "Error invoking local method", ex.getCause()); throw ex.getTargetException(); } } else { throw new OBJECT_NOT_EXIST(); } } public org.omg.CORBA.ORB orb() { return _orb(); } public void orb(org.omg.CORBA.ORB orb) { try { POA _poa = POAHelper.narrow(orb .resolve_initial_references("RootPOA")); _poa.activate_object(this); } catch (org.omg.CORBA.ORBPackage.InvalidName ex) { throw new RuntimeException("ORB must have POA support", ex); } catch (org.omg.PortableServer.POAPackage.WrongPolicy ex) { throw new RuntimeException("wrong policy: " + ex.getMessage(), ex); } catch (org.omg.PortableServer.POAPackage.ServantAlreadyActive ex) { throw new RuntimeException("already active: " + ex.getMessage(), ex); } } public void deactivate() { if (_get_delegate() == null) throw new RuntimeException("object not active"); try { org.omg.PortableServer.POA poa = _state.getPOA(); byte[] id = poa.servant_to_id(this); poa.deactivate_object(id); _set_delegate(null); } catch (Throwable ex) { logger.throwing("", "deactivate", ex); throw new RuntimeException("cannot deactivate: " + ex.getMessage(), ex); } } public java.rmi.Remote getTarget() { return _target; } public synchronized void setTarget(java.rmi.Remote target) { if (target == null) { throw new IllegalArgumentException(); } _descriptor = _state.repo.getRemoteInterface(target.getClass()).getRemoteInterface(); if (_descriptor == null) { throw new RuntimeException("remote classes not supported"); } _target = target; } Delegate getDelegate() { return _state.createDelegate(this); } public org.omg.CORBA.Object thisObject() { return _this_object(); } }
3,262
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/CorbaObjectWriter.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.IOException; import java.util.logging.Logger; import java.util.logging.Level; import org.omg.CORBA.INTERNAL; public final class CorbaObjectWriter extends ObjectWriter { static Logger logger = Logger.getLogger(CorbaObjectWriter.class.getName()); final org.omg.CORBA_2_3.portable.OutputStream out; CorbaObjectWriter(org.omg.CORBA.portable.OutputStream out, java.io.Serializable obj) throws java.io.IOException { super(obj); this.out = (org.omg.CORBA_2_3.portable.OutputStream) out; } public void write(int val) throws java.io.IOException { beforeWriteData(); out.write_octet((byte) val); } public void write(byte[] val) throws java.io.IOException { beforeWriteData(); write(val, 0, val.length); } public void write(byte[] arr, int off, int len) throws java.io.IOException { beforeWriteData(); out.write_octet_array(arr, off, len); } public void writeBoolean(boolean val) throws java.io.IOException { beforeWriteData(); out.write_boolean(val); } public void writeByte(int val) throws java.io.IOException { beforeWriteData(); out.write_octet((byte) val); } public void writeShort(int val) throws java.io.IOException { beforeWriteData(); out.write_short((short) val); } public void writeChar(int val) throws java.io.IOException { beforeWriteData(); out.write_wchar((char) val); } public void writeInt(int val) throws java.io.IOException { beforeWriteData(); out.write_long(val); } public void writeLong(long val) throws java.io.IOException { beforeWriteData(); out.write_longlong(val); } public void writeFloat(float val) throws java.io.IOException { beforeWriteData(); out.write_float(val); } public void writeDouble(double val) throws java.io.IOException { beforeWriteData(); out.write_double(val); } public void writeBytes(java.lang.String val) throws java.io.IOException { for (int i = 0; i < val.length(); i++) { writeByte((int) val.charAt(i)); } } public void writeChars(java.lang.String val) throws java.io.IOException { for (int i = 0; i < val.length(); i++) { writeChar((int) val.charAt(i)); } } public void writeUTF(java.lang.String val) throws java.io.IOException { beforeWriteData(); out.write_wstring(val); } public void writeObjectOverride(Object obj) throws IOException { beforeWriteData(); try { javax.rmi.CORBA.Util.writeAbstractObject(out, obj); } catch (Error err) { logger.log(Level.FINE, "exception in writeObjectOverride", err); throw err; } } public void writeValueObject(Object obj) throws IOException { beforeWriteData(); try { out.write_value((java.io.Serializable) obj); } catch (Error err) { logger.log(Level.FINE, "exception in writeValueObject", err); throw err; } } public void writeCorbaObject(Object obj) throws IOException { beforeWriteData(); javax.rmi.CORBA.Util.writeRemoteObject(out, obj); } public void writeRemoteObject(Object obj) throws IOException { beforeWriteData(); javax.rmi.CORBA.Util.writeRemoteObject(out, obj); } public void writeAny(Object obj) throws IOException { beforeWriteData(); javax.rmi.CORBA.Util.writeAny(out, obj); } public ObjectReader getObjectReader(Object newObject) { throw new INTERNAL("cannot do this"); } /* * (non-Javadoc) * * @see org.apache.yoko.rmi.impl.ObjectWriter#_startValue() */ protected void _startValue(String repID) throws IOException { org.omg.CORBA.portable.ValueOutputStream vout = (org.omg.CORBA.portable.ValueOutputStream) out; vout.start_value(repID); } /* * (non-Javadoc) * * @see org.apache.yoko.rmi.impl.ObjectWriter#_endValue() */ protected void _endValue() throws IOException { org.omg.CORBA.portable.ValueOutputStream vout = (org.omg.CORBA.portable.ValueOutputStream) out; vout.end_value(); } /* * (non-Javadoc) * * @see org.apache.yoko.rmi.impl.ObjectWriter#_nullValue() */ protected void _nullValue() throws IOException { out.write_long(0); } }
3,263
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/CopyRecursionResolver.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; public abstract class CopyRecursionResolver { CopyRecursionResolver next; public final Object orig; CopyRecursionResolver(Object orig) { this.orig = orig; } abstract void resolve(Object copy); }
3,264
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/CorbaObjectReader.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.omg.CORBA.MARSHAL; import org.omg.CORBA.portable.IndirectionException; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.ValueInputStream; import javax.rmi.CORBA.Util; import javax.rmi.PortableRemoteObject; import java.io.IOException; import java.io.Serializable; import java.rmi.Remote; import java.util.Map; public class CorbaObjectReader extends ObjectReaderBase { final org.omg.CORBA_2_3.portable.InputStream in; private final Map<Integer, Object> offsetMap; CorbaObjectReader(InputStream in, Map<Integer, Object> offsetMap, Serializable obj) throws IOException { super(obj); this.in = (org.omg.CORBA_2_3.portable.InputStream) in; this.offsetMap = offsetMap; } public void readFully(byte[] arr, int off, int val) throws IOException { in.read_octet_array(arr, off, val); } public int skipBytes(int len) throws IOException { final byte[] data = new byte[len]; readFully(data, 0, len); return len; } public boolean readBoolean() throws IOException { return in.read_boolean(); } public byte readByte() throws IOException { return in.read_octet(); } public int readUnsignedByte() throws IOException { final int val = in.read_octet(); return val & 0xff; } public short readShort() throws IOException { return in.read_short(); } public int readUnsignedShort() throws IOException { final int val = in.read_short(); return val & 0xffff; } public char readChar() throws IOException { return in.read_wchar(); } public int readInt() throws IOException { return in.read_long(); } public long readLong() throws IOException { return in.read_longlong(); } public float readFloat() throws IOException { return in.read_float(); } public double readDouble() throws IOException { return in.read_double(); } @Deprecated public String readLine() throws IOException { final StringBuilder buf = new StringBuilder(); char ch; try { ch = (char) readUnsignedByte(); } catch (MARSHAL ex) { return null; } do { buf.append(ch); try { ch = (char) readUnsignedByte(); } catch (MARSHAL ex) { // reached EOF return buf.toString(); } if (ch == '\n') { return buf.toString(); } if (ch == '\r') { final char ch2; try { ch2 = (char) readUnsignedByte(); } catch (MARSHAL ex) { // reached EOF return buf.toString(); } if (ch2 == '\n') { return buf.toString(); } else { ch = ch2; } } } while (true); } public String readUTF() throws IOException { return in.read_wstring(); } public Object readAbstractObject() throws IndirectionException { try { return in.read_abstract_interface(); } catch (IndirectionException ex) { return offsetMap.get(ex.offset); } } public Object readAny() throws IndirectionException { try { return Util.readAny(in); } catch (IndirectionException ex) { return offsetMap.get(ex.offset); } } public Object readValueObject() throws IndirectionException { try { return in.read_value(); } catch (IndirectionException ex) { return offsetMap.get(ex.offset); } } public Object readValueObject(Class<?> clz) throws IndirectionException { try { return in.read_value(clz); } catch (IndirectionException ex) { return offsetMap.get(ex.offset); } } public org.omg.CORBA.Object readCorbaObject(Class<?> type) { return in.read_Object(); } public Remote readRemoteObject(Class<?> type) { final org.omg.CORBA.Object objref = in.read_Object(); return (Remote) PortableRemoteObject.narrow(objref, type); } public int read() throws IOException { return readUnsignedByte(); } public int read(byte[] arr) throws IOException { return read(arr, 0, arr.length); } public int read(byte[] arr, int off, int len) throws IOException { readFully(arr, off, len); return len; } public long skip(long len) throws IOException { skipBytes((int) len); return len; } public int available() throws IOException { return in.available(); } @Override protected void _startValue() { ((ValueInputStream)in).start_value(); } @Override protected void _endValue() { ((ValueInputStream)in).end_value(); } }
3,265
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIStubHandler.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Logger; import java.util.logging.Level; import org.omg.CORBA.ORB; /** * This class is the InvocationHandler for instances of POAStub. When a client * calls a remote method, this is translated to a call to the invoke() method in * this class. */ public class RMIStubHandler implements StubHandler, java.io.Serializable { static final Logger logger = Logger.getLogger(RMIStubHandler.class .getName()); protected RMIStubHandler() { } static final RMIStubHandler instance = new RMIStubHandler(); public Object stubWriteReplace(RMIStub stub) { Class type = stub._descriptor.type; return new org.apache.yoko.rmi.impl.RMIPersistentStub(stub, type); } public Object invoke(RMIStub stub, MethodDescriptor method, Object[] args) throws Throwable { // special-case for writeReplace if (method == null) { return stubWriteReplace(stub); } final String method_name = method.getIDLName(); boolean stream_arguments = false; logger.finer("invoking " + method_name); while (true) { boolean is_local = stub._is_local(); if (!is_local || stream_arguments) { org.omg.CORBA.portable.OutputStream out = null; org.omg.CORBA.portable.InputStream in = null; try { out = stub._request(method_name, method.responseExpected()); // write arguments method.writeArguments(out, args); // invoke method in = stub._invoke(out); Object result = method.readResult(in); return result; } catch (org.omg.CORBA.portable.ApplicationException ex) { try { method.readException(ex.getInputStream()); } catch (Throwable exx) { logger.log(Level.FINE, "rmi1::" + method_name + " " + exx.getMessage(), exx); addLocalTrace(method, exx); throw exx; } } catch (org.omg.CORBA.portable.UnknownException ex) { logger.log(Level.FINER, "rmi2::" + method_name + " " + ex.getMessage(), ex); logger.log(Level.FINER, "rmi2::" + method_name + " " + ex.originalEx.getMessage(), ex.originalEx); addLocalTrace(method, ex.originalEx); throw ex.originalEx; } catch (org.omg.CORBA.portable.RemarshalException _exception) { continue; } catch (org.omg.CORBA.SystemException ex) { java.rmi.RemoteException exx = javax.rmi.CORBA.Util .mapSystemException(ex); logger.log(Level.FINER, "rmi3::" + method_name + " " + exx.getMessage(), exx); throw exx; } catch (Throwable ex) { logger.log(Level.FINER, "rmi4::" + method_name + " " + ex.getMessage(), ex); throw ex; } finally { stub._releaseReply(in); } } else { org.omg.CORBA.portable.ServantObject so; so = stub._servant_preinvoke(method_name, RMIServant.class); RMIServant servant; try { servant = (RMIServant) so.servant; } catch (ClassCastException ex) { stream_arguments = true; continue; } catch (NullPointerException ex) { stream_arguments = true; continue; } final RMIState target_state = servant.getRMIState(); final ORB orb = target_state.getORB(); Object return_value = null; boolean same_state; RMIState currentState = RMIState.current(); same_state = (currentState == target_state); Object[] copied_args = method.copyArguments(args, same_state, orb); try { java.lang.reflect.Method m = method .getReflectedMethod(); return_value = servant .invoke_method(m, copied_args); } catch (org.omg.CORBA.SystemException ex) { throw javax.rmi.CORBA.Util.mapSystemException(ex); } finally { stub._servant_postinvoke(so); } return method.copyResult(return_value, same_state, orb); } } } private static Throwable addLocalTrace(MethodDescriptor desc, Throwable ex) { try { throw new Throwable("Client-Side RMI Trace"); } catch (Throwable lex) { StackTraceElement[] remoteTrace = ex.getStackTrace(); StackTraceElement[] localTrace = lex.getStackTrace(); StackTraceElement[] fullTrace = new StackTraceElement[localTrace.length + remoteTrace.length]; for (int i = 0; i < remoteTrace.length; i++) { fullTrace[i] = remoteTrace[i]; } java.lang.reflect.Method m = desc.getReflectedMethod(); resetTraceInfo(m.getDeclaringClass().getName(), m.getName(), localTrace[0]); for (int i = 0; i < localTrace.length; i++) { fullTrace[remoteTrace.length + i] = localTrace[i]; } ex.setStackTrace(fullTrace); return ex; } } static Field classNameField; static Field methodNameField; static Field fileNameField; static Field lineNumberField; static { AccessController.doPrivileged(new PrivilegedAction() { /** * @see java.security.PrivilegedAction#run() */ public Object run() { try { classNameField = StackTraceElement.class .getDeclaredField("declaringClass"); classNameField.setAccessible(true); methodNameField = StackTraceElement.class .getDeclaredField("methodName"); methodNameField.setAccessible(true); fileNameField = StackTraceElement.class .getDeclaredField("fileName"); fileNameField.setAccessible(true); lineNumberField = StackTraceElement.class .getDeclaredField("lineNumber"); lineNumberField.setAccessible(true); } catch (Exception ex) { // ignore } return null; } }); } /** * Method resetTraceInfo. * * @param stackTraceElement */ private static void resetTraceInfo(String className, String methodName, StackTraceElement ste) { try { classNameField.set(ste, className); methodNameField.set(ste, methodName); fileNameField.set(ste, "--- RMI/IIOP INVOCATION ---"); lineNumberField.set(ste, new Integer(-2000)); } catch (IllegalAccessException e) { } catch (NullPointerException e) { } } }
3,266
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ClassDescDescriptor.java
package org.apache.yoko.rmi.impl; import java.io.Serializable; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Level; import java.util.logging.Logger; import javax.rmi.CORBA.ClassDesc; import javax.rmi.CORBA.Util; import org.apache.yoko.util.cmsf.RepIds; import org.omg.CORBA.MARSHAL; class ClassDescDescriptor extends ClassBaseDescriptor { private static final Logger logger = Logger.getLogger(ClassDescDescriptor.class.getName()); ClassDescDescriptor(TypeRepository repository) { super(ClassDesc.class, repository); } /** Read an instance of this value from a CDR stream */ @Override public Serializable readResolve(final Serializable value) { final ClassDesc desc = (ClassDesc) value; Class<?> result = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() { public Class<?> run() { String className = "<unknown>"; try { String repid = (String) getRepidField().get(desc); String codebase = (String) getCobebaseField().get(desc); Class<?> result = RepIds.query(repid).codebase(codebase).toClass(); if (null != result) return result; throw new MARSHAL(String.format("Cannot load class \"%s\"", className)); } catch (IllegalAccessException ex) { throw (MARSHAL)new MARSHAL("no such field: " + ex).initCause(ex); } } }); if (logger.isLoggable(Level.FINE)) logger.fine(String.format("readResolve %s => %s", value, result)); return result; } }
3,267
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ShortDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class ShortDescriptor extends SimpleDescriptor { ShortDescriptor(TypeRepository repository) { super(Short.TYPE, repository, "short", org.omg.CORBA.TCKind.tk_short); } public Object read(org.omg.CORBA.portable.InputStream in) { return new Short(in.read_short()); } public void write(org.omg.CORBA.portable.OutputStream out, Object val) { out.write_short(((Short) val).shortValue()); } }
3,268
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/CharDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class CharDescriptor extends SimpleDescriptor { CharDescriptor(TypeRepository repository) { super(Character.TYPE, repository, "wchar", org.omg.CORBA.TCKind.tk_wchar); } public Object read(org.omg.CORBA.portable.InputStream in) { return new Character(in.read_wchar()); } public void write(org.omg.CORBA.portable.OutputStream out, Object val) { out.write_wchar(((Character) val).charValue()); } }
3,269
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/EnumDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.apache.yoko.util.yasf.Yasf; import java.io.IOException; import java.io.Serializable; class EnumDescriptor extends ValueDescriptor { public EnumDescriptor(Class<?> type, TypeRepository repo) { super(type, repo); } @Override protected final long getSerialVersionUID() { return 0L; } @Override protected final boolean isEnum() { return true; } private FieldDescriptor nameField = null; private FieldDescriptor ordinalField = null; @Override public final void init() { super.init(); // Avoid doing anything that would cause the calculated classHash to change for (FieldDescriptor f: _fields) { if (f.java_name.equals("name")) { nameField = f; } else if (f.java_name.equals("ordinal")) { ordinalField = f; } } } @Override protected void defaultWriteValue(ObjectWriter writer, Serializable val) throws IOException { if ((writer.yasfSet != null) && !!!writer.yasfSet.contains(Yasf.ENUM_FIXED)) { // talking to an old yoko that expects an ordinal field to be written; ordinalField.write(writer, val); } nameField.write(writer, val); } }
3,270
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIInitializer.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.util.logging.Logger; import java.util.logging.Level; import org.omg.CORBA.LocalObject; import org.omg.CORBA.UserException; import org.omg.IOP.Codec; import org.omg.IOP.CodecFactory; import org.omg.IOP.ENCODING_CDR_ENCAPS; import org.omg.IOP.Encoding; import org.omg.PortableInterceptor.ORBInitInfo; import org.omg.PortableInterceptor.ORBInitializer; public class RMIInitializer extends LocalObject implements ORBInitializer { static final Logger logger = Logger.getLogger(RMIInitializer.class .getName()); public void pre_init(ORBInitInfo info) { Encoding encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte)1,(byte) 0); CodecFactory codecFactory = info.codec_factory(); try { Codec codec = codecFactory.create_codec(encoding); RMIInterceptor rmiInterceptor = new RMIInterceptor(codec); info.add_ior_interceptor(rmiInterceptor); } catch (UserException e) { logger.log(Level.FINER, "cannot register RMI Interceptor" + e.getMessage(), e); } } public void post_init(ORBInitInfo info) { } }
3,271
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/CustomMarshaledObjectReader.java
package org.apache.yoko.rmi.impl; import java.io.IOException; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; import org.omg.CORBA.INTERNAL; import org.omg.CORBA.MARSHAL; public final class CustomMarshaledObjectReader extends DelegatingObjectReader { private enum State { UNINITIALISED, BEFORE_CUSTOM_DATA, IN_CUSTOM_DATA, CLOSED; private static final Map<State, Set<State>> TRANSITIONS; static { EnumMap<State, Set<State>> transition = new EnumMap<>(State.class); allow(transition, from(UNINITIALISED), to(BEFORE_CUSTOM_DATA)); allow(transition, from(BEFORE_CUSTOM_DATA), to(IN_CUSTOM_DATA, CLOSED)); allow(transition, from(IN_CUSTOM_DATA), to(CLOSED)); allow(transition, from(CLOSED), to(CLOSED)); TRANSITIONS = Collections.unmodifiableMap(transition); } private static void allow(Map<State, Set<State>> map, State from, Set<State> to) { map.put(from, to); } private static State from(State state) { return state; } private static Set<State> to(State state, State...states) { return Collections.unmodifiableSet(EnumSet.of(state, states)); } void checkStateTransition(State newState) { if (TRANSITIONS.get(this).contains(newState)) return; throw new INTERNAL("Unexpected state transition from " + this + " to " + newState); } } private final ObjectReader objectReader; private State state = State.UNINITIALISED; private State setState(final State newState) throws IOException { state.checkStateTransition(newState); try { return state; } finally { state = newState; switch(newState) { case UNINITIALISED: throw new IllegalStateException(); case BEFORE_CUSTOM_DATA: delegateTo(new DefaultWriteObjectReader(objectReader)); break; case IN_CUSTOM_DATA: delegateTo(objectReader); break; case CLOSED: delegateTo(ClosedObjectReader.INSTANCE); break; } } } private void readCustomRMIValue() throws IOException { setState(State.IN_CUSTOM_DATA); objectReader._startValue(); } public CustomMarshaledObjectReader(ObjectReader delegate) throws IOException { this.objectReader = delegate; setState(State.BEFORE_CUSTOM_DATA); } public void close() throws IOException { switch (setState(State.CLOSED)) { case UNINITIALISED: throw new IllegalStateException(); case BEFORE_CUSTOM_DATA : objectReader.readValueObject(); break; case IN_CUSTOM_DATA : objectReader._endValue(); break; case CLOSED : // nothing to do here break; } } @Override protected final Object readObjectOverride() throws ClassNotFoundException, IOException { return super.readObjectOverride0(); } /** * This class handles reading the defaultWriteObject() data, * and prepares its outer instance when the custom data is * first read. */ private final class DefaultWriteObjectReader extends DelegatingObjectReaderWithBeforeReadHook { private boolean allowDefaultRead = true; public DefaultWriteObjectReader(ObjectReader delegate) throws IOException { super(delegate); } @Override public void defaultReadObject() throws IOException, ClassNotFoundException { if (allowDefaultRead) { allowDefaultRead = false; CustomMarshaledObjectReader.this.objectReader.defaultReadObject(); } else { throw new IllegalStateException("defaultReadObject() or readFields() must not be called more than once"); } } @Override public GetField readFields() throws IOException ,ClassNotFoundException { if (allowDefaultRead) { allowDefaultRead = false; return CustomMarshaledObjectReader.this.objectReader.readFields(); } else { throw new IllegalStateException("readFields() or defaultReadObject() must not be called more than once"); } }; @Override void beforeRead() { try { CustomMarshaledObjectReader.this.readCustomRMIValue(); } catch (IOException e) { throw (MARSHAL)new MARSHAL(e.toString()).initCause(e); } } } }
3,272
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/StubImpl.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; public class StubImpl implements javax.rmi.CORBA.StubDelegate { public StubImpl() { } public int hashCode(javax.rmi.CORBA.Stub stub) { return stub._get_delegate().hashCode(stub); } public boolean equals(javax.rmi.CORBA.Stub stub, java.lang.Object obj) { if (obj instanceof org.omg.CORBA.Object) { return stub._is_equivalent((org.omg.CORBA.Object) obj); } else { return false; } } public java.lang.String toString(javax.rmi.CORBA.Stub stub) { return stub._get_delegate().toString(stub); } public void connect(javax.rmi.CORBA.Stub stub, org.omg.CORBA.ORB orb) throws java.rmi.RemoteException { try { org.omg.CORBA.portable.Delegate delegate; try { delegate = stub._get_delegate(); } catch (org.omg.CORBA.BAD_OPERATION ex) { throw new java.rmi.RemoteException("stub has no identity", ex); } if (delegate.orb(stub) != orb) { org.omg.CORBA.portable.OutputStream out = orb .create_output_stream(); out.write_Object(stub); org.omg.CORBA.portable.InputStream in = out .create_input_stream(); org.omg.CORBA.portable.ObjectImpl impl = (org.omg.CORBA.portable.ObjectImpl) in .read_Object(); stub._set_delegate(impl._get_delegate()); } } catch (org.omg.CORBA.SystemException ex) { throw javax.rmi.CORBA.Util.mapSystemException(ex); } } public void readObject(javax.rmi.CORBA.Stub stub, java.io.ObjectInputStream ois) throws java.io.IOException, java.lang.ClassNotFoundException { org.omg.CORBA.portable.InputStream in = null; if (ois instanceof CorbaObjectReader) { in = ((CorbaObjectReader) ois).in; } else { IOR ior = new IOR(); ior.read(ois); org.omg.CORBA.portable.OutputStream out = RMIState.current() .getORB().create_output_stream(); ior.write(out); in = out.create_input_stream(); } org.omg.CORBA.portable.ObjectImpl impl = (org.omg.CORBA.portable.ObjectImpl) in .read_Object(); stub._set_delegate(impl._get_delegate()); } public void writeObject(javax.rmi.CORBA.Stub stub, java.io.ObjectOutputStream oos) throws java.io.IOException { if (oos instanceof CorbaObjectWriter) { ((CorbaObjectWriter) oos).out.write_Object(stub); } else { org.omg.CORBA.portable.OutputStream out = RMIState.current() .getORB().create_output_stream(); out.write_Object(stub); org.omg.CORBA.portable.InputStream in = out.create_input_stream(); IOR ior = new IOR(); ior.read(in); ior.write(oos); } } }
3,273
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ExceptionDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; class ExceptionDescriptor extends ValueDescriptor { ExceptionDescriptor(Class type, TypeRepository repository) { super(type, repository); } private volatile String ex_repid = null; private String genExceptionRepId() { String name = type.getName(); final String encname; if (name.endsWith("Exception")) { encname = name.substring(0, name.length() - 7); } else { encname = name + "Ex"; } return String.format("IDL:%s:1.0", encname.replace('.', '/')); } final String getExceptionRepositoryID() { if (ex_repid == null) ex_repid = genExceptionRepId(); return ex_repid; } }
3,274
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/FVDEnumDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.omg.CORBA.TypeCode; import org.omg.CORBA.ValueDefPackage.FullValueDescription; class FVDEnumDescriptor extends EnumDescriptor { private final FullValueDescription fvd; private final String repid; FVDEnumDescriptor(FullValueDescription fvd, Class clazz, TypeRepository rep, String repid, ValueDescriptor super_desc) { super(clazz, rep); this.fvd = fvd; this.repid = repid; init(); _super_descriptor = super_desc; } @Override protected String genRepId() { return repid; } @Override FullValueDescription getFullValueDescription() { return fvd; } @Override protected TypeCode genTypeCode() { return fvd.type; } @Override public boolean isCustomMarshalled() { return fvd.is_custom; } }
3,275
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIInterceptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.util.logging.Logger; import java.util.logging.Level; import org.omg.CORBA.Any; import org.omg.CORBA.LocalObject; import org.omg.CORBA.ORB; import org.omg.IOP.Codec; import org.omg.IOP.TAG_JAVA_CODEBASE; import org.omg.IOP.TaggedComponent; import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; import org.omg.PortableInterceptor.IORInfo; import org.omg.PortableInterceptor.IORInterceptor; public class RMIInterceptor extends LocalObject implements IORInterceptor { static final Logger logger = Logger.getLogger(RMIInterceptor.class .getName()); public RMIInterceptor(Codec codec) { this.codec = codec; } private Codec codec; static ThreadLocal currentCodeBase = new ThreadLocal(); static void setCurrent(String codeBase) { currentCodeBase.set(codeBase); } /** * @see org.omg.PortableInterceptor.IORInterceptorOperations#establish_components(IORInfo) */ public void establish_components(IORInfo info) { String codeBase = (String) currentCodeBase.get(); if (codeBase != null) { logger.finer("registering " + codeBase + " for ORB"); // // Create encapsulation // Any any = ORB.init().create_any(); any.insert_string(codeBase); try { byte[] data = codec.encode(any); TaggedComponent component = new TaggedComponent( TAG_JAVA_CODEBASE.value, data); info.add_ior_component(component); } catch (InvalidTypeForEncoding e) { logger.log(Level.WARNING, "Failed to add java codebase to IOR" + e.getMessage(), e); } } } /** * @see org.omg.PortableInterceptor.InterceptorOperations#name() */ public String name() { return "RMI IOR Interceptor"; } /** * @see org.omg.PortableInterceptor.InterceptorOperations#destroy() */ public void destroy() { } }
3,276
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/AnyDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.PrintWriter; import org.omg.CORBA.ORB; import org.omg.CORBA.TCKind; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; class AnyDescriptor extends TypeDescriptor { AnyDescriptor(Class type, TypeRepository rep) { super(type, rep); } @Override protected String genRepId() { return String.format("IDL:%s:1.0", type.getName().replace('.', '/')); } /** Read an instance of this value from a CDR stream */ @Override public Object read(InputStream in) { return javax.rmi.CORBA.Util.readAny(in); } /** Write an instance of this value to a CDR stream */ @Override public void write(OutputStream out, Object val) { javax.rmi.CORBA.Util.writeAny(out, val); } @Override protected TypeCode genTypeCode() { ORB orb = ORB.init(); return orb.get_primitive_tc(TCKind.tk_any); } @Override Object copyObject(Object value, CopyState state) { throw new InternalError("cannot copy org.omg.CORBA.Any"); } @Override void writeMarshalValue(PrintWriter pw, String outName, String paramName) { pw.print("javax.rmi.CORBA.Util.writeAny("); pw.print(outName); pw.print(','); pw.print(paramName); pw.print(')'); } @Override void writeUnmarshalValue(PrintWriter pw, String inName) { pw.print("javax.rmi.CORBA.Util.readAny("); pw.print(inName); pw.print(")"); } }
3,277
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ClassBaseDescriptor.java
package org.apache.yoko.rmi.impl; import org.omg.CORBA.MARSHAL; import javax.rmi.CORBA.ClassDesc; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; abstract class ClassBaseDescriptor extends ValueDescriptor { ClassBaseDescriptor(Class type, TypeRepository repository) { super(type, repository); } private volatile Field repidField = null; private Field genRepIdField() { return findField("repid"); } final Field getRepidField() { if (null == repidField) repidField = genRepIdField(); return repidField; } private volatile Field cobebaseField = null; private Field genCodebaseField() { return findField("codebase"); } final Field getCobebaseField() { if (null == cobebaseField) cobebaseField = genCodebaseField(); return cobebaseField; } private Field findField(final String fieldName) { return AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { Field f = ClassDesc.class.getDeclaredField(fieldName); f.setAccessible(true); return f; } catch (NoSuchFieldException e) { throw (MARSHAL)new MARSHAL("no such field: " + e).initCause(e); } } }); } }
3,278
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/IOR.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; /** * Utility for writing IORs to DataOutput */ class IOR { String type_id; TaggedProfile[] profiles; static class TaggedProfile { int tag; byte[] profile_data; void read(org.omg.CORBA.portable.InputStream in) { tag = in.read_ulong(); int len = in.read_ulong(); profile_data = new byte[len]; in.read_octet_array(profile_data, 0, len); } void write(org.omg.CORBA.portable.OutputStream out) { out.write_ulong(tag); out.write_ulong(profile_data.length); out.write_octet_array(profile_data, 0, profile_data.length); } void read(java.io.DataInput in) throws java.io.IOException { tag = in.readInt(); int len = in.readInt(); profile_data = new byte[len]; in.readFully(profile_data, 0, len); } void write(java.io.DataOutput out) throws java.io.IOException { out.writeInt(tag); out.writeInt(profile_data.length); out.write(profile_data, 0, profile_data.length); } } void read(org.omg.CORBA.portable.InputStream in) { type_id = in.read_string(); int len = in.read_ulong(); profiles = new TaggedProfile[len]; for (int i = 0; i < len; i++) { profiles[i] = new TaggedProfile(); profiles[i].read(in); } } void write(org.omg.CORBA.portable.OutputStream out) { out.write_string(type_id); out.write_ulong(profiles.length); for (int i = 0; i < profiles.length; i++) { profiles[i].write(out); } } void read(java.io.DataInput in) { try { // read type id int strlen = in.readInt(); byte[] data = new byte[strlen]; in.readFully(data, 0, strlen); type_id = new String(data, 0, strlen - 1, "ISO-8859-1"); // read profiles int len = in.readInt(); profiles = new TaggedProfile[len]; for (int i = 0; i < len; i++) { profiles[i] = new TaggedProfile(); profiles[i].read(in); } } catch (java.io.IOException ex) { throw new Error("failed to marshal IOR", ex); } } void write(java.io.DataOutput out) { try { // write type id byte[] string = type_id.getBytes("ISO-8859-1"); out.writeInt(string.length + 1); out.write(string, 0, string.length); out.write(0); // write profile info out.writeInt(profiles.length); for (int i = 0; i < profiles.length; i++) { profiles[i].write(out); } } catch (java.io.IOException ex) { throw new Error("failed to marshal IOR", ex); } } }
3,279
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/IntegerDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class IntegerDescriptor extends SimpleDescriptor { IntegerDescriptor(TypeRepository repository) { super(Integer.TYPE, repository, "long", org.omg.CORBA.TCKind.tk_long); } public Object read(org.omg.CORBA.portable.InputStream in) { return new Integer(in.read_long()); } public void write(org.omg.CORBA.portable.OutputStream out, Object val) { out.write_long(((Integer) val).intValue()); } }
3,280
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/DoubleDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class DoubleDescriptor extends SimpleDescriptor { DoubleDescriptor(TypeRepository repository) { super(Double.TYPE, repository, "double", org.omg.CORBA.TCKind.tk_double); } public Object read(org.omg.CORBA.portable.InputStream in) { return new Double(in.read_double()); } public void write(org.omg.CORBA.portable.OutputStream out, Object val) { out.write_double(((Double) val).doubleValue()); } }
3,281
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIState.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.logging.Logger; import java.util.logging.Level; import javax.rmi.CORBA.Stub; import javax.rmi.CORBA.ValueHandler; import org.apache.yoko.rmi.api.PortableRemoteObjectExt; import org.apache.yoko.rmi.api.PortableRemoteObjectState; import org.apache.yoko.rmi.util.NodeleteSynchronizedMap; import org.omg.CORBA.BAD_INV_ORDER; import org.omg.CORBA.Policy; import org.omg.CORBA.ORBPackage.InvalidName; import org.omg.PortableServer.POA; import org.omg.PortableServer.POAManagerPackage.AdapterInactive; import org.omg.PortableServer.POAPackage.AdapterAlreadyExists; import org.omg.PortableServer.POAPackage.InvalidPolicy; public class RMIState implements PortableRemoteObjectState { static final Logger logger = Logger.getLogger(RMIState.class.getName()); private boolean isShutdown; final private org.omg.CORBA.ORB _orb; private String _name; final TypeRepository repo = TypeRepository.get(); private POA poa; POA getPOA() { return poa; } RMIState(org.omg.CORBA.ORB orb, String name) { if (orb == null) { throw new NullPointerException("ORB is null"); } try { POA rootPoa = (POA) orb.resolve_initial_references("RootPOA"); poa = rootPoa.create_POA(name, null, new Policy[0]); poa.the_POAManager().activate(); } catch (AdapterAlreadyExists e) { logger.log(Level.WARNING, "Adapter already exists", e); } catch (InvalidPolicy e) { logger.log(Level.WARNING, "Invalid policy", e); } catch (InvalidName e) { logger.log(Level.WARNING, "Invalid name", e); } catch (AdapterInactive e) { logger.log(Level.WARNING, "Adapter inactive", e); } _orb = orb; _name = name; } void checkShutDown() { if (isShutdown) { BAD_INV_ORDER ex = new BAD_INV_ORDER( "RMIState has already been shut down"); logger.fine("RMIState has already been shut down " + ex); throw ex; } } public void shutdown() { logger.finer("RMIState shutdown requested; name = " + _name); checkShutDown(); isShutdown = true; } public org.omg.CORBA.ORB getORB() { return _orb; } org.omg.CORBA.portable.Delegate createDelegate(RMIServant servant) { checkShutDown(); byte[] id = servant._id; RemoteDescriptor desc = servant._descriptor; String repid = desc.getRepositoryID(); org.omg.CORBA.portable.ObjectImpl ref; org.omg.PortableServer.POA poa; try { poa = getPOA(); ref = (org.omg.CORBA.portable.ObjectImpl) poa .create_reference_with_id(id, repid); } catch (org.omg.CORBA.BAD_PARAM ex) { throw (InternalError)new InternalError("wrong policy: " + ex.getMessage()).initCause(ex); } return ref._get_delegate(); } static RMIState current() { return (RMIState) PortableRemoteObjectExt.getState(); } public ClassLoader getClassLoader() { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return loader; } // // data for use in PortableRemoteObjectImpl // java.util.Map stub_map = new NodeleteSynchronizedMap() { public java.util.Map initialValue() { return new HashMap(); } }; // // data for use in UtilImpl // java.util.Map tie_map = java.util.Collections .synchronizedMap(new IdentityHashMap()); private java.util.Map static_stub_map = new NodeleteSynchronizedMap() { public java.util.Map initialValue() { return new HashMap(); } }; private URL _codebase; // // // public void setCodeBase(URL codebase) { _codebase = codebase; } public URL getCodeBase() { return _codebase; } void clearState() { stub_map = null; tie_map = null; static_stub_map = null; } static class StaticStubEntry { java.lang.reflect.Constructor stub_constructor; } /** * Method getStaticStub. * * @param codebase * @param type * @return Stub */ public Stub getStaticStub1(String codebase, Class type) { return null; } public Stub getStaticStub(String codebase, Class type) { StaticStubEntry ent = (StaticStubEntry) static_stub_map.get(type); if (ent == null) { ent = new StaticStubEntry(); java.lang.reflect.Constructor cons = findConstructor(codebase, getNewStubClassName(type)); if (cons != null && !javax.rmi.CORBA.Stub.class.isAssignableFrom(cons .getDeclaringClass())) { logger.fine("class " + cons.getDeclaringClass() + " is not a javax.rmi.CORBA.Stub"); cons = null; } if (cons == null) { cons = findConstructor(codebase, getOldStubClassName(type)); } if (cons != null && !javax.rmi.CORBA.Stub.class.isAssignableFrom(cons .getDeclaringClass())) { logger.fine("class " + cons.getDeclaringClass() + " is not a javax.rmi.CORBA.Stub"); cons = null; } ent.stub_constructor = cons; static_stub_map.put(type, ent); } if (ent.stub_constructor == null) { return null; } try { return (Stub) ent.stub_constructor .newInstance(PortableRemoteObjectImpl.NO_ARG); } catch (ClassCastException ex) { logger.log(Level.FINE, "loaded class " + ent.stub_constructor.getDeclaringClass() + " is not a proper stub", ex); } catch (IllegalAccessException ex) { logger.log(Level.FINE, "cannot instantiate stub class for " + type + " :: " + ex.getMessage(), ex); } catch (InstantiationException ex) { logger.log(Level.FINE, "cannot instantiate stub class for " + type + " :: " + ex.getMessage(), ex); } catch (InvocationTargetException ex) { logger.log(Level.FINE, "cannot instantiate stub class for " + type + " :: " + ex.getCause(), ex.getCause()); } return null; } private java.lang.reflect.Constructor findConstructor(String codebase, String stubName) { try { Class stubClass = javax.rmi.CORBA.Util.loadClass(stubName, codebase, getClassLoader()); return stubClass.getConstructor(new Class[0]); } catch (NoSuchMethodException ex) { logger.log(Level.WARNING, "stub class " + stubName + " has no default constructor", ex); } catch (ClassNotFoundException ex) { logger.log(Level.FINE, "failed to load remote class " + stubName + " from " + codebase, ex); // ignore // } return null; } String getNewStubClassName(Class c) { String cname = c.getName(); String pkgname = null; int idx = cname.lastIndexOf('.'); if (idx == -1) { pkgname = "org.omg.stub"; } else { pkgname = "org.omg.stub." + cname.substring(0, idx); } String cplain = cname.substring(idx + 1); return pkgname + "." + "_" + cplain + "_Stub"; } String getOldStubClassName(Class c) { String cname = c.getName(); //String pkgname = null; int idx = cname.lastIndexOf('.'); if (idx == -1) { return "_" + cname + "_Stub"; } else { return cname.substring(0, idx + 1) + "_" + cname.substring(idx + 1) + "_Stub"; } } public void exportObject(Remote remote) throws RemoteException { //PortableRemoteObjectExt.pushState(this); try { javax.rmi.PortableRemoteObject.exportObject(remote); } finally { //PortableRemoteObjectExt.popState(); } } public void unexportObject(Remote remote) throws RemoteException { //PortableRemoteObjectExt.pushState(this); try { javax.rmi.PortableRemoteObject.unexportObject(remote); } finally { //PortableRemoteObjectExt.popState(); } } public String getName() { return _name; } }
3,282
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/DelegatingObjectReader.java
package org.apache.yoko.rmi.impl; import java.io.Externalizable; import java.io.IOException; import java.io.InvalidObjectException; import java.io.NotActiveException; import java.io.ObjectInputValidation; import java.rmi.Remote; import org.omg.CORBA.portable.IndirectionException; abstract class DelegatingObjectReader extends ObjectReader { private ObjectReader delegate; public DelegatingObjectReader() throws IOException {} void delegateTo(ObjectReader delegate) { this.delegate = delegate; } ////////////////////////////////////// // ONLY DELEGATE METHODS BELOW HERE // ////////////////////////////////////// final Object readObjectOverride0() throws ClassNotFoundException, IOException { return delegate.readObjectOverride(); } public int read(byte[] b) throws IOException { return delegate.read(b); } public long skip(long n) throws IOException { return delegate.skip(n); } public void mark(int readlimit) { delegate.mark(readlimit); } public void reset() throws IOException { delegate.reset(); } public boolean markSupported() { return delegate.markSupported(); } public Object readUnshared() throws IOException, ClassNotFoundException { return delegate.readUnshared(); } public void defaultReadObject() throws IOException, ClassNotFoundException { delegate.defaultReadObject(); } public GetField readFields() throws IOException, ClassNotFoundException { return delegate.readFields(); } public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException { delegate.registerValidation(obj, prio); } public int read() throws IOException { return delegate.read(); } public int read(byte[] buf, int off, int len) throws IOException { return delegate.read(buf, off, len); } public int available() throws IOException { return delegate.available(); } public void close() throws IOException { delegate.close(); } public boolean readBoolean() throws IOException { return delegate.readBoolean(); } public byte readByte() throws IOException { return delegate.readByte(); } public int readUnsignedByte() throws IOException { return delegate.readUnsignedByte(); } public char readChar() throws IOException { return delegate.readChar(); } public short readShort() throws IOException { return delegate.readShort(); } public int readUnsignedShort() throws IOException { return delegate.readUnsignedShort(); } public int readInt() throws IOException { return delegate.readInt(); } public long readLong() throws IOException { return delegate.readLong(); } public float readFloat() throws IOException { return delegate.readFloat(); } public double readDouble() throws IOException { return delegate.readDouble(); } public void readFully(byte[] buf) throws IOException { delegate.readFully(buf); } public void readFully(byte[] buf, int off, int len) throws IOException { delegate.readFully(buf, off, len); } public int skipBytes(int len) throws IOException { return delegate.skipBytes(len); } @Deprecated public String readLine() throws IOException { return delegate.readLine(); } public String readUTF() throws IOException { return delegate.readUTF(); } /////////////////////////////////////// // delegate methods for ObjectReader // /////////////////////////////////////// void _startValue() { delegate._startValue(); } void _endValue() { delegate._endValue(); } void setCurrentValueDescriptor(ValueDescriptor desc) { delegate.setCurrentValueDescriptor(desc); } Object readAbstractObject() throws IndirectionException { return delegate.readAbstractObject(); } Object readAny() throws IndirectionException { return delegate.readAny(); } Object readValueObject() throws IndirectionException { return delegate.readValueObject(); } Object readValueObject(Class<?> clz) throws IndirectionException { return delegate.readValueObject(clz); } org.omg.CORBA.Object readCorbaObject(Class<?> type) { return delegate.readCorbaObject(type); } Remote readRemoteObject(Class<?> type) { return delegate.readRemoteObject(type); } void readExternal(Externalizable ext) throws IOException, ClassNotFoundException { delegate.readExternal(ext); } }
3,283
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/AbstractObjectDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.omg.CORBA.ORB; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; import java.io.PrintWriter; class AbstractObjectDescriptor extends ValueDescriptor { protected AbstractObjectDescriptor(Class type, TypeRepository repository) { super(type, repository); } @Override protected String genRepId() { return String.format("IDL:%s:1.0", type.getName().replace('.', '/')); } /** Read an instance of this value from a CDR stream */ @Override public Object read(InputStream in) { org.omg.CORBA_2_3.portable.InputStream _in = (org.omg.CORBA_2_3.portable.InputStream) in; return _in.read_abstract_interface(); } /** Write an instance of this value to a CDR stream */ @Override public void write(OutputStream out, Object value) { org.omg.CORBA_2_3.portable.OutputStream _out = (org.omg.CORBA_2_3.portable.OutputStream) out; _out.write_abstract_interface(value); } @Override protected TypeCode genTypeCode() { ORB orb = ORB.init(); return orb.create_abstract_interface_tc(getRepositoryID(), type.getName()); } @Override public long computeHashCode() { return 0L; } @Override Object copyObject(Object value, CopyState state) { throw new IllegalStateException("not serializable " + value.getClass().getName()); } @Override void writeMarshalValue(PrintWriter pw, String outName, String paramName) { pw.print("javax.rmi.CORBA.Util.writeAbstractObject("); pw.print(outName); pw.print(','); pw.print(paramName); pw.print(')'); } @Override void writeUnmarshalValue(PrintWriter pw, String inName) { pw.print(inName); pw.print(".read_abstract_interface()"); } }
3,284
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIPersistentStub.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.util.logging.Logger; import java.util.logging.Level; /** * RMIStub's (org.apache.yoko.rmi.impl) implement writeReplace by returning an * instance of this class; and this class then implements readResolve to narrow * itself to the correct type. This way, object references to RMI exported * objects are transferred without loss of the runtime type. * * @author Kresten Krab Thorup (krab@eos.dk) */ public class RMIPersistentStub extends javax.rmi.CORBA.Stub { static final Logger logger = Logger.getLogger(RMIPersistentStub.class .getName()); /** the class-type to which this object should be narrow'ed */ private Class type; /** constructor for use by serialization */ RMIPersistentStub() { // System.out.println ("Creating instance of RMIPersistentStub"); } /** constructor used in org.apache.yoko.rmi.impl.RMIStubHandler */ public RMIPersistentStub(javax.rmi.CORBA.Stub stub, Class type) { _set_delegate(stub._get_delegate()); this.type = type; } /** narrows this object (once deserialized) to the relevant type */ public Object readResolve() throws java.lang.ClassNotFoundException { // System.out.println ("RMIPersistentStub::readResolve"); Object result = null; try { result = javax.rmi.PortableRemoteObject.narrow(this, type); } catch (RuntimeException ex) { logger.log(Level.WARNING, "Error narrowing object", ex); throw ex; } // System.out.println ("result is of type "+result.getClass()); return result; } /** standard method */ public String[] _ids() { return new String[] { javax.rmi.CORBA.Util.createValueHandler() .getRMIRepositoryID(type) }; } }
3,285
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/UtilImpl.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.Externalizable; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.rmi.AccessException; import java.rmi.MarshalException; import java.rmi.NoSuchObjectException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.ServerError; import java.rmi.ServerException; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.logging.Level; import java.util.logging.Logger; import javax.rmi.PortableRemoteObject; import javax.rmi.CORBA.Stub; import javax.rmi.CORBA.Tie; import javax.rmi.CORBA.Util; import javax.rmi.CORBA.UtilDelegate; import javax.rmi.CORBA.ValueHandler; import org.apache.yoko.rmi.util.GetSystemPropertyAction; import org.apache.yoko.osgi.ProviderLocator; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.COMM_FAILURE; import org.omg.CORBA.INVALID_TRANSACTION; import org.omg.CORBA.INV_OBJREF; import org.omg.CORBA.MARSHAL; import org.omg.CORBA.NO_IMPLEMENT; import org.omg.CORBA.NO_PERMISSION; import org.omg.CORBA.OBJECT_NOT_EXIST; import org.omg.CORBA.SystemException; import org.omg.CORBA.TCKind; import org.omg.CORBA.TRANSACTION_REQUIRED; import org.omg.CORBA.TRANSACTION_ROLLEDBACK; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.IDLEntity; import org.omg.CORBA.portable.UnknownException; public class UtilImpl implements UtilDelegate { private static final Logger logger = Logger.getLogger(UtilImpl.class.getName()); // Note: this field must be declared before the static intializer that calls Util.loadClass // since that method will call loadClass0 which uses this field... if it is below the static // initializer the _secman field will be null private static final SecMan _secman = getSecMan(); private static final ClassLoader BEST_GUESS_AT_EXTENSION_CLASS_LOADER; static { ClassLoader candidateLoader = getClassLoader(UtilImpl.class); if (candidateLoader == null) { // looks like this class was loaded by the boot class loader // so it is safe to try loading stuff by reflection without // worrying about whether we have imported the packages into the OSGi bundle candidateLoader = findFirstNonNullLoader( "sun.net.spi.nameservice.dns.DNSNameService", "javax.transaction.UserTransaction"); } // We will try to find the extension class // loader by ascending the loader hierarchy // starting from whatever loader we found. for (ClassLoader l = candidateLoader; l != null; l = l.getParent()) { candidateLoader = l; } BEST_GUESS_AT_EXTENSION_CLASS_LOADER = candidateLoader; } private static ClassLoader findFirstNonNullLoader(String...classNames) { for (String className : classNames) { try { final Class<?> c = Class.forName(className); ClassLoader cl = getClassLoader(c); if (cl != null) return cl; } catch (Exception|NoClassDefFoundError swallowed) { } } return null; } /** * Translate a CORBA SystemException to the corresponding RemoteException */ public RemoteException mapSystemException(final SystemException theException) { SystemException ex = theException; if (ex instanceof UnknownException) { Throwable orig = ((UnknownException) ex).originalEx; if (orig instanceof Error) { return new ServerError("Error occurred in server thread", (Error) orig); } else if (orig instanceof RemoteException) { return new ServerException( "RemoteException occurred in server thread", (Exception) orig); } else if (orig instanceof RuntimeException) { throw (RuntimeException) orig; } } Class<? extends SystemException> exclass = ex.getClass(); String name = exclass.getName(); // construct the exception message according to �1.4.8 StringBuffer buf = new StringBuffer("CORBA "); final String prefix = "org.omg.CORBA"; if (name.startsWith(prefix)) { buf.append(name.substring(prefix.length() + 1)); } else { buf.append(name); } buf.append(" "); buf.append(ex.minor); switch (ex.completed.value()) { case org.omg.CORBA.CompletionStatus._COMPLETED_YES: buf.append(" Yes"); break; case org.omg.CORBA.CompletionStatus._COMPLETED_NO: buf.append(" No"); break; case org.omg.CORBA.CompletionStatus._COMPLETED_MAYBE: buf.append(" Maybe"); break; } String exceptionMessage = buf.toString(); return createRemoteException(ex, exceptionMessage); } private RemoteException createRemoteException(SystemException sysEx, String s) { RemoteException result; try { throw sysEx; } catch (BAD_PARAM|COMM_FAILURE|MARSHAL e) { result = new MarshalException(s); } catch (INV_OBJREF|NO_IMPLEMENT|OBJECT_NOT_EXIST e) { result = new NoSuchObjectException(s); } catch(NO_PERMISSION e) { result = new AccessException(s); } catch (TRANSACTION_REQUIRED e) { result = createRemoteException("javax.transaction.TransactionRequiredException", s); } catch (TRANSACTION_ROLLEDBACK e) { result = createRemoteException("javax.transaction.TransactionRolledbackException", s); } catch (INVALID_TRANSACTION e) { result = createRemoteException("javax.transaction.InvalidTransactionException", s); } catch (SystemException catchAll) { result = new RemoteException(s); } result.detail = sysEx; return result; } private static RemoteException createRemoteException(String className, String s) { RemoteException result; try { @SuppressWarnings("unchecked") Class<? extends RemoteException> clazz = Util.loadClass(className, null, null); Constructor<? extends RemoteException> ctor = clazz.getConstructor(String.class); result = ctor.newInstance(s); } catch (Throwable t) { result = new RemoteException(s); result.addSuppressed(t); } return result; } static SystemException mapRemoteException(RemoteException rex) { if (rex.detail instanceof org.omg.CORBA.SystemException) return (org.omg.CORBA.SystemException) rex.detail; if (rex.detail instanceof RemoteException) rex = (RemoteException) rex.detail; SystemException sysEx; if (rex instanceof java.rmi.NoSuchObjectException) { sysEx = new org.omg.CORBA.INV_OBJREF(rex.getMessage()); } else if (rex instanceof java.rmi.AccessException) { sysEx = new org.omg.CORBA.NO_PERMISSION(rex.getMessage()); } else if (rex instanceof java.rmi.MarshalException) { sysEx = new org.omg.CORBA.MARSHAL(rex.getMessage()); } else { sysEx = createSystemException(rex); } sysEx.initCause(rex); throw sysEx; } private static SystemException createSystemException(RemoteException rex) { return createSystemException(rex, rex.getClass()); } /** * utility method to check for JTA exception types without linking to the JTA classes directly */ private static SystemException createSystemException(RemoteException rex, Class<?> fromClass) { // Recurse up the parent chain, // until we reach a known JTA type. switch(fromClass.getName()) { // Of course, we place some known elephants in Cairo. case "java.lang.Object": case "java.lang.Throwable": case "java.lang.Exception": case "java.lang.RuntimeException": case "java.lang.Error": case "java.io.IOException": case "java.rmi.RemoteException": return new UnknownException(rex); case "javax.transaction.InvalidTransactionException": return new INVALID_TRANSACTION(rex.getMessage()); case "javax.transaction.TransactionRolledbackException": return new TRANSACTION_ROLLEDBACK(rex.getMessage()); case "javax.transaction.TransactionRequiredException": return new TRANSACTION_REQUIRED(rex.getMessage()); } return createSystemException(rex, fromClass.getSuperclass()); } /** * Write an org.omg.CORBA.Any containing the given object. * <p/> * The object is not converted or translated, simply written. Thus, it must * be either an IDL-generated entity, a Serializable value or an * org.omg.CORBA.Object. Specifically, a Remote objects and Servants cannot * be written, but their corresponding Stubs can. * * @param out The stream to which the value should be written * @param obj The object/value to write * @throws org.omg.CORBA.MARSHAL if the value cannot be written */ public void writeAny(org.omg.CORBA.portable.OutputStream out, Object obj) throws org.omg.CORBA.SystemException { // // In this implementation of RMI/IIOP we do not use type codes // beyond the implementation of this method, and it's // counterpart readAny. // org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(); Any any = orb.create_any(); if (obj == null) { // JDK 1.3.1-1 doesn't like NULL typecodes, so // we write it as a null Value. any.insert_Value(null); } else if (obj instanceof String) { any.insert_Value((String) obj); } else if (obj instanceof org.omg.CORBA.Object) { any.insert_Object((org.omg.CORBA.Object) obj); } else if (obj instanceof Any) { any.insert_any((Any) obj); } else if (obj instanceof IDLEntity) { any.insert_Value((Serializable) obj); } else if (obj instanceof java.rmi.Remote) { Remote ro = (Remote) obj; org.omg.CORBA.Object corba_obj; try { corba_obj = (org.omg.CORBA.Object) PortableRemoteObject .toStub(ro); } catch (java.rmi.NoSuchObjectException ex) { throw (org.omg.CORBA.MARSHAL) new org.omg.CORBA.MARSHAL( "object not exported " + ro).initCause(ex); } any.insert_Object((org.omg.CORBA.Object) corba_obj); } else if (obj instanceof Serializable || obj instanceof Externalizable) { any.insert_Value((Serializable) obj); } else { throw new MARSHAL("cannot write as " + obj.getClass() + " to an Any"); } out.write_any(any); } public Object readAny(org.omg.CORBA.portable.InputStream in) throws org.omg.CORBA.SystemException { Any any = in.read_any(); TypeCode typecode = any.type(); switch (typecode.kind().value()) { case TCKind._tk_null: case TCKind._tk_void: return null; case TCKind._tk_value: case TCKind._tk_value_box: return any.extract_Value(); case TCKind._tk_abstract_interface: org.omg.CORBA_2_3.portable.InputStream in23 = (org.omg.CORBA_2_3.portable.InputStream) any .create_input_stream(); return in23.read_abstract_interface(); case TCKind._tk_string: return any.extract_string(); case TCKind._tk_objref: org.omg.CORBA.Object ref = any.extract_Object(); return ref; case TCKind._tk_any: return any.extract_any(); default: String id = "<unknown>"; try { id = typecode.id(); } catch (org.omg.CORBA.TypeCodePackage.BadKind ex) { } throw new MARSHAL("cannot extract " + id + " (" + typecode.kind().value() + ") value from Any"); } } /** * Write a remote object. It must already be exported. * <p/> * This method accepts values of org.omg.CORBA.Object (including stubs), and * instances of java.rmi.Remote for objects that have already been exported. */ public void writeRemoteObject(org.omg.CORBA.portable.OutputStream out, Object obj) throws org.omg.CORBA.SystemException { org.omg.CORBA.Object objref = null; if (obj == null) { out.write_Object(null); return; } else if (obj instanceof org.omg.CORBA.Object) { objref = (org.omg.CORBA.Object) obj; } else if (obj instanceof Remote) { try { objref = (javax.rmi.CORBA.Stub) PortableRemoteObject .toStub((java.rmi.Remote) obj); } catch (java.rmi.NoSuchObjectException ex) { } if (objref == null) { try { PortableRemoteObject.exportObject((java.rmi.Remote) obj); objref = (javax.rmi.CORBA.Stub) PortableRemoteObject .toStub((java.rmi.Remote) obj); } catch (java.rmi.RemoteException ex) { throw (MARSHAL) new MARSHAL("cannot convert Remote to Object").initCause(ex); } } } else { throw new MARSHAL( "object is neither Remote nor org.omg.CORBA.Object: " + obj.getClass().getName()); } out.write_Object(objref); } public void writeAbstractObject(org.omg.CORBA.portable.OutputStream out, Object obj) { logger.finer("writeAbstractObject.1 " + " out=" + out); if (obj instanceof org.omg.CORBA.Object || obj instanceof Serializable) { // skip // } else if (obj instanceof Remote) { org.omg.CORBA.Object objref = null; try { objref = (org.omg.CORBA.Object) PortableRemoteObject .toStub((Remote) obj); } catch (java.rmi.NoSuchObjectException ex) { } if (objref == null) { try { PortableRemoteObject.exportObject((Remote) obj); objref = (org.omg.CORBA.Object) PortableRemoteObject .toStub((Remote) obj); } catch (RemoteException ex) { throw (MARSHAL) new MARSHAL("unable to export object").initCause(ex); } } obj = objref; } org.omg.CORBA_2_3.portable.OutputStream out_ = (org.omg.CORBA_2_3.portable.OutputStream) out; logger.finer("writeAbstractObject.2 " + " out=" + out); out_.write_abstract_interface(obj); } @SuppressWarnings("unchecked") protected java.util.Map<Remote, Tie> tie_map() { return RMIState.current().tie_map; } public void registerTarget(Tie tie, Remote obj) { if (obj == null) throw new IllegalArgumentException("remote object is null"); tie.setTarget(obj); tie_map().put(obj, tie); // log.info("exported instance of "+obj.getClass()+" in // "+RMIState.current().getName()); } public Tie getTie(Remote obj) { if (obj == null) return null; return tie_map().get(obj); } public ValueHandler createValueHandler() { return ValueHandlerImpl.get(); } public String getCodebase(@SuppressWarnings("rawtypes") Class clz) { if (clz == null) return null; if (clz.isArray()) return getCodebase(clz.getComponentType()); if (clz.isPrimitive()) return null; ClassLoader theLoader = clz.getClassLoader(); // ignore system classes if (theLoader == null) return null; // ignore J2SE base class loader if (theLoader == (Object.class).getClassLoader()) return null; // ignore standard extensions if (theLoader == BEST_GUESS_AT_EXTENSION_CLASS_LOADER) return null; RMIState state = RMIState.current(); ClassLoader stateLoader = state.getClassLoader(); try { // is the class loaded with the stateLoader? if (clz.equals(stateLoader.loadClass(clz.getName()))) { java.net.URL codebaseURL = state.getCodeBase(); if (codebaseURL != null) { logger.finer("class " + clz.getName() + " => " + codebaseURL); // System.out.println ("class "+clz.getName()+" => // "+codebaseURL); return codebaseURL.toString(); } } } catch (ClassNotFoundException ex) { // ignore } return AccessController.doPrivileged(new GetSystemPropertyAction("java.rmi.server.codebase")); } static class SecMan extends java.rmi.RMISecurityManager { @SuppressWarnings("rawtypes") public Class[] getClassContext() { return super.getClassContext(); } } private static SecMan getSecMan() { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<SecMan>() { public SecMan run() { return new SecMan(); } }); } catch (PrivilegedActionException e) { throw new RuntimeException(e); } } @SuppressWarnings("rawtypes") public Class loadClass(String name, String codebase, ClassLoader loader) throws ClassNotFoundException { try { return loadClass0(name, codebase, loader); } catch (ClassNotFoundException ex) { logger.log(Level.FINER, "cannot load from " + codebase + " " + ex.getMessage(), ex); throw ex; } } static public Class<?> loadClass0(String name, String codebase, ClassLoader loader) throws ClassNotFoundException { try { return ProviderLocator.loadClass(name, null, loader); } catch (ClassNotFoundException e) { //skip } Class<?> result = null; ClassLoader stackLoader = null; ClassLoader thisLoader = Util.class.getClassLoader(); Class<?>[] stack = _secman.getClassContext(); for (int i = 1; i < stack.length; i++) { ClassLoader testLoader = stack[i].getClassLoader(); if (testLoader != null && testLoader != thisLoader) { stackLoader = thisLoader; break; } } if (stackLoader != null) { try { result = stackLoader.loadClass(name); } catch (ClassNotFoundException ex) { // skip // } if (result != null) { return result; } } // try loading using our loader, just in case we really were loaded // using the same classloader the delegate is in. if (thisLoader != null) { try { result = thisLoader.loadClass(name); } catch (ClassNotFoundException ex) { // skip // } if (result != null) { return result; } } if (codebase != null && !"".equals(codebase) && !Boolean.getBoolean("java.rmi.server.useCodeBaseOnly")) { logger.finer("trying RMIClassLoader"); try (URLClassLoader url_loader = new URLClassLoader(new URL[]{new URL(codebase)}, loader)) { result = url_loader.loadClass(name); } catch (ClassNotFoundException ex) { logger.log(Level.FINER, "RMIClassLoader says " + ex.getMessage(), ex); } catch (MalformedURLException ex) { logger.log(Level.FINER, "RMIClassLoader says " + ex.getMessage(), ex); logger.finer("FAILED class download " + name + " from " + codebase + " " + ex.getMessage()); } catch (RuntimeException ex) { logger.log(Level.FINER, "FAILED class download " + name + " from " + codebase + " " + ex.getMessage(), ex); } catch (IOException unimportant) { } if (result != null) { return result; } } else { codebase = (String) AccessController.doPrivileged(new GetSystemPropertyAction("java.rmi.server.codebase")); if (codebase != null) { try { result = java.rmi.server.RMIClassLoader.loadClass(codebase, name); } catch (ClassNotFoundException ex) { // skip // } catch (MalformedURLException ex) { // skip // } if (result != null) { return result; } } } if (loader == null) { loader = getContextClassLoader(); } try { result = loader.loadClass(name); } catch (ClassNotFoundException ex) { logger.log(Level.FINER, "LocalLoader says " + ex.getMessage(), ex); } if (result != null) { return result; } throw new ClassNotFoundException(name); } public boolean isLocal(Stub stub) throws RemoteException { try { if (stub instanceof RMIStub) { return true; } else { return stub._is_local(); } } catch (org.omg.CORBA.SystemException ex) { throw mapSystemException(ex); } } public RemoteException wrapException(Throwable ex) { if (ex instanceof Error) { return new java.rmi.ServerError(ex.getMessage(), (Error) ex); } else if (ex instanceof RemoteException) { return new java.rmi.ServerException(ex.getMessage(), (Exception) ex); } else if (ex instanceof org.omg.CORBA.portable.UnknownException) { org.omg.CORBA.portable.UnknownException uex = (org.omg.CORBA.portable.UnknownException) ex; return new java.rmi.ServerError( ex.getMessage(), (uex.originalEx instanceof Error ? (Error) uex.originalEx : new Error("[OTHER EXCEPTION] " + ex.getMessage()))); } else if (ex instanceof org.omg.CORBA.SystemException) { return mapSystemException((org.omg.CORBA.SystemException) ex); } else if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { return new java.rmi.RemoteException(ex.getMessage(), ex); } } static ClassLoader getContextClassLoader() { return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); } static ClassLoader getClassLoader(final Class<?> clz) { if (System.getSecurityManager() == null) { return clz.getClassLoader(); } else { return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return clz.getClassLoader(); } }); } } static Object copyRMIStub(RMIStub stub) throws RemoteException { ClassLoader loader = getContextClassLoader(); if (getClassLoader(stub._descriptor.type) == loader) { return stub; } RemoteDescriptor desc = stub._descriptor; Class<?> targetClass; try { targetClass = Util.loadClass(desc.type.getName(), stub ._get_codebase(), loader); } catch (ClassNotFoundException ex) { logger.log(Level.FINER, "copyRMIStub exception (current loader is: " + loader + ") " + ex.getMessage(), ex); throw new RemoteException("Class not found", ex); } return PortableRemoteObjectImpl.narrow1(RMIState.current(), stub, targetClass); } static boolean copy_with_corba = false; /** * Copy a single object, maintaining internal reference integrity. * <p/> * This is done by writing and reading the object to/from a temporary * stream. As such, this should be called after the receiving context's * class-loaders etc. have been set up. */ public Object copyObject(Object obj, org.omg.CORBA.ORB orb) throws RemoteException { if (obj == null) return null; if (orb == null) throw new NullPointerException(); if (obj instanceof String || obj instanceof Number) return obj; if (obj instanceof RMIStub) { return copyRMIStub((RMIStub) obj); } /* * try { org.omg.CORBA_2_3.portable.OutputStream out = * (org.omg.CORBA_2_3.portable.OutputStream) orb.create_output_stream * (); * * out.write_value ((java.io.Serializable) obj); * * org.omg.CORBA_2_3.portable.InputStream in = * (org.omg.CORBA_2_3.portable.InputStream) out.create_input_stream (); * * return in.read_value (); * } catch (org.omg.CORBA.SystemException ex) { throw * mapSystemException (ex); } */ try { TypeRepository rep = RMIState.current().repo; CopyState state = new CopyState(rep); return state.copy(obj); } catch (CopyRecursionException ex) { throw new MarshalException("unable to resolve recursion", ex); } catch (org.omg.CORBA.SystemException ex) { throw mapSystemException(ex); } } static final Object READ_SERIALIZABLE_KEY = new Object(); /** * Copy an array of objects, maintaining internal reference integrity. * <p/> * This is done by writing and reading the object array to/from a temporary * stream. As such, this should be called after the receiving context's * class-loaders etc. have been set up. */ public Object[] copyObjects(Object[] objs, org.omg.CORBA.ORB orb) throws RemoteException { if (objs == null || orb == null) throw new NullPointerException(); if (objs.length == 0) return objs; try { TypeRepository rep = RMIState.current().repo; CopyState state = new CopyState(rep); try { return (Object[]) state.copy(objs); } catch (CopyRecursionException ex) { throw new MarshalException("unable to resolve recursion", ex); } /* * int length = objs.length; * * for (int i = 0; i < length; i++) { * * Object val = objs[i]; * * if (val == null || val instanceof String || val instanceof * Number) { // do nothing, just leave the object in place // * } else if (val instanceof RMIStub) { objs[i] = * copyRMIStub((RMIStub)val); * } else { if (orb == null) { orb = RMIState.current().getORB(); } * * if (out == null) { out = * (org.omg.CORBA_2_3.portable.OutputStream) orb * .create_output_stream(); } * * out.write_value((java.io.Serializable) val); objs[i] = * READ_SERIALIZABLE_KEY; } * } * * if (out != null) { * * org.omg.CORBA_2_3.portable.InputStream in = * (org.omg.CORBA_2_3.portable.InputStream) out * .create_input_stream(); * * for (int i = 0; i < length; i++) { if (objs[i] == * READ_SERIALIZABLE_KEY) { objs[i] = in.read_value(); } } } * * return objs; */ } catch (org.omg.CORBA.SystemException ex) { throw mapSystemException(ex); } } public void unexportObject(Remote obj) throws java.rmi.NoSuchObjectException { if (obj == null) return; java.util.Map<Remote, Tie> tie_map = tie_map(); if (tie_map == null) return; Tie tie = tie_map.remove(obj); if (tie == null) { logger.fine("unexporting unknown instance of " + obj.getClass().getName() + " from " + RMIState.current().getName()); return; } else { logger.finer("unexporting instance of " + obj.getClass().getName() + " from " + RMIState.current().getName()); } tie.deactivate(); } }
3,286
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/StubBuilder.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class StubBuilder { public StubBuilder() { } /** * Generate stubs for the list of Classes (java.lang.Class objects) * specified in INTERFACES; into the directory specified by DIR. The * resulting set of generated classes may well include more classes than * specified in INTERFACES. * * @return list of File objects for generated files. */ static public Collection generateStubs(File dir, Collection interfaces) throws IOException { Set pending = new HashSet(); ArrayList result = new ArrayList(); TypeRepository rep = TypeRepository.get(); Iterator it = interfaces.iterator(); while (it.hasNext()) { Class cl = (Class) it.next(); RemoteDescriptor desc = (RemoteDescriptor) rep.getDescriptor(cl); desc.addDependencies(pending); } Class[] classes = new Class[pending.size()]; pending.toArray(classes); for (int i = 0; i < classes.length; i++) { if (!java.rmi.Remote.class.isAssignableFrom(classes[i])) { continue; } RemoteDescriptor desc = (RemoteDescriptor) rep .getDescriptor(classes[i]); String name = desc.getStubClassName(); String file = name.replace('.', File.separatorChar) + ".java"; File stubfile = new File(dir, file); File gendir = stubfile.getParentFile(); gendir.mkdirs(); PrintWriter pw = new PrintWriter(new FileWriter(stubfile)); desc.writeStubClass(pw); pw.close(); result.add(file); } return result; } public static void main(String[] args) throws Exception { ArrayList al = new ArrayList(); for (int i = 0; i < args.length; i++) { al.add(Class.forName(args[i])); } StubBuilder.generateStubs(new File("."), al); } }
3,287
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RemoteClassDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class RemoteClassDescriptor extends RemoteDescriptor { @Override protected String genRepId() { return String.format("IDL:%s:1.0", type.getName().replace('.', '/')); } RemoteClassDescriptor(Class type, TypeRepository repository) { super(type, repository); } @Override protected RemoteInterfaceDescriptor genRemoteInterface() { Class[] remotes = collect_remote_interfaces(type); if (remotes.length == 0) { throw new RuntimeException(type.getName() + " has no remote interfaces"); } Class most_specific_interface = remotes[0]; return repo.getDescriptor(most_specific_interface).getRemoteInterface(); } }
3,288
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/StringDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.omg.CORBA.MARSHAL; import org.omg.CORBA.TypeCode; import org.omg.CORBA.WStringValueHelper; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.OutputStream; import java.io.Serializable; class StringDescriptor extends ValueDescriptor { StringDescriptor(TypeRepository repository) { super(String.class, repository); } @Override protected final String genIDLName() { return "CORBA_WStringValue"; } @Override protected String genPackageName() { return "CORBA"; } @Override protected String genTypeName() { return "WStringValue"; } /** Read an instance of this value from a CDR stream */ @Override public Object read(InputStream in) { return WStringValueHelper.read(in); } /** Write an instance of this value to a CDR stream */ @Override public void write(OutputStream out, Object value) { WStringValueHelper.write(out, (String) value); } @Override public void writeValue(OutputStream out, Serializable value) { throw new MARSHAL("internal error"); } @Override protected final TypeCode genTypeCode() { return WStringValueHelper.type(); } @Override Object copyObject(Object value, CopyState state) { return value; } }
3,289
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/MethodDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.PrintWriter; import java.lang.reflect.Method; import java.rmi.MarshalException; import java.rmi.RemoteException; import java.util.logging.Logger; import java.util.logging.Level; import javax.rmi.CORBA.Util; import org.omg.CORBA.ORB; public final class MethodDescriptor extends ModelElement { static final Logger logger = Logger.getLogger(MethodDescriptor.class.getName()); /** The refleced method object for this method */ final java.lang.reflect.Method reflected_method; java.lang.Object invocation_block_selector; boolean onewayInitialized = false; boolean oneway = false; public boolean responseExpected() { if (!onewayInitialized) { if (!reflected_method.getReturnType().equals(Void.TYPE)) { onewayInitialized = true; oneway = false; return true; } Class[] exceptions = reflected_method.getExceptionTypes(); for (int i = 0; i < exceptions.length; i++) { if (exceptions[i] == org.apache.yoko.rmi.api.RemoteOnewayException.class) { oneway = true; break; } } onewayInitialized = true; } return !oneway; } public java.lang.reflect.Method getReflectedMethod() { return reflected_method; } MethodDescriptor(java.lang.reflect.Method method, TypeRepository repository) { super(repository, method.getName()); reflected_method = method; } /** The number of arguments */ int parameter_count; /** The argument's type descriptors */ TypeDescriptor[] parameter_types; /** The return value's type descriptor */ TypeDescriptor return_type; /** The declared exception's type descriptors */ ExceptionDescriptor[] exception_types; boolean copyWithinState; /** * Copy a set of arguments. If sameState=true, then we're invoking on the * same RMIState, i.e. an environment with the same context class loader. */ Object[] copyArguments(Object[] args, boolean sameState, ORB orb) throws RemoteException { if (!sameState) { try { org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) orb .create_output_stream(); for (int i = 0; i < args.length; i++) { if (parameter_types[i].copyBetweenStates()) { parameter_types[i].write(out, args[i]); } } org.omg.CORBA_2_3.portable.InputStream in = (org.omg.CORBA_2_3.portable.InputStream) out .create_input_stream(); for (int i = 0; i < args.length; i++) { if (parameter_types[i].copyBetweenStates()) { args[i] = parameter_types[i].read(in); } } } catch (org.omg.CORBA.SystemException ex) { logger.log(Level.FINE, "Exception occurred copying arguments", ex); throw Util.mapSystemException(ex); } } else if (copyWithinState) { CopyState state = new CopyState(repo); for (int i = 0; i < args.length; i++) { if (parameter_types[i].copyWithinState()) { try { args[i] = state.copy(args[i]); } catch (CopyRecursionException e) { final int idx = i; final Object[] args_arr = args; state.registerRecursion(new CopyRecursionResolver( args[i]) { public void resolve(Object value) { args_arr[idx] = value; } }); } } } } return args; } Object copyResult(Object result, boolean sameState, ORB orb) throws RemoteException { if (result == null) { return null; } if (!sameState) { if (return_type.copyBetweenStates()) { try { org.omg.CORBA_2_3.portable.OutputStream out = (org.omg.CORBA_2_3.portable.OutputStream) orb .create_output_stream(); return_type.write(out, result); org.omg.CORBA_2_3.portable.InputStream in = (org.omg.CORBA_2_3.portable.InputStream) out .create_input_stream(); return return_type.read(in); } catch (org.omg.CORBA.SystemException ex) { logger.log(Level.FINE, "Exception occurred copying result", ex); throw Util.mapSystemException(ex); } } } else if (copyWithinState) { CopyState state = new CopyState(repo); try { return state.copy(result); } catch (CopyRecursionException e) { throw new MarshalException("cannot copy recursive value?"); } } return result; } /** * read the arguments to this method, and return them as an array of objects */ public Object[] readArguments(org.omg.CORBA.portable.InputStream in) { Object[] args = new Object[parameter_count]; for (int i = 0; i < parameter_count; i++) { args[i] = parameter_types[i].read(in); } return args; } public void writeArguments(org.omg.CORBA.portable.OutputStream out, Object[] args) { /* * if (log.isDebugEnabled ()) { java.util.Map recurse = new * org.apache.yoko.rmi.util.IdentityHashMap (); java.io.CharArrayWriter cw = new * java.io.CharArrayWriter (); java.io.PrintWriter pw = new * java.io.PrintWriter (cw); * * pw.print ("invoking "); pw.print (reflected_method.toString ()); * * for (int i = 0; i < parameter_count; i++) { pw.print (" arg["+i+"] = * "); if (args[i] == null) { pw.write ("null"); } else { TypeDescriptor * desc; * * try { desc = getTypeRepository ().getDescriptor (args[i].getClass * ()); } catch (RuntimeException ex) { desc = parameter_types[i]; } * * desc.print (pw, recurse, args[i]); } } * * pw.close (); log.debug (cw.toString ()); } */ for (int i = 0; i < parameter_count; i++) { parameter_types[i].write(out, args[i]); } } /** write the result of this method */ public void writeResult(org.omg.CORBA.portable.OutputStream out, Object value) { return_type.write(out, value); } static final String UNKNOWN_EXCEPTION_ID = "IDL:omg.org/CORBA/portable/UnknownException:1.0"; public org.omg.CORBA.portable.OutputStream writeException( org.omg.CORBA.portable.ResponseHandler response, Throwable ex) { for (int i = 0; i < exception_types.length; i++) { if (exception_types[i].type.isInstance(ex)) { org.omg.CORBA.portable.OutputStream out = response .createExceptionReply(); org.omg.CORBA_2_3.portable.OutputStream out2 = (org.omg.CORBA_2_3.portable.OutputStream) out; out2 .write_string(exception_types[i] .getExceptionRepositoryID()); out2.write_value((java.io.Serializable) ex); return out; } } logger.log(Level.WARNING, "unhandled exception: " + ex.getMessage(), ex); throw new org.omg.CORBA.portable.UnknownException(ex); } public void readException(org.omg.CORBA.portable.InputStream in) throws Throwable { org.omg.CORBA_2_3.portable.InputStream in2 = (org.omg.CORBA_2_3.portable.InputStream) in; String ex_id = in.read_string(); Throwable ex = null; for (int i = 0; i < exception_types.length; i++) { if (ex_id.equals(exception_types[i].getExceptionRepositoryID())) { ex = (Throwable) in2.read_value(); throw ex; } } ex = (Throwable) in2.read_value(); if (ex instanceof Exception) { throw new java.rmi.UnexpectedException(ex.getMessage(), (Exception) ex); } else if (ex instanceof Error) { throw ex; } } public Object readResult(org.omg.CORBA.portable.InputStream in) { Object result = return_type.read(in); /* * if (log.isDebugEnabled ()) { java.util.Map recurse = new * org.apache.yoko.rmi.util.IdentityHashMap (); java.io.CharArrayWriter cw = new * java.io.CharArrayWriter (); java.io.PrintWriter pw = new * java.io.PrintWriter (cw); * * pw.print ("returning from "); pw.println (reflected_method.toString * ()); pw.print (" => "); * * if (result == null) { pw.write ("null"); } else { * * TypeDescriptor desc; * * try { desc = getTypeRepository ().getDescriptor (result.getClass ()); } * catch (RuntimeException ex) { desc = return_type; } * * desc.print (pw, recurse, result); } * * pw.close (); log.debug (cw.toString ()); } */ return result; } String transformOverloading(String mname) { StringBuffer buf = new StringBuffer(mname); if (parameter_types.length == 0) { buf.append("__"); } else { for (int i = 0; i < parameter_types.length; i++) { buf.append("__"); buf.append(parameter_types[i].getIDLName()); } } return buf.toString(); } boolean isOverloaded = false; boolean isCaseSensitive = false; protected void setOverloaded(boolean val) { isOverloaded = val; } protected void setCaseSensitive(boolean val) { isCaseSensitive = val; } public void init() { Class[] param_types = reflected_method.getParameterTypes(); parameter_types = new TypeDescriptor[param_types.length]; for (int i = 0; i < param_types.length; i++) { try { parameter_types[i] = repo.getDescriptor(param_types[i]); copyWithinState |= parameter_types[i].copyWithinState(); } catch (RuntimeException ex) { throw ex; } } Class result_type = reflected_method.getReturnType(); return_type = repo.getDescriptor(result_type); Class[] exc_types = reflected_method.getExceptionTypes(); exception_types = new ExceptionDescriptor[exc_types.length]; for (int i = 0; i < exc_types.length; i++) { exception_types[i] = (ExceptionDescriptor) repo.getDescriptor(exc_types[i]); } parameter_count = param_types.length; super.init(); } @Override protected String genIDLName() { String idl_name = null; if (isSetterMethod()) { idl_name = "_set_" + transformIdentifier(attributeName()); } else if (isGetterMethod()) { idl_name = "_get_" + transformIdentifier(attributeName()); } else { idl_name = transformIdentifier(java_name); } if (isCaseSensitive) { idl_name = transformCaseSensitive(idl_name); } if (isOverloaded) { idl_name = transformOverloading(idl_name); } return idl_name; } private String attributeName() { String methodName = java_name; StringBuffer buf = new StringBuffer(); int pfxLen; if (methodName.startsWith("get")) pfxLen = 3; else if (methodName.startsWith("is")) pfxLen = 2; else if (methodName.startsWith("set")) pfxLen = 3; else throw new RuntimeException("methodName " + methodName + " is not attribute"); if (methodName.length() >= (pfxLen + 2) && Character.isUpperCase(methodName.charAt(pfxLen)) && Character.isUpperCase(methodName.charAt(pfxLen + 1))) { return methodName.substring(pfxLen); } buf.append(Character.toLowerCase(methodName.charAt(pfxLen))); buf.append(methodName.substring(pfxLen + 1)); return buf.toString(); } private boolean isSetterMethod() { Method m = getReflectedMethod(); String name = m.getName(); if (!name.startsWith("set")) return false; if (name.length() == 3) return false; if (!Character.isUpperCase(name.charAt(3))) return false; if (!m.getReturnType().equals(Void.TYPE)) return false; if (m.getParameterTypes().length == 1) return true; else return false; } private boolean isGetterMethod() { Method m = getReflectedMethod(); String name = m.getName(); int pfxLen; if (name.startsWith("get")) pfxLen = 3; else if (name.startsWith("is") && m.getReturnType().equals(Boolean.TYPE)) pfxLen = 2; else return false; if (name.length() == pfxLen) return false; if (!Character.isUpperCase(name.charAt(pfxLen))) return false; if (m.getReturnType().equals(Void.TYPE)) return false; if (m.getParameterTypes().length == 0) return true; else return false; } static String transformIdentifier(String name) { StringBuffer buf = new StringBuffer(); // it cannot start with underscore; prepend a 'J' if (name.charAt(0) == '_') buf.append('J'); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); // basic identifier elements if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || (ch == '_')) { buf.append(ch); } // dot becomes underscore else if (ch == '.') { buf.append('_'); } // else, use translate to UXXXX unicode else { buf.append('U'); String hex = Integer.toHexString((int) ch); switch (hex.length()) { case 1: buf.append('0'); case 2: buf.append('0'); case 3: buf.append('0'); } buf.append(hex); } } return buf.toString(); } private static String transformCaseSensitive(String name) { StringBuffer buf = new StringBuffer(name); buf.append('_'); for (int i = 0; i < name.length(); i++) { char ch = name.charAt(i); // basic identifier elements if (Character.isUpperCase(ch)) { buf.append('_'); buf.append(i); } } return buf.toString(); } void writeStubMethod(PrintWriter pw) { pw.println("\t/**"); pw.println("\t *"); pw.println("\t */"); writeMethodHead(pw); pw.println("\t{"); pw.println("\t\tboolean marshal = !" + UTIL + ".isLocal (this);"); pw.println("\t\tmarshal: while(true) {"); pw.println("\t\tif(marshal) {"); writeMarshalCall(pw); pw.println("\t\t} else {"); writeLocalCall(pw); pw.println("\t\t}}"); // pw.println ("throw new org.omg.CORBA.NO_IMPLEMENT(\"local // invocation\")"); pw.println("\t}\n"); } void writeMethodHead(PrintWriter pw) { pw.print("\tpublic "); writeJavaType(pw, reflected_method.getReturnType()); pw.print(' '); pw.print(java_name); pw.print(" ("); Class[] args = reflected_method.getParameterTypes(); for (int i = 0; i < args.length; i++) { if (i != 0) { pw.print(", "); } writeJavaType(pw, args[i]); pw.print(" arg"); pw.print(i); } pw.println(")"); Class[] ex = reflected_method.getExceptionTypes(); pw.print("\t\tthrows "); for (int i = 0; i < ex.length; i++) { if (i != 0) { pw.print(", "); } writeJavaType(pw, ex[i]); } pw.println(); } static void writeJavaType(PrintWriter pw, Class type) { if (type.isArray()) { writeJavaType(pw, type.getComponentType()); pw.print("[]"); } else { pw.print(type.getName()); } } static final String SERVANT = "org.omg.CORBA.portable.ServantObject"; static final String INPUT = "org.omg.CORBA_2_3.portable.InputStream"; static final String OUTPUT = "org.omg.CORBA_2_3.portable.OutputStream"; static final String UTIL = "javax.rmi.CORBA.Util"; void writeMarshalCall(PrintWriter pw) { pw.println("\t\t" + INPUT + " in = null;"); pw.println("\t\ttry {"); pw.println("\t\t\t" + OUTPUT + " out " + "= (" + OUTPUT + ")_request (\"" + getIDLName() + "\", true);"); pw.println("\t\t\ttry{"); Class[] args = reflected_method.getParameterTypes(); for (int i = 0; i < args.length; i++) { TypeDescriptor desc = repo.getDescriptor(args[i]); pw.print("\t\t\t"); desc.writeMarshalValue(pw, "out", "arg" + i); pw.println(";"); } pw.println("\t\t\tin = (" + INPUT + ")_invoke(out);"); Class rtype = reflected_method.getReturnType(); if (rtype == Void.TYPE) { pw.println("\t\t\treturn;"); } else { pw.print("\t\t\treturn ("); writeJavaType(pw, rtype); pw.print(")"); TypeDescriptor desc = repo.getDescriptor(rtype); desc.writeUnmarshalValue(pw, "in"); pw.println(";"); } pw .println("\t\t} catch (org.omg.CORBA.portable.ApplicationException ex) {"); pw.println("\t\t\t" + INPUT + " exin = (" + INPUT + ")ex.getInputStream();"); pw.println("\t\t\tString exname = exin.read_string();"); Class[] ex = reflected_method.getExceptionTypes(); for (int i = 0; i < ex.length; i++) { if (java.rmi.RemoteException.class.isAssignableFrom(ex[i])) { continue; } ExceptionDescriptor exd = (ExceptionDescriptor) repo.getDescriptor(ex[i]); pw.println("\t\t\tif (exname.equals(\"" + exd.getExceptionRepositoryID() + "\"))"); pw.print("\t\t\t\tthrow ("); writeJavaType(pw, ex[i]); pw.print(")exin.read_value("); writeJavaType(pw, ex[i]); pw.println(".class);"); } pw.println("\t\t\tthrow new java.rmi.UnexpectedException(exname,ex);"); pw .println("\t\t} catch (org.omg.CORBA.portable.RemarshalException ex) {"); pw.println("\t\t\tcontinue marshal;"); pw.println("\t\t} finally {"); pw.println("\t\t\t if(in != null) _releaseReply(in);"); pw.println("\t\t}"); pw.println("\t\t} catch (org.omg.CORBA.SystemException ex) {"); pw.println("\t\t\t throw " + UTIL + ".mapSystemException(ex);"); pw.println("\t\t}"); } void writeLocalCall(PrintWriter pw) { Class thisClass = reflected_method.getDeclaringClass(); pw.println("\t\t\t" + SERVANT + " so = _servant_preinvoke ("); pw.println("\t\t\t\t\"" + getIDLName() + "\","); pw.print("\t\t\t\t"); writeJavaType(pw, thisClass); pw.println(".class);"); pw .print("\t\t\tif (so==null || so.servant==null || !(so.servant instanceof "); writeJavaType(pw, thisClass); pw.print("))"); pw.println(" { marshal=true; continue marshal; }"); pw.println("\t\t\ttry {"); // copy arguments Class[] args = reflected_method.getParameterTypes(); if (args.length == 1) { if (repo.getDescriptor(args[0]).copyInStub()) { pw.print("\t\t\t\targ0 = ("); writeJavaType(pw, args[0]); pw.println(")" + UTIL + ".copyObject(arg0, _orb());"); } } else if (args.length > 1) { boolean[] copy = new boolean[args.length]; int copyCount = 0; for (int i = 0; i < args.length; i++) { TypeDescriptor td = repo.getDescriptor(args[i]); copy[i] = td.copyInStub(); if (copy[i]) { copyCount += 1; } } if (copyCount > 0) { pw.println("\t\t\t\tObject[] args = new Object[" + copyCount + "];"); int pos = 0; for (int i = 0; i < args.length; i++) { if (copy[i]) { pw.println("\t\t\t\targs[" + (pos++) + "] = arg" + i + ";"); } } pw.println("\t\t\t\targs=" + UTIL + ".copyObjects(args,_orb());"); pos = 0; for (int i = 0; i < args.length; i++) { if (copy[i]) { pw.print("\t\t\t\targ" + i + "=("); writeJavaType(pw, args[i]); pw.println(")args[" + (pos++) + "];"); } } } } // now, invoke! Class out = reflected_method.getReturnType(); pw.print("\t\t\t\t"); if (out != Void.TYPE) { writeJavaType(pw, out); pw.print(" result = "); } pw.print("(("); writeJavaType(pw, thisClass); pw.print(")so.servant)."); pw.print(java_name); pw.print("("); for (int i = 0; i < args.length; i++) { if (i != 0) { pw.print(','); } pw.print("arg" + i); } pw.println(");"); pw.print("\t\t\t\treturn "); if (out != Void.TYPE) { TypeDescriptor td = repo.getDescriptor(out); if (td.copyInStub()) { pw.print('('); writeJavaType(pw, out); pw.print(')'); pw.println(UTIL + ".copyObject (result, _orb());"); } else { pw.println("result;"); } } else { pw.println(";"); } pw.println("\t\t\t} finally {"); pw.println("\t\t\t\t_servant_postinvoke (so);"); pw.println("\t\t\t}"); } void addDependencies(java.util.Set classes) { TypeDescriptor desc = null; desc = repo.getDescriptor(reflected_method.getReturnType()); desc.addDependencies(classes); Class[] param = reflected_method.getParameterTypes(); for (int i = 0; i < param.length; i++) { desc = repo.getDescriptor(param[i]); desc.addDependencies(classes); } Class[] ex = reflected_method.getExceptionTypes(); for (int i = 0; i < ex.length; i++) { desc = repo.getDescriptor(ex[i]); desc.addDependencies(classes); } } static final java.lang.Class REMOTE_EXCEPTION = java.rmi.RemoteException.class; boolean isRemoteOperation() { Class[] ex = reflected_method.getExceptionTypes(); for (int i = 0; i < ex.length; i++) { if (REMOTE_EXCEPTION.isAssignableFrom(ex[i])) return true; } return false; } }
3,290
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIRemoteStub.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.rmi.Remote; /** * @since Aug 14, 2003 */ public final class RMIRemoteStub extends RMIStub implements Remote { protected Object writeReplace() { return new org.apache.yoko.rmi.impl.RMIPersistentStub(this, Remote.class); } }
3,291
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/StubHandler.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Logger; import org.omg.CORBA.ORB; /** * This class is the interface for instances of POAStub. When a client * calls a remote method, this is translated to a call to the invoke() method in * this class. */ public interface StubHandler { /** * Invocation method for an method call. This * method catches the calls from the generated * stub method and handles the appropriate * argument and return value marshalling. * * @param stub The stub object used to catch the call. * @param method The descriptor for the method being invoked. * @param args The arguments passed to the method. * * @return The method return value (if any). * @exception Throwable */ public Object invoke(RMIStub stub, MethodDescriptor method, Object[] args) throws Throwable; /** * Handle a writeReplace operation on a Stub. * * @param stub The source RMIStub. * * @return The replacement object for serialization. */ public Object stubWriteReplace(RMIStub stub); }
3,292
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/RMIStubDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.IOException; class RMIStubDescriptor extends ValueDescriptor { RMIStubDescriptor(Class type, TypeRepository repository) { super(type, repository); } @Override protected String genRepId() { final Class[] ifaces = type.getInterfaces(); if (ifaces.length != 2 || ifaces[1] != org.apache.yoko.rmi.util.stub.Stub.class) { throw new RuntimeException("Unexpected RMIStub structure"); } final String ifname = ifaces[0].getName(); final int idx = ifname.lastIndexOf('.'); return ((idx < 0) ? String.format("RMI:_%s_Stub:0", ifname) : String.format("RMI:%s_%s_Stub:0", ifname.substring(0, idx + 1), ifname.substring(idx + 1))); } // // Override writeValue/readvalue, such that only the superclass' // state is written. This ensures that fields in the proxy are // not included on the wire. // @Override protected void writeValue(ObjectWriter writer, java.io.Serializable val) throws IOException { _super_descriptor.writeValue(writer, val); } @Override protected void readValue(ObjectReader reader, java.io.Serializable value) throws IOException { _super_descriptor.readValue(reader, value); } }
3,293
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/FloatDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class FloatDescriptor extends SimpleDescriptor { FloatDescriptor(TypeRepository repository) { super(Float.TYPE, repository, "float", org.omg.CORBA.TCKind.tk_float); } public Object read(org.omg.CORBA.portable.InputStream in) { return new Float(in.read_float()); } public void write(org.omg.CORBA.portable.OutputStream out, Object val) { out.write_float(((Float) val).floatValue()); } }
3,294
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/IDLEntityDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import org.omg.CORBA.MARSHAL; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.ObjectImpl; import org.omg.CORBA.portable.OutputStream; import javax.rmi.CORBA.Util; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; class IDLEntityDescriptor extends ValueDescriptor { private final boolean isCorba; private final Class helperType; IDLEntityDescriptor(Class type, TypeRepository repository) { super(type, repository); isCorba = org.omg.CORBA.Object.class.isAssignableFrom(type); try { final String helperName = type.getName() + "Helper"; helperType = Util.loadClass(helperName, null, type.getClassLoader()); } catch (ClassNotFoundException ex) { throw new RuntimeException("cannot load IDL Helper class for " + type, ex); } } @Override protected final String genIDLName() { return "org_omg_boxedIDL_" + super.genIDLName(); } private volatile Method readMethod = null; private Method getReadMethod() { if (null == readMethod) readMethod = genHelperMethod("read"); return readMethod; } private volatile Method writeMethod = null; private Method getWriteMethod() { if (null == writeMethod) writeMethod = genHelperMethod("write"); return writeMethod; } private volatile Method typeMethod = null; private Method getTypeMethod() { if (null == typeMethod) typeMethod = genHelperMethod("type"); return typeMethod; } private Method genHelperMethod(final String name) { return AccessController.doPrivileged(new PrivilegedAction<Method>() { @Override public Method run() { for (Method m: helperType.getDeclaredMethods()) { if (m.getName().equals(name)) return m; } throw new RuntimeException("Unable to find " + name + " method for " + helperType.getName()); } }); } /** Read an instance of this value from a CDR stream */ @Override public Object read(InputStream in) { org.omg.CORBA_2_3.portable.InputStream _in = (org.omg.CORBA_2_3.portable.InputStream) in; // there are two ways we need to deal with IDLEntity classes. Ones that also implement // the CORBA Object interface are actual corba objects, and must be handled that way. // Other IDLEntity classes are just transmitted by value. if (isCorba) { return _in.read_Object(type); } else { // we directly call read_value() on the stream here, with the explicitly specified // repository ID. The input stream will handle validating the value tag for us, and eventually // will call our readValue() method to deserialize the object. return _in.read_value(getRepositoryID()); } } @Override public Serializable readValue(final InputStream in, final Map offsetMap, final Integer offset) { try { Serializable value = (Serializable) getReadMethod().invoke(null, new Object[]{in}); offsetMap.put(offset, value); return value; } catch (InvocationTargetException ex) { throw (MARSHAL)new MARSHAL(""+ex.getCause()).initCause(ex.getCause()); } catch (IllegalAccessException ex) { throw (MARSHAL)new MARSHAL(ex.getMessage()).initCause(ex); } } /** Write an instance of this value to a CDR stream */ @Override public void write(OutputStream out, Object val) { org.omg.CORBA_2_3.portable.OutputStream _out = (org.omg.CORBA_2_3.portable.OutputStream) out; // there are two ways we need to deal with IDLEntity classes. Ones that also implement // the CORBA Object interface are actual corba objects, and must be handled that way. // Other IDLEntity classes are just transmitted by value. if (val instanceof ObjectImpl) { _out.write_Object((org.omg.CORBA.Object)val); } else { // we directly call write_value() on the stream here, with the explicitly specified // repository ID. the output stream will handle writing the value tag for us, and eventually // will call our writeValue() method to serialize the object. _out.write_value((Serializable)val, getRepositoryID()); } } @Override public void writeValue(OutputStream out, Serializable val) { try { getWriteMethod().invoke(null, new Object[] { out, val }); } catch (InvocationTargetException ex) { throw (MARSHAL)new MARSHAL(""+ ex.getCause()).initCause(ex.getCause()); } catch (IllegalAccessException ex) { throw (MARSHAL)new MARSHAL(ex.getMessage()).initCause(ex); } } @Override protected TypeCode genTypeCode() { try { return (TypeCode) getTypeMethod().invoke(null, new Object[0]); } catch (InvocationTargetException ex) { throw (MARSHAL)new MARSHAL(""+ex.getCause()).initCause(ex.getCause()); } catch (IllegalAccessException ex) { throw (MARSHAL)new MARSHAL(ex.getMessage()).initCause(ex); } } }
3,295
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/DelegatingObjectReaderWithHook.java
package org.apache.yoko.rmi.impl; import java.io.Externalizable; import java.io.IOException; import java.io.InvalidObjectException; import java.io.NotActiveException; import java.io.ObjectInputValidation; import java.rmi.Remote; import org.omg.CORBA.portable.IndirectionException; abstract class DelegatingObjectReaderWithBeforeReadHook extends DelegatingObjectReader { private final ObjectReader delegate; DelegatingObjectReaderWithBeforeReadHook(ObjectReader delegate) throws IOException { super.delegateTo(delegate); this.delegate = delegate; } abstract void beforeRead(); @Override final void delegateTo(ObjectReader delegate) { throw new UnsupportedOperationException(); } ////////////////////////////////////// // ONLY DELEGATE METHODS BELOW HERE // ////////////////////////////////////// public int read(byte[] b) throws IOException { beforeRead(); return delegate.read(b); } public long skip(long n) throws IOException { beforeRead(); return delegate.skip(n); } public void mark(int readlimit) { delegate.mark(readlimit); } public void reset() throws IOException { delegate.reset(); } public boolean markSupported() { return delegate.markSupported(); } public Object readUnshared() throws IOException, ClassNotFoundException { beforeRead(); return delegate.readUnshared(); } public abstract void defaultReadObject() throws IOException, ClassNotFoundException; public abstract GetField readFields() throws IOException, ClassNotFoundException; public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException { delegate.registerValidation(obj, prio); } public int read() throws IOException { beforeRead(); return delegate.read(); } public int read(byte[] buf, int off, int len) throws IOException { beforeRead(); return delegate.read(buf, off, len); } public int available() throws IOException { return delegate.available(); } public void close() throws IOException { delegate.close(); } public boolean readBoolean() throws IOException { beforeRead(); return delegate.readBoolean(); } public byte readByte() throws IOException { beforeRead(); return delegate.readByte(); } public int readUnsignedByte() throws IOException { beforeRead(); return delegate.readUnsignedByte(); } public char readChar() throws IOException { beforeRead(); return delegate.readChar(); } public short readShort() throws IOException { beforeRead(); return delegate.readShort(); } public int readUnsignedShort() throws IOException { beforeRead(); return delegate.readUnsignedShort(); } public int readInt() throws IOException { beforeRead(); return delegate.readInt(); } public long readLong() throws IOException { beforeRead(); return delegate.readLong(); } public float readFloat() throws IOException { beforeRead(); return delegate.readFloat(); } public double readDouble() throws IOException { beforeRead(); return delegate.readDouble(); } public void readFully(byte[] buf) throws IOException { beforeRead(); delegate.readFully(buf); } public void readFully(byte[] buf, int off, int len) throws IOException { beforeRead(); delegate.readFully(buf, off, len); } public int skipBytes(int len) throws IOException { beforeRead(); return delegate.skipBytes(len); } @SuppressWarnings("deprecation") public String readLine() throws IOException { beforeRead(); return delegate.readLine(); } public String readUTF() throws IOException { beforeRead(); return delegate.readUTF(); } @Override protected final Object readObjectOverride() throws ClassNotFoundException ,IOException { beforeRead(); return delegate.readObjectOverride(); }; /////////////////////////////////////// // delegate methods for ObjectReader // /////////////////////////////////////// Object readAbstractObject() throws IndirectionException { beforeRead(); return delegate.readAbstractObject(); } Object readAny() throws IndirectionException { beforeRead(); return delegate.readAny(); } Object readValueObject() throws IndirectionException { beforeRead(); return delegate.readValueObject(); } Object readValueObject(Class<?> clz) throws IndirectionException { beforeRead(); return delegate.readValueObject(clz); } org.omg.CORBA.Object readCorbaObject(Class<?> type) { beforeRead(); return delegate.readCorbaObject(type); } Remote readRemoteObject(Class<?> type) { beforeRead(); return delegate.readRemoteObject(type); } void readExternal(Externalizable ext) throws IOException, ClassNotFoundException { beforeRead(); delegate.readExternal(ext); } }
3,296
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/LongDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; final class LongDescriptor extends SimpleDescriptor { LongDescriptor(TypeRepository repository) { super(Long.TYPE, repository, "long_long", org.omg.CORBA.TCKind.tk_longlong); } public Object read(org.omg.CORBA.portable.InputStream in) { return new Long(in.read_longlong()); } public void write(org.omg.CORBA.portable.OutputStream out, Object val) { out.write_longlong(((Long) val).longValue()); } }
3,297
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ClassDescriptor.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; import java.io.Serializable; import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Level; import java.util.logging.Logger; import javax.rmi.CORBA.ClassDesc; import javax.rmi.CORBA.Util; import javax.rmi.CORBA.ValueHandler; import org.omg.CORBA.MARSHAL; class ClassDescriptor extends ClassBaseDescriptor { private static final Logger logger = Logger.getLogger(ClassDescriptor.class.getName()); ClassDescriptor(TypeRepository repository) { super(Class.class, repository); } @Override Object copyObject(Object orig, CopyState state) { state.put(orig, orig); return orig; } /** Write an instance of this value to a CDR stream */ @Override public Serializable writeReplace(final Serializable value) { final Class<?> type = (Class<?>) value; final ClassDesc result = AccessController .doPrivileged(new PrivilegedAction<ClassDesc>() { public ClassDesc run() { try { final ClassDesc desc = new ClassDesc(); ValueHandler handler = Util.createValueHandler(); String repId = handler.getRMIRepositoryID(type); getRepidField().set(desc, repId); String codebase = Util.getCodebase(type); getCobebaseField().set(desc, codebase); return desc; } catch (IllegalAccessException ex) { throw (MARSHAL)new MARSHAL("no such field: " + ex).initCause(ex); } } }); if (logger.isLoggable(Level.FINE)) logger.fine(String.format("writeReplace %s => %s", value, result)); return result; } }
3,298
0
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi
Create_ds/geronimo-yoko/yoko-rmi-impl/src/main/java/org/apache/yoko/rmi/impl/ModelElement.java
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.yoko.rmi.impl; abstract class ModelElement { final TypeRepository repo; final String java_name; // the java name of the type protected ModelElement(TypeRepository repo, String java_name) { this.repo = repo; this.java_name = java_name; } protected void init() { } private volatile String idlName = null; // fully resolved package name protected abstract String genIDLName(); public final String getIDLName() { if (null == idlName) idlName = genIDLName(); return idlName; } }
3,299