gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.rest.resources; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import org.hamcrest.Description; import org.hamcrest.Matchers; import org.hamcrest.TypeSafeMatcher; import org.junit.Before; import org.junit.Test; import org.onlab.osgi.ServiceDirectory; import org.onlab.osgi.TestServiceDirectory; import org.onlab.rest.BaseResource; import org.onosproject.codec.CodecService; import org.onosproject.codec.impl.CodecManager; import org.onosproject.net.key.DeviceKey; import org.onosproject.net.key.DeviceKeyAdminService; import org.onosproject.net.key.DeviceKeyId; import org.onosproject.net.key.DeviceKeyService; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotFoundException; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.HashSet; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Unit tests for device key REST APIs. */ public class DeviceKeyWebResourceTest extends ResourceTest { final DeviceKeyService mockDeviceKeyService = createMock(DeviceKeyService.class); final DeviceKeyAdminService mockDeviceKeyAdminService = createMock(DeviceKeyAdminService.class); final HashSet<DeviceKey> deviceKeySet = new HashSet<>(); private static final String ID = "id"; private static final String TYPE = "type"; private static final String LABEL = "label"; private static final String COMMUNITY_NAME = "community_name"; private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private final String deviceKeyId1 = "DeviceKeyId1"; private final String deviceKeyId2 = "DeviceKeyId2"; private final String deviceKeyId3 = "DeviceKeyId3"; private final String deviceKeyId4 = "DeviceKeyId4"; private final String deviceKeyLabel = "DeviceKeyLabel"; private final String deviceKeyCommunityName = "DeviceKeyCommunityName"; private final String deviceKeyUsername = "DeviceKeyUsername"; private final String deviceKeyPassword = "DeviceKeyPassword"; private final DeviceKey deviceKey1 = DeviceKey.createDeviceKeyUsingCommunityName( DeviceKeyId.deviceKeyId(deviceKeyId1), deviceKeyLabel, deviceKeyCommunityName); private final DeviceKey deviceKey2 = DeviceKey.createDeviceKeyUsingUsernamePassword( DeviceKeyId.deviceKeyId(deviceKeyId2), null, deviceKeyUsername, deviceKeyPassword); private final DeviceKey deviceKey3 = DeviceKey.createDeviceKeyUsingUsernamePassword( DeviceKeyId.deviceKeyId(deviceKeyId3), null, null, null); private final DeviceKey deviceKey4 = DeviceKey.createDeviceKeyUsingCommunityName( DeviceKeyId.deviceKeyId(deviceKeyId4), null, null); /** * Initializes test mocks and environment. */ @Before public void setUpMocks() { expect(mockDeviceKeyService.getDeviceKeys()).andReturn(deviceKeySet).anyTimes(); // Register the services needed for the test CodecManager codecService = new CodecManager(); codecService.activate(); ServiceDirectory testDirectory = new TestServiceDirectory() .add(DeviceKeyService.class, mockDeviceKeyService) .add(DeviceKeyAdminService.class, mockDeviceKeyAdminService) .add(CodecService.class, codecService); BaseResource.setServiceDirectory(testDirectory); } /** * Hamcrest matcher to check that a device key representation in JSON matches * the actual device key. */ public static class DeviceKeyJsonMatcher extends TypeSafeMatcher<JsonObject> { private final DeviceKey deviceKey; private String reason = ""; public DeviceKeyJsonMatcher(DeviceKey deviceKeyValue) { deviceKey = deviceKeyValue; } @Override public boolean matchesSafely(JsonObject jsonHost) { // Check the device key id final String jsonId = jsonHost.get(ID).asString(); if (!jsonId.equals(deviceKey.deviceKeyId().id().toString())) { reason = ID + " " + deviceKey.deviceKeyId().id().toString(); return false; } // Check the device key label final String jsonLabel = (jsonHost.get(LABEL).isNull()) ? null : jsonHost.get(LABEL).asString(); if (deviceKey.label() != null) { if ((jsonLabel == null) || !jsonLabel.equals(deviceKey.label())) { reason = LABEL + " " + deviceKey.label(); return false; } } // Check the device key type final String jsonType = jsonHost.get(TYPE).asString(); if (!jsonType.equals(deviceKey.type().toString())) { reason = TYPE + " " + deviceKey.type().toString(); return false; } if (jsonType.equals(DeviceKey.Type.COMMUNITY_NAME.toString())) { // Check the device key community name final String jsonCommunityName = jsonHost.get(COMMUNITY_NAME).isNull() ? null : jsonHost.get(COMMUNITY_NAME).asString(); if (deviceKey.asCommunityName().name() != null) { if (!jsonCommunityName.equals(deviceKey.asCommunityName().name().toString())) { reason = COMMUNITY_NAME + " " + deviceKey.asCommunityName().name().toString(); return false; } } } else if (jsonType.equals(DeviceKey.Type.USERNAME_PASSWORD.toString())) { // Check the device key username final String jsonUsername = jsonHost.get(USERNAME).isNull() ? null : jsonHost.get(USERNAME).asString(); if (deviceKey.asUsernamePassword().username() != null) { if (!jsonUsername.equals(deviceKey.asUsernamePassword().username().toString())) { reason = USERNAME + " " + deviceKey.asUsernamePassword().username().toString(); return false; } } // Check the device key password final String jsonPassword = jsonHost.get(PASSWORD).isNull() ? null : jsonHost.get(PASSWORD).asString(); if (deviceKey.asUsernamePassword().password() != null) { if (!jsonPassword.equals(deviceKey.asUsernamePassword().password().toString())) { reason = PASSWORD + " " + deviceKey.asUsernamePassword().password().toString(); return false; } } } else { reason = "Unknown " + TYPE + " " + deviceKey.type().toString(); return false; } return true; } @Override public void describeTo(Description description) { description.appendText(reason); } } /** * Factory to allocate a device key array matcher. * * @param deviceKey device key object we are looking for * @return matcher */ private static DeviceKeyJsonMatcher matchesDeviceKey(DeviceKey deviceKey) { return new DeviceKeyJsonMatcher(deviceKey); } /** * Hamcrest matcher to check that a device key is represented properly in a JSON * array of device keys. */ public static class DeviceKeyJsonArrayMatcher extends TypeSafeMatcher<JsonArray> { private final DeviceKey deviceKey; private String reason = ""; public DeviceKeyJsonArrayMatcher(DeviceKey deviceKeyValue) { deviceKey = deviceKeyValue; } @Override public boolean matchesSafely(JsonArray json) { boolean deviceKeyFound = false; final int expectedAttributes = 5; for (int jsonDeviceKeyIndex = 0; jsonDeviceKeyIndex < json.size(); jsonDeviceKeyIndex++) { final JsonObject jsonHost = json.get(jsonDeviceKeyIndex).asObject(); // Device keys can have a variable number of attribute so we check // that there is a minimum number. if (jsonHost.names().size() < expectedAttributes) { reason = "Found a device key with the wrong number of attributes"; return false; } final String jsonDeviceKeyId = jsonHost.get(ID).asString(); if (jsonDeviceKeyId.equals(deviceKey.deviceKeyId().id().toString())) { deviceKeyFound = true; // We found the correct device key, check the device key attribute values assertThat(jsonHost, matchesDeviceKey(deviceKey)); } } if (!deviceKeyFound) { reason = "Device key with id " + deviceKey.deviceKeyId().id().toString() + " was not found"; return false; } else { return true; } } @Override public void describeTo(Description description) { description.appendText(reason); } } /** * Factory to allocate a device key array matcher. * * @param deviceKey device key object we are looking for * @return matcher */ private static DeviceKeyJsonArrayMatcher hasDeviceKey(DeviceKey deviceKey) { return new DeviceKeyJsonArrayMatcher(deviceKey); } /** * Tests the result of the REST API GET when there are no device keys. */ @Test public void testGetDeviceKeysEmptyArray() { replay(mockDeviceKeyService); WebTarget wt = target(); String response = wt.path("keys").request().get(String.class); assertThat(response, is("{\"keys\":[]}")); verify(mockDeviceKeyService); } /** * Tests the result of the REST API GET when device keys are defined. */ @Test public void testGetDeviceKeysArray() { replay(mockDeviceKeyService); deviceKeySet.add(deviceKey1); deviceKeySet.add(deviceKey2); deviceKeySet.add(deviceKey3); deviceKeySet.add(deviceKey4); WebTarget wt = target(); String response = wt.path("keys").request().get(String.class); assertThat(response, containsString("{\"keys\":[")); final JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); assertThat(result.names(), hasSize(1)); assertThat(result.names().get(0), is("keys")); final JsonArray deviceKeys = result.get("keys").asArray(); assertThat(deviceKeys, notNullValue()); assertEquals("Device keys array is not the correct size.", 4, deviceKeys.size()); assertThat(deviceKeys, hasDeviceKey(deviceKey1)); assertThat(deviceKeys, hasDeviceKey(deviceKey2)); assertThat(deviceKeys, hasDeviceKey(deviceKey3)); assertThat(deviceKeys, hasDeviceKey(deviceKey4)); verify(mockDeviceKeyService); } /** * Tests the result of the REST API GET using a device key identifier. */ @Test public void testGetDeviceKeyById() { deviceKeySet.add(deviceKey1); expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1))) .andReturn(deviceKey1) .anyTimes(); replay(mockDeviceKeyService); WebTarget wt = target(); String response = wt.path("keys/" + deviceKeyId1).request().get(String.class); final JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); assertThat(result, matchesDeviceKey(deviceKey1)); verify(mockDeviceKeyService); } /** * Tests that a GET of a non-existent object throws an exception. */ @Test public void testGetNonExistentDeviceKey() { expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1))) .andReturn(null) .anyTimes(); replay(mockDeviceKeyService); WebTarget wt = target(); try { wt.path("keys/" + deviceKeyId1).request().get(String.class); fail("GET of a non-existent device key did not throw an exception"); } catch (NotFoundException ex) { assertThat(ex.getMessage(), containsString("HTTP 404 Not Found")); } verify(mockDeviceKeyService); } /** * Tests adding of new device key using POST via JSON stream. */ @Test public void testPost() { mockDeviceKeyAdminService.addKey(anyObject()); expectLastCall(); replay(mockDeviceKeyAdminService); WebTarget wt = target(); InputStream jsonStream = DeviceKeyWebResourceTest.class .getResourceAsStream("post-device-key.json"); Response response = wt.path("keys").request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(jsonStream)); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); String location = response.getLocation().getPath(); assertThat(location, Matchers.startsWith("/keys/" + deviceKeyId3)); verify(mockDeviceKeyAdminService); } /** * Tests adding of a null device key using POST via JSON stream. */ @Test public void testPostNullDeviceKey() { replay(mockDeviceKeyAdminService); WebTarget wt = target(); try { wt.path("keys").request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null device key did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockDeviceKeyAdminService); } /** * Tests removing a device key with DELETE request. */ @Test public void testDelete() { expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId2))) .andReturn(deviceKey2) .anyTimes(); mockDeviceKeyAdminService.removeKey(anyObject()); expectLastCall(); replay(mockDeviceKeyService); replay(mockDeviceKeyAdminService); WebTarget wt = target(); Response response = wt.path("keys/" + deviceKeyId2) .request(MediaType.APPLICATION_JSON_TYPE) .delete(); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK)); verify(mockDeviceKeyService); verify(mockDeviceKeyAdminService); } /** * Tests that a DELETE of a non-existent device key throws an exception. */ @Test public void testDeleteNonExistentDeviceKey() { expect(mockDeviceKeyService.getDeviceKey(anyObject())) .andReturn(null) .anyTimes(); expectLastCall(); replay(mockDeviceKeyService); replay(mockDeviceKeyAdminService); WebTarget wt = target(); try { wt.path("keys/" + "NON_EXISTENT_DEVICE_KEY").request() .delete(String.class); fail("Delete of a non-existent device key did not throw an exception"); } catch (NotFoundException ex) { assertThat(ex.getMessage(), containsString("HTTP 404 Not Found")); } verify(mockDeviceKeyService); verify(mockDeviceKeyAdminService); } }
package com.mageddo.commons; import java.util.Collections; import java.util.HashMap; import java.util.Map; public final class Maps { private Maps() { } public static <K, V> Map<K, V> of() { return Collections.unmodifiableMap(new HashMap<>()); } /** * Returns an unmodifiable map containing a single mapping. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the mapping's key * @param v1 the mapping's value * @return a {@code Map} containing the specified mapping * @throws NullPointerException if the key or the value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing two mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if the keys are duplicates * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing three mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing four mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing five mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing six mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); m.put(k6, v6); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing seven mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); m.put(k6, v6); m.put(k7, v7); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing eight mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @param k8 the eighth mapping's key * @param v8 the eighth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); m.put(k6, v6); m.put(k7, v7); m.put(k8, v8); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing nine mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @param k8 the eighth mapping's key * @param v8 the eighth mapping's value * @param k9 the ninth mapping's key * @param v9 the ninth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); m.put(k6, v6); m.put(k7, v7); m.put(k8, v8); m.put(k9, v9); return Collections.unmodifiableMap(m); } /** * Returns an unmodifiable map containing ten mappings. * See <a href="#unmodifiable">Unmodifiable Maps</a> for details. * * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @param k1 the first mapping's key * @param v1 the first mapping's value * @param k2 the second mapping's key * @param v2 the second mapping's value * @param k3 the third mapping's key * @param v3 the third mapping's value * @param k4 the fourth mapping's key * @param v4 the fourth mapping's value * @param k5 the fifth mapping's key * @param v5 the fifth mapping's value * @param k6 the sixth mapping's key * @param v6 the sixth mapping's value * @param k7 the seventh mapping's key * @param v7 the seventh mapping's value * @param k8 the eighth mapping's key * @param v8 the eighth mapping's value * @param k9 the ninth mapping's key * @param v9 the ninth mapping's value * @param k10 the tenth mapping's key * @param v10 the tenth mapping's value * @return a {@code Map} containing the specified mappings * @throws IllegalArgumentException if there are any duplicate keys * @throws NullPointerException if any key or value is {@code null} * @since 9 */ public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { final Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); m.put(k6, v6); m.put(k7, v7); m.put(k8, v8); m.put(k9, v9); m.put(k10, v10); return Collections.unmodifiableMap(m); } }
package org.mindtrails.persistence; import org.mindtrails.Application; import org.mindtrails.MockClasses.TestStudy; import org.mindtrails.domain.Study; import org.mindtrails.domain.tango.Item; import org.mindtrails.domain.tracking.EmailLog; import org.mindtrails.domain.tracking.GiftLog; import org.mindtrails.domain.Participant; import org.mindtrails.domain.PasswordToken; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.security.crypto.password.StandardPasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; /** * Created with IntelliJ IDEA. * User: dan * Date: 3/18/14 * Time: 6:58 AM * Assure that Participants are correctly stored and retrieved from the database. */ @Transactional @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) public class ParticipantRepositoryTest { @Autowired protected ParticipantRepository participantRepository; @Test public void testPasswordIsEncryptedWhenStored() { Participant p; String password = "Abcdefg1#"; StandardPasswordEncoder encoder = new StandardPasswordEncoder(); p = new Participant("Dan Funk", "[email protected]", false); p.updatePassword(password); Assert.assertNotNull(p.getPassword()); Assert.assertNotSame(password, p.getPassword()); Assert.assertTrue(encoder.matches(password, p.getPassword())); // If the password isn't set, it doesn't overwrite the DAO. p.updatePassword(null); Assert.assertNotNull(p.getPassword()); Assert.assertNotSame(password, p.getPassword()); Assert.assertTrue(encoder.matches(password, p.getPassword())); } @Test public void testDateCreatedIsSetOnCreation() { Participant p; p = new Participant("Dan Funk", "[email protected]", false); Assert.assertNotNull(p.getDateCreated()); } @Test @Transactional public void savedEmailLogSurfacesInReturnedParticipant() { Participant participant; EmailLog log; EmailLog log2; // Create a participant participant = new Participant("John", "[email protected]", false); participant.setStudy(new TestStudy()); log = new EmailLog(participant, "day2"); participant.addEmailLog(log); participantRepository.save(participant); participantRepository.flush(); // Participant should have an id now that it is saved. Assert.assertNotNull(participant.getId()); // Verify that the log message is returned, when loading that participant back up. participant = participantRepository.findOne(participant.getId()); Assert.assertNotNull(participant); Assert.assertNotNull(participant.getEmailLogs()); Assert.assertEquals(1, participant.getEmailLogs().size()); log = participant.getEmailLogs().iterator().next(); Assert.assertEquals("day2", log.getEmailType()); Assert.assertNotNull(log.getDateSent()); } @Test @Transactional public void giftLogSurfacesInReturnedParticipant() { Participant participant; GiftLog logDao; GiftLog log; participant = new Participant("Dan", "[email protected]", false); Item item = new Item(); item.setCurrencyCode("USD"); item.setUtid("XXX111222"); logDao = new GiftLog(participant, "SESSION1", 5, 5, item); logDao.setOrderId("code123"); logDao.setDateSent(new Date()); participant.addGiftLog(logDao); participantRepository.save(participant); participantRepository.flush(); Assert.assertNotNull(participant.getId()); Assert.assertNotNull(participant); Assert.assertNotNull(participant.getGiftLogs()); Assert.assertEquals(1, participant.getGiftLogs().size()); logDao = participant.getGiftLogs().iterator().next(); Assert.assertEquals("code123", logDao.getOrderId()); Assert.assertNotNull(logDao.getDateSent()); } @Test @Transactional public void testFindByToken() { Participant participant; Participant p, p2; PasswordToken token; String tokenString = "abcfedf"; // Create a participant participant = new Participant("John", "[email protected]", false); // Create a token DAO object token = new PasswordToken(participant, new Date(), tokenString); // Connect the two and save. participant.setPasswordToken(token); participantRepository.save(participant); participantRepository.flush(); // Find the participant by the token. participant = participantRepository.findByToken(tokenString); Assert.assertNotNull(participant); Assert.assertEquals(tokenString, participant.getPasswordToken().getToken()); Assert.assertEquals("[email protected]", participant.getEmail()); } @Test @Transactional public void testFindByCondition() { Participant p, p2, p3; TestStudy s, s2, s3; // Create a few participants p = new Participant("John", "[email protected]", false); s = new TestStudy(); s.setConditioning("unassigned"); p.setStudy(s); // Create a few participants p2 = new Participant("James", "[email protected]", false); s2 = new TestStudy(); s2.setConditioning("control"); p2.setStudy(s2); // Create a few participants p3 = new Participant("Mark", "[email protected]", false); s3 = new TestStudy(); s3.setConditioning("unassigned"); p3.setStudy(s3); participantRepository.save(p); participantRepository.save(p2); participantRepository.save(p3); participantRepository.flush(); // Find the participant by the token. List<Participant> all = participantRepository.findAllByCondition("unassigned"); Assert.assertNotNull(all); Assert.assertEquals(2, all.size()); Assert.assertEquals("unassigned", all.get(0).getStudy().getConditioning()); Assert.assertEquals("unassigned", all.get(1).getStudy().getConditioning()); } @Test @Transactional public void testFindCoachesAndCoachees() { // Create a participant Participant coach = new Participant("John", "[email protected]", false); coach.setCoaching(true); Participant p1 = new Participant("Paul", "[email protected]", false); Participant p2 = new Participant("George", "[email protected]", false); Participant p3 = new Participant("Ringo", "[email protected]", false); coach.setCoaching(true); p1.setCoachedBy(coach); p2.setCoachedBy(coach); participantRepository.save(coach); participantRepository.save(p1); participantRepository.save(p2); participantRepository.save(p3); PageRequest pageRequest = new PageRequest(0, 20); Page<Participant> coachees = participantRepository.findByCoachedBy(coach, pageRequest); List<Participant> coaches = participantRepository.findCoaches(); Assert.assertEquals("John doesn't coach Ringo", 2, coachees.getTotalElements()); Assert.assertEquals("John is the only coach", 1, coaches.size()); } @Test @Transactional public void listParticipantsEligible() { Study s1 = new TestStudy("SessionOne", 0, "COACH"); Study s2 = new TestStudy("SessionOne", 0, "NO_COACH"); Study s3 = new TestStudy("SessionOne", 0, "TRAINING"); Study s4 = new TestStudy("SessionOne", 0, "CONTROL"); Study s5 = new TestStudy("SessionOne", 0, "COACH"); Study s6 = new TestStudy("SessionOne", 0, "COACH"); Participant p1 = new Participant("Paul", "[email protected]", false); Participant p2 = new Participant("George", "[email protected]", false); Participant p3 = new Participant("Ringo", "[email protected]", false); Participant p4 = new Participant("John", "[email protected]", false); Participant p5 = new Participant("Scott", "[email protected]", false); Participant p6 = new Participant("Francis", "[email protected]", false); p1.setStudy(s1); p2.setStudy(s2); p3.setStudy(s3); p4.setStudy(s4); p5.setStudy(s5); p6.setStudy(s6); p1.setAttritionRisk(.5f); p2.setAttritionRisk(.2f); p3.setAttritionRisk(.7f); p5.setCoaching(true); p6.setTestAccount(true); participantRepository.save(p1); participantRepository.save(p2); participantRepository.save(p3); participantRepository.save(p4); participantRepository.save(p5); participantRepository.save(p6); PageRequest pageRequest = new PageRequest(0, 20); Page<Participant> coachees = participantRepository.findEligibleForCoaching("COACH", pageRequest); // Should be two, because three are three participants in the COACH condition, all have no coach assigned, but // one of them is a test account. Assert.assertEquals(2, coachees.getTotalElements() ); } }
/* * Title: GridSim Toolkit * Description: GridSim (Grid Simulation) Toolkit for Modeling and Simulation * of Parallel and Distributed Systems such as Clusters and Grids * License: GPL - http://www.gnu.org/copyleft/gpl.html * Copyright (c) 2006, The University of Melbourne, Australia and * University of Ljubljana, Slovenia */ package gridsim.datagrid.index; import eduni.simjava.*; import gridsim.*; import gridsim.datagrid.*; import gridsim.net.*; /** * An abstract class for the functionality of a Replica Catalogue (RC) entity. * The RC entity is a core component of every Data Grid system. The * function of a RC is to store the information (metadata) about files and to * provide mapping between a filename and its physical location(s). * <br> * The RC does not have to be a single entity in a Data Grid system. * It can also be composed of several distributed components, which, by * switching the information among them, provide a transparent service to * the users and resources. * <br> * Currently, GridSim allows two possible catalogue models: * <ul> * <li> Centralized Model. <br> * There is only one RC component in a Data Grid system that handles all * registrations and queries sent by resources and users. * Hence, the RC maps a filename to a list of resources that stores this file. * <br><br> * <li> Hierarchical Model. <br> * The hierarchical RC model is constructed as a catalogue tree. * In this model, some information are stored in the root of the catalogue * tree, and the rest in the leaves. * </ul> * <br> * Common functionalities of a RC is encapsulated in this class, an * abstract parent class for both {@link gridsim.datagrid.index.TopRegionalRC} * and {@link gridsim.datagrid.index.RegionalRC}. * The {@link gridsim.datagrid.index.TopRegionalRC} class acts as a * centralized RC or a root RC in a hierarchical model. In constrast, the * {@link gridsim.datagrid.index.RegionalRC} class represents a local RC * and/or a leaf RC in a hierarchical model. * Therefore, creating a new RC model can be done by extending this * class and implementing the abstract methods. * * @author Uros Cibej and Anthony Sulistio * @since GridSim Toolkit 4.0 */ public abstract class AbstractRC extends GridSimCore { /** A flag that denotes whether this entity is located inside a resource * or not */ protected boolean localRC_; // local RC or not /** A resource ID that hosts this RC entity (if applicable) */ protected int resourceID_; // resource ID that hosts this RC private int gisID_; // GIS entity ID /** * Creates a new <b>local</b> Replica Catalogue (RC) entity. * This constructor should be used if you want this RC entity to be inside * a resource's domain, hence known as <i>a Local RC</i>. * As a consequence, this entity uses the resource ID and I/O port for * identification. * <br> * The Local RC is responsible for indexing available files on the * resource only. It also handles users' queries. * However, the Local RC does not serve as a catalogue * server to other resources. This should be done by a leaf or regional RC. * * @param name this entity name * @param resourceID resource ID that hosts this RC entity * @param outputPort resource's output port * @throws Exception This happens when one of the input parameters is * invalid. */ protected AbstractRC(String name, int resourceID, Sim_port outputPort) throws Exception { super(name); if (resourceID == -1 || outputPort == null) { throw new Exception("AbstractRC(): Error - invalid parameter."); } resourceID_ = resourceID; localRC_ = true; super.output = outputPort; init(); } /** * Creates a new Replica Catalogue (RC) entity. * @param name this entity name * @param link the link that this GridSim entity will use to * communicate with other GridSim or Network entities. * @throws Exception This happens when one of the input parameters is * invalid. */ protected AbstractRC(String name, Link link) throws Exception { super(name, link); resourceID_ = -1; localRC_ = false; init(); } /** * Sets a regional GIS name for this entity to communicate with * @param name a regional GIS name * @return <tt>true</tt> if successful, <tt>false</tt> otherwise */ public boolean setRegionalGIS(String name) { if (name == null || name.length() == 0) { return false; } int id = GridSim.getEntityId(name); if (id == -1) { return false; } gisID_ = id; return true; } /** * Handles incoming requests to this entity, <b>DO NOT OVERRIDE</b> this * method. Implement the {@link #processOtherEvent(Sim_event)} instead. */ public void body() { // if it is a local RC, then use its resource entity ID int id = -1; if (localRC_) { id = resourceID_; } // otherwise, use my entity ID else { id = super.get_id(); } // register to central/main GIS if no regional GIS exists if (gisID_ == -1) { gisID_ = GridSim.getGridInfoServiceEntityId(); } // need to wait for few seconds before registering to a regional GIS. // This is because to allow all routers to fill in their routing tables else { String name = GridSim.getEntityName(gisID_); super.sim_pause(GridSim.PAUSE); System.out.println(super.get_name() + ".body(): wait for " + GridSim.PAUSE + " seconds before registering to " + name); } // register to a GIS entity first int register = DataGridTags.REGISTER_REPLICA_CTLG; super.send(super.output, GridSimTags.SCHEDULE_NOW, register, new IO_data(new Integer(id), DataGridTags.PKT_SIZE, gisID_)); // Below method is for a child class to override registerOtherEntity(); // Process events until END_OF_SIMULATION is received from the // GridSimShutdown Entity Sim_event ev = new Sim_event(); while (Sim_system.running()) { super.sim_get_next(ev); // if the simulation finishes then exit the loop if (ev.get_tag() == GridSimTags.END_OF_SIMULATION) { processEndSimulation(); break; } // process the received event processEvent(ev); } // remove I/O entities created during construction of this entity super.terminateIOEntities(); } /** * Processes an incoming request that uses a user-defined tag. This method * is useful for creating a new RC entity. * @param ev a Sim_event object (or an incoming event or request) * @return <tt>true</tt> if successful, <tt>false</tt> otherwise */ protected abstract boolean processOtherEvent(Sim_event ev); /** * Registers other information to a GIS entity. */ protected abstract void registerOtherEntity(); /** * Performs last activities before the end of a simulation. */ protected abstract void processEndSimulation(); /** * Register a file which is already stored in a resource <b>before</b> the * start of simulation * @param fAttr a file attribute object * @param id the owner ID of this file * @return <tt>true</tt> if successful, <tt>false</tt> otherwise */ public abstract boolean registerOriginalFile(FileAttribute fAttr, int id); /** * Initializes any local variables */ private void init() { gisID_ = -1; } /** * Processes incoming events one by one * @param ev a Sim_event object * @return <tt>true</tt> if successful, <tt>false</tt> if a tag is unknown */ public boolean processEvent(Sim_event ev) { boolean result = false; switch (ev.get_tag()) { // Ping packet case GridSimTags.INFOPKT_SUBMIT: processPingRequest(ev); result = true; break; default: result = processOtherEvent(ev); break; } return result; } /** * Processes a ping request. * @param ev a Sim_event object */ private void processPingRequest(Sim_event ev) { InfoPacket pkt = (InfoPacket) ev.get_data(); pkt.setTag(GridSimTags.INFOPKT_RETURN); pkt.setDestID(pkt.getSrcID()); // sends back to the sender super.send(super.output, GridSimTags.SCHEDULE_NOW, GridSimTags.INFOPKT_RETURN, new IO_data(pkt, pkt.getSize(), pkt.getSrcID())); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.tempuri; import java.math.BigDecimal; import java.math.BigInteger; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.datatype.Duration; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import org.datacontract.schemas._2004._07.system.DateTimeOffset; @WebService(name = "IBaseDataTypesDocLitB", targetNamespace = "http://tempuri.org/") @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) public interface IBaseDataTypesDocLitB { /** * * @param inBool * @return * returns boolean */ @WebMethod(operationName = "RetBool", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetBool") @WebResult(name = "RetBoolResult", targetNamespace = "http://tempuri.org/", partName = "RetBoolResult") public boolean retBool( @WebParam(name = "inBool", targetNamespace = "http://tempuri.org/", partName = "inBool") boolean inBool); /** * * @param inByte * @return * returns short */ @WebMethod(operationName = "RetByte", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetByte") @WebResult(name = "RetByteResult", targetNamespace = "http://tempuri.org/", partName = "RetByteResult") public short retByte( @WebParam(name = "inByte", targetNamespace = "http://tempuri.org/", partName = "inByte") short inByte); /** * * @param inSByte * @return * returns byte */ @WebMethod(operationName = "RetSByte", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetSByte") @WebResult(name = "RetSByteResult", targetNamespace = "http://tempuri.org/", partName = "RetSByteResult") public byte retSByte( @WebParam(name = "inSByte", targetNamespace = "http://tempuri.org/", partName = "inSByte") byte inSByte); /** * * @param inByteArray * @return * returns byte[] */ @WebMethod(operationName = "RetByteArray", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetByteArray") @WebResult(name = "RetByteArrayResult", targetNamespace = "http://tempuri.org/", partName = "RetByteArrayResult") public byte[] retByteArray( @WebParam(name = "inByteArray", targetNamespace = "http://tempuri.org/", partName = "inByteArray") byte[] inByteArray); /** * * @param inChar * @return * returns int */ @WebMethod(operationName = "RetChar", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetChar") @WebResult(name = "RetCharResult", targetNamespace = "http://tempuri.org/", partName = "RetCharResult") public int retChar( @WebParam(name = "inChar", targetNamespace = "http://tempuri.org/", partName = "inChar") int inChar); /** * * @param inDecimal * @return * returns java.math.BigDecimal */ @WebMethod(operationName = "RetDecimal", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetDecimal") @WebResult(name = "RetDecimalResult", targetNamespace = "http://tempuri.org/", partName = "RetDecimalResult") public BigDecimal retDecimal( @WebParam(name = "inDecimal", targetNamespace = "http://tempuri.org/", partName = "inDecimal") BigDecimal inDecimal); /** * * @param inFloat * @return * returns float */ @WebMethod(operationName = "RetFloat", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetFloat") @WebResult(name = "RetFloatResult", targetNamespace = "http://tempuri.org/", partName = "RetFloatResult") public float retFloat( @WebParam(name = "inFloat", targetNamespace = "http://tempuri.org/", partName = "inFloat") float inFloat); /** * * @param inDouble * @return * returns double */ @WebMethod(operationName = "RetDouble", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetDouble") @WebResult(name = "RetDoubleResult", targetNamespace = "http://tempuri.org/", partName = "RetDoubleResult") public double retDouble( @WebParam(name = "inDouble", targetNamespace = "http://tempuri.org/", partName = "inDouble") double inDouble); /** * * @param inSingle * @return * returns float */ @WebMethod(operationName = "RetSingle", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetSingle") @WebResult(name = "RetSingleResult", targetNamespace = "http://tempuri.org/", partName = "RetSingleResult") public float retSingle( @WebParam(name = "inSingle", targetNamespace = "http://tempuri.org/", partName = "inSingle") float inSingle); /** * * @param inInt * @return * returns int */ @WebMethod(operationName = "RetInt", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetInt") @WebResult(name = "RetIntResult", targetNamespace = "http://tempuri.org/", partName = "RetIntResult") public int retInt( @WebParam(name = "inInt", targetNamespace = "http://tempuri.org/", partName = "inInt") int inInt); /** * * @param inShort * @return * returns short */ @WebMethod(operationName = "RetShort", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetShort") @WebResult(name = "RetShortResult", targetNamespace = "http://tempuri.org/", partName = "RetShortResult") public short retShort( @WebParam(name = "inShort", targetNamespace = "http://tempuri.org/", partName = "inShort") short inShort); /** * * @param inLong * @return * returns long */ @WebMethod(operationName = "RetLong", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetLong") @WebResult(name = "RetLongResult", targetNamespace = "http://tempuri.org/", partName = "RetLongResult") public long retLong( @WebParam(name = "inLong", targetNamespace = "http://tempuri.org/", partName = "inLong") long inLong); /** * * @param inObject * @return * returns java.lang.Object */ @WebMethod(operationName = "RetObject", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetObject") @WebResult(name = "RetObjectResult", targetNamespace = "http://tempuri.org/", partName = "RetObjectResult") public Object retObject( @WebParam(name = "inObject", targetNamespace = "http://tempuri.org/", partName = "inObject") Object inObject); /** * * @param inUInt * @return * returns long */ @WebMethod(operationName = "RetUInt", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetUInt") @WebResult(name = "RetUIntResult", targetNamespace = "http://tempuri.org/", partName = "RetUIntResult") public long retUInt( @WebParam(name = "inUInt", targetNamespace = "http://tempuri.org/", partName = "inUInt") long inUInt); /** * * @param inUShort * @return * returns int */ @WebMethod(operationName = "RetUShort", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetUShort") @WebResult(name = "RetUShortResult", targetNamespace = "http://tempuri.org/", partName = "RetUShortResult") public int retUShort( @WebParam(name = "inUShort", targetNamespace = "http://tempuri.org/", partName = "inUShort") int inUShort); /** * * @param inULong * @return * returns java.math.BigInteger */ @WebMethod(operationName = "RetULong", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetULong") @WebResult(name = "RetULongResult", targetNamespace = "http://tempuri.org/", partName = "RetULongResult") public BigInteger retULong( @WebParam(name = "inULong", targetNamespace = "http://tempuri.org/", partName = "inULong") BigInteger inULong); /** * * @param inString * @return * returns java.lang.String */ @WebMethod(operationName = "RetString", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetString") @WebResult(name = "RetStringResult", targetNamespace = "http://tempuri.org/", partName = "RetStringResult") public String retString( @WebParam(name = "inString", targetNamespace = "http://tempuri.org/", partName = "inString") String inString); /** * * @param inGuid * @return * returns java.lang.String */ @WebMethod(operationName = "RetGuid", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetGuid") @WebResult(name = "RetGuidResult", targetNamespace = "http://tempuri.org/", partName = "RetGuidResult") public String retGuid( @WebParam(name = "inGuid", targetNamespace = "http://tempuri.org/", partName = "inGuid") String inGuid); /** * * @param inUri * @return * returns java.lang.String */ @WebMethod(operationName = "RetUri", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetUri") @WebResult(name = "RetUriResult", targetNamespace = "http://tempuri.org/", partName = "RetUriResult") public String retUri( @WebParam(name = "inUri", targetNamespace = "http://tempuri.org/", partName = "inUri") String inUri); /** * * @param inDateTime * @return * returns javax.xml.datatype.XMLGregorianCalendar */ @WebMethod(operationName = "RetDateTime", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetDateTime") @WebResult(name = "RetDateTimeResult", targetNamespace = "http://tempuri.org/", partName = "RetDateTimeResult") public XMLGregorianCalendar retDateTime( @WebParam(name = "inDateTime", targetNamespace = "http://tempuri.org/", partName = "inDateTime") XMLGregorianCalendar inDateTime); /** * * @param inDateTimeOffset * @return * returns org.datacontract.schemas._2004._07.system.DateTimeOffset */ @WebMethod(operationName = "RetDateTimeOffset", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetDateTimeOffset") @WebResult(name = "RetDateTimeOffsetResult", targetNamespace = "http://tempuri.org/", partName = "RetDateTimeOffsetResult") public DateTimeOffset retDateTimeOffset( @WebParam(name = "inDateTimeOffset", targetNamespace = "http://tempuri.org/", partName = "inDateTimeOffset") DateTimeOffset inDateTimeOffset); /** * * @param inTimeSpan * @return * returns javax.xml.datatype.Duration */ @WebMethod(operationName = "RetTimeSpan", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetTimeSpan") @WebResult(name = "RetTimeSpanResult", targetNamespace = "http://tempuri.org/", partName = "RetTimeSpanResult") public Duration retTimeSpan( @WebParam(name = "inTimeSpan", targetNamespace = "http://tempuri.org/", partName = "inTimeSpan") Duration inTimeSpan); /** * * @param inQName * @return * returns javax.xml.namespace.QName */ @WebMethod(operationName = "RetQName", action = "http://tempuri.org/IBaseDataTypesDocLitB/RetQName") @WebResult(name = "RetQNameResult", targetNamespace = "http://tempuri.org/", partName = "RetQNameResult") public QName retQName( @WebParam(name = "inQName", targetNamespace = "http://tempuri.org/", partName = "inQName") QName inQName); }
/* * Copyright 2019 Stephane Nicolas * Copyright 2019 Daniel Molinero Reguera * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package toothpick; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.fail; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.inject.Singleton; import org.junit.After; import org.junit.Test; import toothpick.data.CustomScope; import toothpick.data.NotAScope; public class ScopeNodeTest { @After public void tearDown() throws Exception { Toothpick.reset(); } @Test(expected = IllegalArgumentException.class) public void testCreateScope_shouldFail_whenNameIsNull() { // GIVEN // WHEN Scope scope = new ScopeImpl(null); // THEN assertThat(scope, is(scope)); } @Test public void testCreateScope_shouldBindToScopeAnnotation_whenNameIsAScopeAnnotation() { // GIVEN Scope scope = new ScopeImpl(CustomScope.class); // WHEN boolean isSupportingToScopeAnnotation = scope.isScopeAnnotationSupported(CustomScope.class); // THEN assertThat(isSupportingToScopeAnnotation, is(true)); } @Test public void testCreateScope_shouldNotBindToScopeAnnotation_whenNameIsNotAScopeAnnotation() { // GIVEN Scope scope = new ScopeImpl(NotAScope.class); // WHEN boolean isSupportingToScopeAnnotation = scope.isScopeAnnotationSupported(CustomScope.class); // THEN assertThat(isSupportingToScopeAnnotation, is(false)); } @Test public void testGetParentScope_shouldReturnRootScope_whenAskedForSingleton() { // GIVEN Scope parentScope = Toothpick.openScope("root"); Scope childScope = Toothpick.openScopes("root", "child"); // WHEN Scope scope = childScope.getParentScope(Singleton.class); // THEN assertThat(scope, is(parentScope)); } @Test public void testGetParentScope_shouldReturnItself_whenScopedToScopeAnnotation() { // GIVEN Scope childScope = Toothpick.openScopes("root", "child"); childScope.supportScopeAnnotation(CustomScope.class); // WHEN Scope scope = childScope.getParentScope(CustomScope.class); // THEN assertThat(scope, is(childScope)); } @Test public void testGetParentScope_shouldReturnParentScope_whenParentSupportsScopeAnnotation() { // GIVEN Scope parentScope = Toothpick.openScope("root"); parentScope.supportScopeAnnotation(CustomScope.class); Scope childScope = Toothpick.openScopes("root", "child"); // WHEN Scope scope = childScope.getParentScope(CustomScope.class); // THEN assertThat(scope, is(parentScope)); } @Test(expected = IllegalStateException.class) public void testGetParentScope_shouldFail_whenNoParentSupportsScopeAnnotation() { // GIVEN Scope scope = Toothpick.openScope("root"); // WHEN scope.getParentScope(CustomScope.class); // THEN fail("Should throw an exception"); } @Test(expected = IllegalArgumentException.class) public void testGetParentScope_shouldFail_WhenAnnotationIsNotAScope() { // GIVEN Scope scope = Toothpick.openScope("root"); // WHEN scope.getParentScope(NotAScope.class); // THEN fail("Should throw an exception"); } @Test public void testGetRootScope_shouldReturnNodeItselfI_whenRoot() { // GIVEN Scope parentScope = Toothpick.openScope("root"); // WHEN Scope scope = parentScope.getRootScope(); // THEN assertThat(scope, is(parentScope)); } @Test public void testGetRootScope_shouldReturnRootScope_whenHasParent() { // GIVEN Scope parentScope = Toothpick.openScope("root"); Scope childScope = Toothpick.openScopes("root", "child"); // WHEN Scope scope = childScope.getRootScope(); // THEN assertThat(scope, is(parentScope)); } @Test(expected = IllegalArgumentException.class) public void testBindScopeAnnotation_shouldFail_whenSingleton() { // GIVEN Scope scope = Toothpick.openScope("root"); // WHEN scope.supportScopeAnnotation(Singleton.class); // THEN fail("Should throw an exception"); } @Test(expected = IllegalArgumentException.class) public void testBindScopeAnnotation_shouldFail_whenAnnotationIsNotAScope() { // GIVEN Scope scope = Toothpick.openScope("root"); // WHEN scope.supportScopeAnnotation(NotAScope.class); // THEN fail("Should throw an exception"); } @Test public void testSupportScopeAnnotation_shouldReturnFalse_whenNotSupported() { // GIVEN Scope scope = Toothpick.openScope("root"); // WHEN boolean isSupportingToScopeAnnotation = scope.isScopeAnnotationSupported(CustomScope.class); // THEN assertThat(isSupportingToScopeAnnotation, is(false)); } @Test public void testSupportScopeAnnotation_shouldReturnTrue_whenSupported() { // GIVEN Scope parentScope = Toothpick.openScope("root"); parentScope.supportScopeAnnotation(CustomScope.class); // WHEN boolean isSupportingToScopeAnnotation = parentScope.isScopeAnnotationSupported(CustomScope.class); // THEN assertThat(isSupportingToScopeAnnotation, is(true)); } @Test public void testSupportScopeAnnotation_shouldReturnTrue_whenRootScopeAskedForSingleton() { // GIVEN Scope parentScope = Toothpick.openScope("root"); // WHEN boolean isSupportingSingleton = parentScope.isScopeAnnotationSupported(Singleton.class); // THEN assertThat(isSupportingSingleton, is(true)); } @Test public void testSupportScopeAnnotation_shouldReturnFalse_whenNonRootScopeAskedForSingleton() { // GIVEN Scope childScope = Toothpick.openScopes("root", "child"); // WHEN boolean isSupportingSingleton = childScope.isScopeAnnotationSupported(Singleton.class); // THEN assertThat(isSupportingSingleton, is(false)); } @Test public void testGetChildrenScopes_shouldReturnEmptyList_whenHasNoChildren() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); // WHEN boolean hasNoChildren = parentScope.getChildrenScopes().isEmpty(); // THEN assertThat(hasNoChildren, is(true)); } @Test public void testGetChildrenScopes_shouldReturnChildren_whenHasChildren() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode childScope = new ScopeImpl("child"); parentScope.addChild(childScope); // WHEN Collection<ScopeNode> childrenScopes = parentScope.getChildrenScopes(); // THEN assertThat(childrenScopes.isEmpty(), is(false)); assertThat(childrenScopes.size(), is(1)); assertThat(childrenScopes.iterator().next(), is(childScope)); } @Test(expected = IllegalArgumentException.class) public void testAddChild_shouldFail_whenChildIsNull() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); // WHEN parentScope.addChild(null); // THEN fail("Should throw an exception"); } @Test public void testAddChild_shouldReturnChild() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode childScope = new ScopeImpl("child"); parentScope.addChild(childScope); // WHEN ScopeNode child = parentScope.addChild(childScope); // THEN assertThat(child, is(childScope)); } @Test(expected = IllegalStateException.class) public void testAddChild_shouldFail_whenChildAlreadyHasParent() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode parentScope2 = new ScopeImpl("foo"); ScopeNode childScope = new ScopeImpl("child"); parentScope.addChild(childScope); // WHEN parentScope2.addChild(childScope); // THEN fail("Should throw an exception"); } @Test(expected = IllegalArgumentException.class) public void testRemoveChild_shouldFail_whenChildIsNull() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); // WHEN parentScope.removeChild(null); // THEN fail("Should throw an exception"); } @Test(expected = IllegalStateException.class) public void testRemoveChild_shouldFail_whenChildHasNoParent() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode childScope = new ScopeImpl("child"); // WHEN parentScope.removeChild(childScope); // THEN fail("Should throw an exception"); } @Test(expected = IllegalStateException.class) public void testRemoveChild_shouldFail_whenChildHasDifferentParent() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode parentScope2 = new ScopeImpl("foo"); ScopeNode childScope = new ScopeImpl("child"); parentScope.addChild(childScope); // WHEN parentScope2.removeChild(childScope); // THEN fail("Should throw an exception"); } @Test public void testRemoveChild() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode childScope = new ScopeImpl("child"); parentScope.addChild(childScope); // WHEN parentScope.removeChild(childScope); // WHEN Collection<ScopeNode> childrenScopes = parentScope.getChildrenScopes(); // THEN assertThat(childrenScopes.isEmpty(), is(true)); } @Test public void testEqualsAndHashCode_shouldReturnTrue_whenNodeHasSameName() { // GIVEN Scope scope = new ScopeImpl("foo"); Scope scope2 = new ScopeImpl("foo"); // WHEN boolean equals = scope.equals(scope2); boolean equals2 = scope2.equals(scope); int hashScope = scope.hashCode(); int hashScope2 = scope2.hashCode(); // THEN assertThat(equals, is(true)); assertThat(equals2, is(true)); assertThat(hashScope, is(hashScope2)); } @Test public void testEqualsAndHashCode_shouldReturnFalse_whenNodeHasDifferentName() { // GIVEN Scope scope = new ScopeImpl("foo"); Scope scope2 = new ScopeImpl("bar"); // WHEN boolean equals = scope.equals(scope2); int hashScope = scope.hashCode(); int hashScope2 = scope2.hashCode(); // THEN assertThat(equals, is(false)); assertThat(hashScope, not(is(hashScope2))); } @Test public void testGetParentScopeNames_shouldReturnParentNames_whenThereAreParents() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode childScope = new ScopeImpl("child"); parentScope.addChild(childScope); // WHEN final List<Object> parentScopesNames = childScope.getParentScopesNames(); // THEN assertThat(parentScopesNames.size(), is(1)); assertThat(parentScopesNames.iterator().next(), is(parentScope.getName())); } @Test public void testGetParentScopeNames_shouldReturnParentNamesInOrder_whenThereAreParents() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); ScopeNode childScope = new ScopeImpl("child"); ScopeNode grandChildScope = new ScopeImpl("grandChild"); parentScope.addChild(childScope); childScope.addChild(grandChildScope); // WHEN final List<Object> grandParentScopesNames = grandChildScope.getParentScopesNames(); // THEN assertThat(grandParentScopesNames.size(), is(2)); final Iterator<Object> iterator = grandParentScopesNames.iterator(); assertThat(iterator.next(), is(childScope.getName())); assertThat(iterator.next(), is(parentScope.getName())); } @Test public void testGetParentScopeNames_shouldReturnParentNames_whenThereAreNoParents() { // GIVEN ScopeNode parentScope = new ScopeImpl("root"); // WHEN final List<Object> parentScopesNames = parentScope.getParentScopesNames(); // THEN assertThat(parentScopesNames.size(), is(0)); } @Test public void testReset_shouldClearSupportedAnnotations_andFlagTheScopeAsOpen() throws Exception { // GIVEN ScopeNode scope = new ScopeImpl("root"); scope.supportScopeAnnotation(CustomScope.class); scope.close(); // WHEN scope.reset(); // THEN assertThat(scope.isScopeAnnotationSupported(CustomScope.class), is(false)); assertThat(scope.isOpen, is(true)); } @Test public void testReset_shouldRebindScopeAnnotation() throws Exception { // GIVEN ScopeNode scope = new ScopeImpl(CustomScope.class); // WHEN scope.reset(); // THEN assertThat(scope.isScopeAnnotationSupported(CustomScope.class), is(true)); } }
/* Copyright (c) 2017 FA Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import de.uniks.networkparser.IdMap; import de.uniks.networkparser.interfaces.SendableEntityCreator; public class BankCreator implements SendableEntityCreator { private final String[] properties = new String[] { Bank.PROPERTY_FEE, Bank.PROPERTY_BANKNAME, Bank.PROPERTY_CUSTOMERUSER, Bank.PROPERTY_TRANSACTION, Bank.PROPERTY_CUSTOMERACCOUNTS, Bank.PROPERTY_ADMINUSERS, Bank.PROPERTY_ADMINACCOUNTS, Bank.PROPERTY_FEEVALUE, Bank.PROPERTY_PASSWORDCODE, }; @Override public String[] getProperties() { return properties; } @Override public Object getSendableInstance(boolean reference) { return new Bank(); } @Override public Object getValue(Object target, String attrName) { int pos = attrName.indexOf('.'); String attribute = attrName; if (pos > 0) { attribute = attrName.substring(0, pos); } if (Bank.PROPERTY_FEE.equalsIgnoreCase(attribute)) { return ((Bank) target).getFee(); } if (Bank.PROPERTY_BANKNAME.equalsIgnoreCase(attribute)) { return ((Bank) target).getBankName(); } if (Bank.PROPERTY_CUSTOMERUSER.equalsIgnoreCase(attribute)) { return ((Bank) target).getCustomerUser(); } if (Bank.PROPERTY_TRANSACTION.equalsIgnoreCase(attribute)) { return ((Bank) target).getTransaction(); } if (Bank.PROPERTY_CUSTOMERACCOUNTS.equalsIgnoreCase(attribute)) { return ((Bank) target).getCustomerAccounts(); } if (Bank.PROPERTY_ADMINUSERS.equalsIgnoreCase(attribute)) { return ((Bank) target).getAdminUsers(); } if (Bank.PROPERTY_ADMINACCOUNTS.equalsIgnoreCase(attribute)) { return ((Bank) target).getAdminAccounts(); } if (Bank.PROPERTY_FEEVALUE.equalsIgnoreCase(attribute)) { return ((Bank) target).getFeeValue(); } // if (Bank.PROPERTY_PASSWORDCODE.equalsIgnoreCase(attribute)) // { // return ((Bank) target).getPasswordCode(); // } return null; } @Override public boolean setValue(Object target, String attrName, Object value, String type) { // if (Bank.PROPERTY_PASSWORDCODE.equalsIgnoreCase(attrName)) // { // ((Bank) target).setPasswordCode((String) value); // return true; // } if (Bank.PROPERTY_BANKNAME.equalsIgnoreCase(attrName)) { ((Bank) target).setBankName((String) value); return true; } if (Bank.PROPERTY_FEE.equalsIgnoreCase(attrName)) { ((Bank) target).setFee(Double.parseDouble(value.toString())); return true; } if (SendableEntityCreator.REMOVE.equals(type) && value != null) { attrName = attrName + type; } if (Bank.PROPERTY_CUSTOMERUSER.equalsIgnoreCase(attrName)) { ((Bank) target).withCustomerUser((User) value); return true; } if ((Bank.PROPERTY_CUSTOMERUSER + SendableEntityCreator.REMOVE).equalsIgnoreCase(attrName)) { ((Bank) target).withoutCustomerUser((User) value); return true; } if (Bank.PROPERTY_TRANSACTION.equalsIgnoreCase(attrName)) { ((Bank) target).setTransaction((Transaction) value); return true; } if (Bank.PROPERTY_CUSTOMERACCOUNTS.equalsIgnoreCase(attrName)) { ((Bank) target).withCustomerAccounts((Account) value); return true; } if ((Bank.PROPERTY_CUSTOMERACCOUNTS + SendableEntityCreator.REMOVE).equalsIgnoreCase(attrName)) { ((Bank) target).withoutCustomerAccounts((Account) value); return true; } if (Bank.PROPERTY_ADMINUSERS.equalsIgnoreCase(attrName)) { ((Bank) target).withAdminUsers((User) value); return true; } if ((Bank.PROPERTY_ADMINUSERS + SendableEntityCreator.REMOVE).equalsIgnoreCase(attrName)) { ((Bank) target).withoutAdminUsers((User) value); return true; } if (Bank.PROPERTY_ADMINACCOUNTS.equalsIgnoreCase(attrName)) { ((Bank) target).withAdminAccounts((Account) value); return true; } if ((Bank.PROPERTY_ADMINACCOUNTS + SendableEntityCreator.REMOVE).equalsIgnoreCase(attrName)) { ((Bank) target).withoutAdminAccounts((Account) value); return true; } if (Bank.PROPERTY_FEEVALUE.equalsIgnoreCase(attrName)) { ((Bank) target).withFeeValue((FeeValue) value); return true; } if ((Bank.PROPERTY_FEEVALUE + SendableEntityCreator.REMOVE).equalsIgnoreCase(attrName)) { ((Bank) target).withoutFeeValue((FeeValue) value); return true; } return false; } public static IdMap createIdMap(String sessionID) { return CreatorCreator.createIdMap(sessionID); } //========================================================================== public void removeObject(Object entity) { ((Bank) entity).removeYou(); } }
package org.andengine.opengl.font; import java.util.List; import org.andengine.entity.text.AutoWrap; import org.andengine.util.TextUtils; import org.andengine.util.exception.MethodNotYetImplementedException; /** * (c) Zynga 2012 * * @author Nicolas Gramlich <[email protected]> * @since 15:06:32 - 25.01.2012 */ public class FontUtils { // =========================================================== // Constants // =========================================================== private static final int UNSPECIFIED = -1; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /** * @param pFont * @param pText * @return the width of pText. */ public static float measureText(final IFont pFont, final CharSequence pText) { return FontUtils.measureText(pFont, pText, null); } /** * @param pFont * @param pText * @param pStart the index of the first character to start measuring. * @param pEnd <code>1</code> beyond the index of the last character to measure. * @return the width of pText. */ public static float measureText(final IFont pFont, final CharSequence pText, final int pStart, final int pEnd) { return FontUtils.measureText(pFont, pText, pStart, pEnd, null); } /** * @param pFont * @param pText * @param pWidths (optional) If not <code>null</code>, returns the actual width measured. * @return the width of pText. */ public static float measureText(final IFont pFont, final CharSequence pText, final float[] pWidths) { return FontUtils.measureText(pFont, pText, 0, pText.length(), pWidths); } /** * Does not respect linebreaks! * * @param pFont * @param pText * @param pStart the index of the first character to start measuring. * @param pEnd <code>1</code> beyond the index of the last character to measure. * @param pWidths (optional) If not <code>null</code>, returns the actual width after each character. * @return the width of pText. */ public static float measureText(final IFont pFont, final CharSequence pText, final int pStart, final int pEnd, final float[] pWidths) { final int textLength = pEnd - pStart; /* Early exits. */ if(pStart == pEnd) { return 0; } else if(textLength == 1) { return pFont.getLetter(pText.charAt(pStart)).mWidth; } Letter previousLetter = null; float width = 0; for(int pos = pStart, i = 0; pos < pEnd; pos++, i++) { final Letter letter = pFont.getLetter(pText.charAt(pos)); if(previousLetter != null) { width += previousLetter.getKerning(letter.mCharacter); } previousLetter = letter; /* Check if this is the last character. */ if(pos == (pEnd - 1)) { width += letter.mOffsetX + letter.mWidth; } else { width += letter.mAdvance; } if(pWidths != null) { pWidths[i] = width; } } return width; } /** * Measure the text, stopping early if the measured width exceeds pMaximumWidth. * * @param pFont * @param pText * @param pMeasureDirection If {@link MeasureDirection#FORWARDS}, starts with the first character in the {@link CharSequence}. If {@link MeasureDirection#BACKWARDS} starts with the last character in the {@link CharSequence}. * @param pWidthMaximum * @param pMeasuredWidth (optional) If not <code>null</code>, returns the actual width measured. Must be an Array of size <code>1</code> or bigger. * @return the number of chars that were measured. */ public static int breakText(final IFont pFont, final CharSequence pText, final MeasureDirection pMeasureDirection, final float pWidthMaximum, final float[] pMeasuredWidth) { throw new MethodNotYetImplementedException(); } public static <L extends List<CharSequence>> L splitLines(final CharSequence pText, final L pResult) { return TextUtils.split(pText, '\n', pResult); } /** * Does not respect linebreaks! * * @param pFont * @param pText * @param pResult * @param pAutoWrapWidth * @return */ public static <L extends List<CharSequence>> L splitLines(final IFont pFont, final CharSequence pText, final L pResult, final AutoWrap pAutoWrap, final float pAutoWrapWidth) { /** * TODO In order to respect already existing linebreaks, {@link FontUtils#split(CharSequence, List)} could be leveraged and than the following methods could be called for each line. */ switch(pAutoWrap) { case LETTERS: return FontUtils.splitLinesByLetters(pFont, pText, pResult, pAutoWrapWidth); case WORDS: return FontUtils.splitLinesByWords(pFont, pText, pResult, pAutoWrapWidth); case CJK: return FontUtils.splitLinesByCJK(pFont, pText, pResult, pAutoWrapWidth); case NONE: default: throw new IllegalArgumentException("Unexpected " + AutoWrap.class.getSimpleName() + ": '" + pAutoWrap + "'."); } } private static <L extends List<CharSequence>> L splitLinesByLetters(final IFont pFont, final CharSequence pText, final L pResult, final float pAutoWrapWidth) { final int textLength = pText.length(); int lineStart = 0; int lineEnd = 0; int lastNonWhitespace = 0; boolean charsAvailable = false; for(int i = 0; i < textLength; i++) { final char character = pText.charAt(i); if(character != ' ') { if(charsAvailable) { lastNonWhitespace = i + 1; } else { charsAvailable = true; lineStart = i; lastNonWhitespace = lineStart + 1; lineEnd = lastNonWhitespace; } } if(charsAvailable) { // /* Just for debugging. */ // final CharSequence line = pText.subSequence(lineStart, lineEnd); // final float lineWidth = FontUtils.measureText(pFont, pText, lineStart, lineEnd); // // final CharSequence lookaheadLine = pText.subSequence(lineStart, lastNonWhitespace); final float lookaheadLineWidth = FontUtils.measureText(pFont, pText, lineStart, lastNonWhitespace); final boolean isEndReached = (i == (textLength - 1)); if(isEndReached) { /* When the end of the string is reached, add remainder to result. */ if(lookaheadLineWidth <= pAutoWrapWidth) { pResult.add(pText.subSequence(lineStart, lastNonWhitespace)); } else { pResult.add(pText.subSequence(lineStart, lineEnd)); /* Avoid special case where last line is added twice. */ if(lineStart != i) { pResult.add(pText.subSequence(i, lastNonWhitespace)); } } } else { if(lookaheadLineWidth <= pAutoWrapWidth) { lineEnd = lastNonWhitespace; } else { pResult.add(pText.subSequence(lineStart, lineEnd)); i = lineEnd - 1; charsAvailable = false; } } } } return pResult; } private static <L extends List<CharSequence>> L splitLinesByWords(final IFont pFont, final CharSequence pText, final L pResult, final float pAutoWrapWidth) { final int textLength = pText.length(); if(textLength == 0) { return pResult; } final float spaceWidth = pFont.getLetter(' ').mAdvance; int lastWordEnd = FontUtils.UNSPECIFIED; int lineStart = FontUtils.UNSPECIFIED; int lineEnd = FontUtils.UNSPECIFIED; float lineWidthRemaining = pAutoWrapWidth; boolean firstWordInLine = true; int i = 0; while(i < textLength) { int spacesSkipped = 0; /* Find next word. */ { /* Skip whitespaces. */ while((i < textLength) && (pText.charAt(i) == ' ')) { i++; spacesSkipped++; } } final int wordStart = i; /* Mark beginning of a new line. */ if(lineStart == FontUtils.UNSPECIFIED) { lineStart = wordStart; } { /* Skip non-whitespaces. */ while((i < textLength) && (pText.charAt(i) != ' ')) { i++; } } final int wordEnd = i; /* Nothing more could be read. */ if(wordStart == wordEnd) { if(!firstWordInLine) { pResult.add(pText.subSequence(lineStart, lineEnd)); } break; } // /* Just for debugging. */ // final CharSequence word = pText.subSequence(wordStart, wordEnd); final float wordWidth = FontUtils.measureText(pFont, pText, wordStart, wordEnd); /* Determine the width actually needed for the current word. */ final float widthNeeded; if(firstWordInLine) { widthNeeded = wordWidth; } else { widthNeeded = (spacesSkipped * spaceWidth) + wordWidth; } /* Check if the word fits into the rest of the line. */ if (widthNeeded <= lineWidthRemaining) { if(firstWordInLine) { firstWordInLine = false; } else { lineWidthRemaining -= FontUtils.getAdvanceCorrection(pFont, pText, lastWordEnd - 1); } lineWidthRemaining -= widthNeeded; lastWordEnd = wordEnd; lineEnd = wordEnd; /* Check if the end was reached. */ if(wordEnd == textLength) { pResult.add(pText.subSequence(lineStart, lineEnd)); /* Added the last line. */ break; } } else { /* Special case for lines with only one word. */ if(firstWordInLine) { /* Check for lines that are just too big. */ if(wordWidth >= pAutoWrapWidth) { pResult.add(pText.subSequence(wordStart, wordEnd)); lineWidthRemaining = pAutoWrapWidth; } else { lineWidthRemaining = pAutoWrapWidth - wordWidth; /* Check if the end was reached. */ if(wordEnd == textLength) { pResult.add(pText.subSequence(wordStart, wordEnd)); /* Added the last line. */ break; } } /* Start a completely new line. */ firstWordInLine = true; lastWordEnd = FontUtils.UNSPECIFIED; lineStart = FontUtils.UNSPECIFIED; lineEnd = FontUtils.UNSPECIFIED; } else { /* Finish the current line. */ pResult.add(pText.subSequence(lineStart, lineEnd)); /* Check if the end was reached. */ if(wordEnd == textLength) { /* Add the last word. */ pResult.add(pText.subSequence(wordStart, wordEnd)); // TODO Does this cover all cases? break; } else { /* Start a new line, carrying over the current word. */ lineWidthRemaining = pAutoWrapWidth - wordWidth; firstWordInLine = false; lastWordEnd = wordEnd; lineStart = wordStart; lineEnd = wordEnd; } } } } return pResult; } private static <L extends List<CharSequence>> L splitLinesByCJK(final IFont pFont, final CharSequence pText, final L pResult, final float pAutoWrapWidth) { final int textLength = pText.length(); int lineStart = 0; int lineEnd = 0; /* Skip whitespaces at the beginning of the string. */ while((lineStart < textLength) && (pText.charAt(lineStart) == ' ')) { lineStart++; lineEnd++; } int i = lineEnd; while(i < textLength) { lineStart = lineEnd; { /* Look for a sub string */ boolean charsAvailable = true; while(i < textLength) { { /* Skip whitespaces at the end of the string */ int j = lineEnd; while ( j < textLength ) { if ( pText.charAt( j ) == ' ' ) { j++; } else { break; } } if ( j == textLength ) { if ( lineStart == lineEnd ) { charsAvailable = false; } i = textLength; break; } } lineEnd++; final float lineWidth = FontUtils.measureText(pFont, pText, lineStart, lineEnd); if(lineWidth > pAutoWrapWidth) { if ( lineStart < lineEnd - 1 ) { lineEnd--; } pResult.add(pText.subSequence(lineStart, lineEnd)); charsAvailable = false; i = lineEnd; break; } i = lineEnd; } if(charsAvailable) { pResult.add(pText.subSequence(lineStart, lineEnd)); } } } return pResult; } private static float getAdvanceCorrection(final IFont pFont, final CharSequence pText, final int pIndex) { final Letter lastWordLastLetter = pFont.getLetter(pText.charAt(pIndex)); return -(lastWordLastLetter.mOffsetX + lastWordLastLetter.mWidth) + lastWordLastLetter.mAdvance; } // =========================================================== // Inner and Anonymous Classes // =========================================================== public enum MeasureDirection { // =========================================================== // Elements // =========================================================== FORWARDS, BACKWARDS; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
/* * Copyright 2008 Alin Dreghiciu. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.qi4j.test.indexing; import org.junit.Before; import org.junit.Test; import org.qi4j.api.composite.Composite; import org.qi4j.api.entity.EntityReference; import org.qi4j.api.query.QueryExpressions; import org.qi4j.api.query.grammar.OrderBy; import org.qi4j.api.service.ServiceReference; import org.qi4j.functional.Specification; import org.qi4j.spi.query.EntityFinder; import org.qi4j.spi.query.EntityFinderException; import org.qi4j.spi.query.IndexExporter; import org.qi4j.test.indexing.model.*; import java.io.IOException; import java.util.*; import static org.junit.Assert.assertEquals; import static org.qi4j.api.query.QueryExpressions.*; import static org.qi4j.test.indexing.NameableAssert.assertNames; import static org.qi4j.test.indexing.NameableAssert.toList; public abstract class AbstractEntityFinderTest extends AbstractAnyQueryTest { private static final Specification<Composite> ALL = null; private static final OrderBy[] NO_SORTING = null; private static final Integer NO_FIRST_RESULT = null; private static final Integer NO_MAX_RESULTS = null; private EntityFinder entityFinder; private static final String JACK = "Jack Doe"; private static final String JOE = "Joe Doe"; private static final String ANN = "Ann Doe"; @Before public void setUp() throws Exception { super.setUp(); entityFinder = this.module.findService( EntityFinder.class ).get(); } @Test public void showNetwork() throws IOException { final ServiceReference<IndexExporter> indexerService = this.module.findService( IndexExporter.class ); final IndexExporter exporter = indexerService.get(); exporter.exportReadableToStream( System.out ); // todo asserts } @Test public void script01() throws EntityFinderException { // should return all persons (Joe, Ann, Jack Doe) Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, ALL, NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE, JACK, ANN ); } @Test public void script02() throws EntityFinderException { Nameable nameable = templateFor( Nameable.class ); // should return Gaming domain Iterable<EntityReference> entities = entityFinder.findEntities( Domain.class, QueryExpressions.eq( nameable.name(), "Gaming" ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, "Gaming" ); } @Test public void script03() throws EntityFinderException { // should return all entities Iterable<EntityReference> entities = entityFinder.findEntities( Nameable.class, ALL, NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, NameableAssert.allNames() ); } @Test public void script04() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Joe and Ann Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, eq( person.placeOfBirth() .get() .name(), "Kuala Lumpur" ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE, ANN ); } @Test public void script05() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Joe Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, eq( person.mother() .get() .placeOfBirth() .get() .name(), "Kuala Lumpur" ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE ); } @Test public void script06() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Joe and Ann Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, ge( person.yearOfBirth(), 1973 ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE, ANN ); } @Test public void script07() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Jack Doe Iterable<EntityReference> entities = entityFinder.findEntities( Nameable.class, and( ge( person.yearOfBirth(), 1900 ), eq( person .placeOfBirth() .get() .name(), "Penang" ) ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JACK ); } @Test public void script08() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Jack and Ann Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, or( eq( person.yearOfBirth(), 1970 ), eq( person .yearOfBirth(), 1975 ) ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JACK, ANN ); } @Test public void script09() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Ann Doe Iterable<EntityReference> entities = entityFinder.findEntities( Female.class, or( eq( person.yearOfBirth(), 1970 ), eq( person .yearOfBirth(), 1975 ) ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, ANN ); } @Test public void script10() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Joe and Jack Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, not( eq( person.yearOfBirth(), 1975 ) ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE, JACK ); } @Test public void script11() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Joe Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, isNotNull( person.email() ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE ); } @Test public void script12() throws EntityFinderException { Person person = templateFor( Person.class ); // should return Ann and Jack Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, isNull( person.email() ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, ANN, JACK ); } @Test public void script13() throws EntityFinderException { Male person = templateFor( Male.class ); // should return Jack Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, isNotNull( person.wife() ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JACK ); } @Test public void script14() throws EntityFinderException { Male person = templateFor( Male.class ); // should return Joe Doe Iterable<EntityReference> entities = entityFinder.findEntities( Male.class, isNull( person.wife() ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JOE ); } @Test public void script15() throws EntityFinderException { Male person = templateFor( Male.class ); // should return Ann and Joe Doe Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, isNull( person.wife() ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, ANN, JOE ); } @Test public void script16() throws EntityFinderException { // should return only 2 entities final List<EntityReference> references = toList( entityFinder.findEntities( Nameable.class, ALL, NO_SORTING, NO_FIRST_RESULT, 2, Collections.<String, Object>emptyMap() ) ); assertEquals( "2 identitities", 2, references.size() ); } @Test public void script17() throws EntityFinderException { // should return only 2 entities starting with third one final List<EntityReference> references = toList( entityFinder.findEntities( Nameable.class, ALL, NO_SORTING, 3, 2, Collections.<String, Object>emptyMap() ) ); assertEquals( "2 identitities", 2, references.size() ); } @Test public void script18() throws EntityFinderException { // should return all Nameable entities sorted by name Nameable nameable = templateFor( Nameable.class ); final String[] allNames = NameableAssert.allNames(); Arrays.sort( allNames ); Iterable<EntityReference> entities = entityFinder.findEntities( Nameable.class, ALL, new OrderBy[] { orderBy( nameable.name() ) }, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( false, entities, allNames ); } @Test public void script19() throws EntityFinderException { // should return all Nameable entities with a name > "B" sorted by name Nameable nameable = templateFor( Nameable.class ); List<String> largerThanB = new ArrayList<String>(); for( String name : NameableAssert.allNames() ) { if( name.compareTo( "B" ) > 0 ) { largerThanB.add( name ); } } Collections.sort( largerThanB ); Iterable<EntityReference> entities = entityFinder.findEntities( Nameable.class, gt( nameable.name(), "B" ), new OrderBy[] { orderBy( nameable.name() ) }, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( false, entities, largerThanB.toArray( new String[ largerThanB.size() ] ) ); } @Test public void script20() throws EntityFinderException { // should return all Persons born after 1973 (Ann and Joe Doe) sorted descending by name Person person = templateFor( Person.class ); Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, gt( person.yearOfBirth(), 1973 ), new OrderBy[] { orderBy( person.name(), OrderBy.Order.DESCENDING ) }, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( false, entities, JOE, ANN ); } @Test public void script21() throws EntityFinderException { // should return all Persons sorted name of the city they were born Person person = templateFor( Person.class ); Iterable<EntityReference> entities = entityFinder.findEntities( Person.class, ALL, new OrderBy[] { orderBy( person.placeOfBirth().get().name() ), orderBy( person.name() ) }, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( false, entities, ANN, JOE, JACK ); } @Test public void script22() throws EntityFinderException { Nameable nameable = templateFor( Nameable.class ); // should return Jack and Joe Doe Iterable<EntityReference> entities = entityFinder.findEntities( Nameable.class, matches( nameable.name(), "J.*Doe" ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, Collections.<String, Object>emptyMap() ); assertNames( entities, JACK, JOE ); } @Test public void script23() throws EntityFinderException { Nameable nameable = templateFor( Nameable.class ); // Try using variables Map<String, Object> variables = new HashMap<String, Object>(); variables.put("domain", "Gaming"); Iterable<EntityReference> entities = entityFinder.findEntities( Domain.class, QueryExpressions.eq( nameable.name(), QueryExpressions.<String>variable( "domain" ) ), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, variables ); assertNames( entities, "Gaming" ); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hadoop.hbase.master; import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.Server; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.master.RegionState.State; /** * Run bulk assign. Does one RCP per regionserver passing a * batch of regions using {@link GeneralBulkAssigner.SingleServerBulkAssigner}. */ @InterfaceAudience.Private public class GeneralBulkAssigner extends BulkAssigner { private static final Log LOG = LogFactory.getLog(GeneralBulkAssigner.class); private Map<ServerName, List<HRegionInfo>> failedPlans = new ConcurrentHashMap<ServerName, List<HRegionInfo>>(); private ExecutorService pool; final Map<ServerName, List<HRegionInfo>> bulkPlan; final AssignmentManager assignmentManager; final boolean waitTillAllAssigned; public GeneralBulkAssigner(final Server server, final Map<ServerName, List<HRegionInfo>> bulkPlan, final AssignmentManager am, final boolean waitTillAllAssigned) { super(server); this.bulkPlan = bulkPlan; this.assignmentManager = am; this.waitTillAllAssigned = waitTillAllAssigned; } @Override protected String getThreadNamePrefix() { return this.server.getServerName() + "-GeneralBulkAssigner"; } @Override protected void populatePool(ExecutorService pool) { this.pool = pool; // shut it down later in case some assigner hangs for (Map.Entry<ServerName, List<HRegionInfo>> e: this.bulkPlan.entrySet()) { pool.execute(new SingleServerBulkAssigner(e.getKey(), e.getValue(), this.assignmentManager, this.failedPlans)); } } /** * * @param timeout How long to wait. * @return true if done. */ @Override protected boolean waitUntilDone(final long timeout) throws InterruptedException { Set<HRegionInfo> regionSet = new HashSet<HRegionInfo>(); for (List<HRegionInfo> regionList : bulkPlan.values()) { regionSet.addAll(regionList); } pool.shutdown(); // no more task allowed int serverCount = bulkPlan.size(); int regionCount = regionSet.size(); long startTime = System.currentTimeMillis(); long rpcWaitTime = startTime + timeout; while (!server.isStopped() && !pool.isTerminated() && rpcWaitTime > System.currentTimeMillis()) { if (failedPlans.isEmpty()) { pool.awaitTermination(100, TimeUnit.MILLISECONDS); } else { reassignFailedPlans(); } } if (!pool.isTerminated()) { LOG.warn("bulk assigner is still running after " + (System.currentTimeMillis() - startTime) + "ms, shut it down now"); // some assigner hangs, can't wait any more, shutdown the pool now List<Runnable> notStarted = pool.shutdownNow(); if (notStarted != null && !notStarted.isEmpty()) { server.abort("some single server assigner hasn't started yet" + " when the bulk assigner timed out", null); return false; } } int reassigningRegions = 0; if (!failedPlans.isEmpty() && !server.isStopped()) { reassigningRegions = reassignFailedPlans(); } Configuration conf = server.getConfiguration(); long perRegionOpenTimeGuesstimate = conf.getLong("hbase.bulk.assignment.perregion.open.time", 1000); long endTime = Math.max(System.currentTimeMillis(), rpcWaitTime) + perRegionOpenTimeGuesstimate * (reassigningRegions + 1); RegionStates regionStates = assignmentManager.getRegionStates(); // We're not synchronizing on regionsInTransition now because we don't use any iterator. while (!regionSet.isEmpty() && !server.isStopped() && endTime > System.currentTimeMillis()) { Iterator<HRegionInfo> regionInfoIterator = regionSet.iterator(); while (regionInfoIterator.hasNext()) { HRegionInfo hri = regionInfoIterator.next(); if (regionStates.isRegionOnline(hri) || regionStates.isRegionInState(hri, State.SPLITTING, State.SPLIT, State.MERGING, State.MERGED)) { regionInfoIterator.remove(); } } if (!waitTillAllAssigned) { // No need to wait, let assignment going on asynchronously break; } if (!regionSet.isEmpty()) { regionStates.waitForUpdate(100); } } if (LOG.isDebugEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; String status = "successfully"; if (!regionSet.isEmpty()) { status = "with " + regionSet.size() + " regions still in transition"; } LOG.debug("bulk assigning total " + regionCount + " regions to " + serverCount + " servers, took " + elapsedTime + "ms, " + status); } return regionSet.isEmpty(); } @Override protected long getTimeoutOnRIT() { // Guess timeout. Multiply the max number of regions on a server // by how long we think one region takes opening. Configuration conf = server.getConfiguration(); long perRegionOpenTimeGuesstimate = conf.getLong("hbase.bulk.assignment.perregion.open.time", 1000); int maxRegionsPerServer = 1; for (List<HRegionInfo> regionList : bulkPlan.values()) { int size = regionList.size(); if (size > maxRegionsPerServer) { maxRegionsPerServer = size; } } long timeout = perRegionOpenTimeGuesstimate * maxRegionsPerServer + conf.getLong("hbase.regionserver.rpc.startup.waittime", 60000) + conf.getLong("hbase.bulk.assignment.perregionserver.rpc.waittime", 30000) * bulkPlan.size(); LOG.debug("Timeout-on-RIT=" + timeout); return timeout; } @Override protected UncaughtExceptionHandler getUncaughtExceptionHandler() { return new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.warn("Assigning regions in " + t.getName(), e); } }; } private int reassignFailedPlans() { List<HRegionInfo> reassigningRegions = new ArrayList<HRegionInfo>(); for (Map.Entry<ServerName, List<HRegionInfo>> e : failedPlans.entrySet()) { LOG.info("Failed assigning " + e.getValue().size() + " regions to server " + e.getKey() + ", reassigning them"); reassigningRegions.addAll(failedPlans.remove(e.getKey())); } RegionStates regionStates = assignmentManager.getRegionStates(); for (HRegionInfo region : reassigningRegions) { if (!regionStates.isRegionOnline(region)) { assignmentManager.invokeAssign(region); } } return reassigningRegions.size(); } /** * Manage bulk assigning to a server. */ static class SingleServerBulkAssigner implements Runnable { private final ServerName regionserver; private final List<HRegionInfo> regions; private final AssignmentManager assignmentManager; private final Map<ServerName, List<HRegionInfo>> failedPlans; SingleServerBulkAssigner(final ServerName regionserver, final List<HRegionInfo> regions, final AssignmentManager am, final Map<ServerName, List<HRegionInfo>> failedPlans) { this.regionserver = regionserver; this.regions = regions; this.assignmentManager = am; this.failedPlans = failedPlans; } @Override public void run() { try { if (!assignmentManager.assign(regionserver, regions)) { failedPlans.put(regionserver, regions); } } catch (Throwable t) { LOG.warn("Failed bulking assigning " + regions.size() + " region(s) to " + regionserver.getServerName() + ", and continue to bulk assign others", t); failedPlans.put(regionserver, regions); } } } }
package org.motechproject.nms.api.web; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.motechproject.nms.api.web.contract.BadRequest; import org.motechproject.nms.api.web.exception.NotAuthorizedException; import org.motechproject.nms.api.web.exception.NotDeployedException; import org.motechproject.nms.api.web.exception.NotFoundException; import org.motechproject.nms.flw.domain.FrontLineWorker; import org.motechproject.nms.flw.service.FrontLineWorkerService; import org.motechproject.nms.flw.service.WhitelistService; import org.motechproject.nms.kilkari.domain.DeactivationReason; import org.motechproject.nms.props.domain.CallDisconnectReason; import org.motechproject.nms.props.domain.FinalCallStatus; import org.motechproject.nms.props.domain.Service; import org.motechproject.nms.props.service.PropertyService; import org.motechproject.nms.region.domain.Circle; import org.motechproject.nms.region.domain.State; import org.motechproject.nms.region.service.StateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import java.util.Map; import java.util.Set; /** * BaseController * * Common data & helper methods * All error handlers * */ public class BaseController { public static final String MOBILE_ACADEMY = "mobileacademy"; public static final String MOBILE_KUNJI = "mobilekunji"; public static final String KILKARI = "kilkari"; public static final String NOT_PRESENT = "<%s: Not Present>"; public static final String INVALID = "<%s: Invalid>"; public static final String NOT_FOUND = "<%s: Not Found>"; public static final String NOT_AUTHORIZED = "<%s: Not Authorized>"; public static final String NOT_DEPLOYED = "<%s: Not Deployed In State>"; public static final String IVR_INTERACTION_LOG = "IVR INTERACTION: %s"; public static final long SMALLEST_10_DIGIT_NUMBER = 1000000000L; public static final long LARGEST_10_DIGIT_NUMBER = 9999999999L; public static final long SMALLEST_15_DIGIT_NUMBER = 100000000000000L; public static final long LARGEST_15_DIGIT_NUMBER = 999999999999999L; public static final int CALL_ID_LENGTH = 25; public static final long MILLIS = 1000; public static final int MAX_LENGTH_255 = 255; public static final int MA_MIN_SCORE = 0; public static final int MA_MAX_SCORE = 4; public static final String CALLING_NUMBER = "callingNumber"; private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class); public static final String LOG_RESPONSE_FORMAT = "RESPONSE: %s"; @Autowired private WhitelistService whitelistService; @Autowired private PropertyService propertyService; @Autowired private FrontLineWorkerService frontLineWorkerService; @Autowired private StateService stateService; protected static void log(final String endpoint, final String s) { LOGGER.info(IVR_INTERACTION_LOG.format(endpoint) + (StringUtils.isBlank(s) ? "" : " : " + s)); } protected static void log(final String endpoint) { log(endpoint, null); } protected static boolean validateFieldPresent(StringBuilder errors, String fieldName, Object value) { if (value != null) { return true; } errors.append(String.format(NOT_PRESENT, fieldName)); return false; } protected static boolean validateFieldString(StringBuilder errors, String fieldName, String value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (value.length() > 0) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateFieldPositiveLong(StringBuilder errors, String fieldName, Long value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (value >= 0) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateDeactivationReason(StringBuilder errors, String fieldName, String value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } DeactivationReason reason = DeactivationReason.valueOf(value); if (reason.equals(DeactivationReason.WEEKLY_CALLS_NOT_ANSWERED) || reason.equals(DeactivationReason.LOW_LISTENERSHIP)) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateField10Digits(StringBuilder errors, String fieldName, Long value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (value >= SMALLEST_10_DIGIT_NUMBER && value <= LARGEST_10_DIGIT_NUMBER) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateField15Digits(StringBuilder errors, String fieldName, Long value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (value >= SMALLEST_15_DIGIT_NUMBER && value <= LARGEST_15_DIGIT_NUMBER) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateCallId(StringBuilder errors, String value) { if (value == null || value.isEmpty()) { errors.append(String.format(NOT_PRESENT, "callId")); return false; } if (value.length() == CALL_ID_LENGTH) { return true; } errors.append(String.format(INVALID, "callId")); return false; } protected static boolean validateFieldCallStatus(StringBuilder errors, String fieldName, Integer value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (FinalCallStatus.isValidEnumValue(value)) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateFieldGfStatus(StringBuilder errors, String fieldName, String value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (("Active").equals(value) || ("Inactive").equals(value)) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected static boolean validateFieldCallDisconnectReason(StringBuilder errors, String fieldName, Integer value) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (CallDisconnectReason.isValidEnumValue(value)) { return true; } errors.append(String.format(INVALID, fieldName)); return false; } protected boolean validateFieldExactLength(StringBuilder errors, String fieldName, String value, int length) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } if (value.length() != length) { errors.append(String.format(INVALID, fieldName)); return false; } return true; } protected boolean validateRequiredFieldMaxLength(StringBuilder errors, String fieldName, String value, int length) { if (!validateFieldPresent(errors, fieldName, value)) { return false; } return validateFieldMaxLength(errors, fieldName, value, length); } protected boolean validateFieldMaxLength(StringBuilder errors, String fieldName, String value, int length) { if (value != null && value.length() > length) { errors.append(String.format(INVALID, fieldName)); return false; } return true; } protected StringBuilder validate(Long callingNumber, String callId) { StringBuilder failureReasons = new StringBuilder(); validateField10Digits(failureReasons, "callingNumber", callingNumber); validateCallId(failureReasons, callId); return failureReasons; } protected StringBuilder validate(Long callingNumber, String callId, String operator, String circle) { StringBuilder failureReasons = validate(callingNumber, callId); validateFieldMaxLength(failureReasons, "operator", operator, MAX_LENGTH_255); validateFieldMaxLength(failureReasons, "circle", circle, MAX_LENGTH_255); return failureReasons; } protected DateTime epochToDateTime(long epoch) { return new DateTime(epoch * MILLIS); // epoch time sent by IVR is in secs } protected State getStateForFrontLineWorker(FrontLineWorker flw, Circle circle) { State state = frontLineWorkerService.getState(flw); if (state == null && circle != null) { state = getStateFromCircle(circle); } return state; } protected State getStateFromCircle(Circle circle) { State state = null; if (circle != null) { Set<State> states = stateService.getAllInCircle(circle); if (states.size() == 1) { state = states.iterator().next(); } } return state; } protected boolean frontLineWorkerAuthorizedForAccess(FrontLineWorker flw, State state) { return whitelistService.numberWhitelistedForState(state, flw.getContactNumber()); } /** * Check if the service is deployed for a given circle * @param service service to check * @param circle circle of the caller * @return true if circle is null/unknown, or * true if no states in circle or * true if one state in circle is authorized, otherwise * false if none of the states in circle are deployed */ protected boolean serviceDeployedInCircle(Service service, Circle circle) { if (circle == null) { return true; } Set<State> states = stateService.getAllInCircle(circle); if (states == null || states.isEmpty()) { // No state available return true; } for (State currentState : states) { // multiple states, false if undeployed in all states if (serviceDeployedInUserState(service, currentState)) { return true; } } return false; } /** * Check if the service is deployed for a given state * @param service service to check * @param state (geographical)state of the user * @return true, if state is null or * true, if state is deployed * false, if state is not deployed */ protected boolean serviceDeployedInUserState(Service service, State state) { return propertyService.isServiceDeployedInState(service, state); } protected boolean validateMAScores(Map<String, Integer> scores) { if (scores != null) { for (Integer currentScore : scores.values()) { if (currentScore < MA_MIN_SCORE || currentScore > MA_MAX_SCORE) { throw new IllegalArgumentException(String.format(INVALID, "scoresByChapter")); } } } return true; } @ExceptionHandler(NotAuthorizedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public BadRequest handleException(NotAuthorizedException e, HttpServletRequest request) { log(String.format(LOG_RESPONSE_FORMAT, request.getRequestURI()), e.getMessage()); return new BadRequest(e.getMessage()); } @ExceptionHandler(NotDeployedException.class) @ResponseStatus(HttpStatus.NOT_IMPLEMENTED) @ResponseBody public BadRequest handleException(NotDeployedException e, HttpServletRequest request) { log(String.format(LOG_RESPONSE_FORMAT, request.getRequestURI()), e.getMessage()); return new BadRequest(e.getMessage()); } @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public BadRequest handleException(IllegalArgumentException e, HttpServletRequest request) { log(String.format(LOG_RESPONSE_FORMAT, request.getRequestURI()), e.getMessage()); return new BadRequest(e.getMessage()); } @ExceptionHandler(NotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody public BadRequest handleException(NotFoundException e, HttpServletRequest request) { log(String.format(LOG_RESPONSE_FORMAT, request.getRequestURI()), e.getMessage()); return new BadRequest(e.getMessage()); } @ExceptionHandler(NullPointerException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public BadRequest handleException(NullPointerException e, HttpServletRequest request) { log(String.format(LOG_RESPONSE_FORMAT, request.getRequestURI()), e.getMessage()); LOGGER.error("Internal Server Error", e); return new BadRequest(e.getMessage()); } /** * Handles malformed JSON, returns a slightly more informative message than a generic HTTP-400 Bad Request */ @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public BadRequest handleException(HttpMessageNotReadableException e, HttpServletRequest request) { log(String.format(LOG_RESPONSE_FORMAT, request.getRequestURI()), e.getMessage()); return new BadRequest(e.getMessage()); } protected Service getServiceFromName(String serviceName) { Service service = null; if (MOBILE_ACADEMY.equals(serviceName)) { service = Service.MOBILE_ACADEMY; } if (MOBILE_KUNJI.equals(serviceName)) { service = Service.MOBILE_KUNJI; } return service; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.cassandra.db.virtual; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import org.apache.cassandra.config.Config; import org.apache.cassandra.config.EncryptionOptions.ServerEncryptionOptions.InternodeEncryption; import org.apache.cassandra.cql3.CQLTester; public class SettingsTableTest extends CQLTester { private static final String KS_NAME = "vts"; private Config config; private SettingsTable table; @BeforeClass public static void setUpClass() { CQLTester.setUpClass(); } @Before public void config() { config = new Config(); table = new SettingsTable(KS_NAME, config); VirtualKeyspaceRegistry.instance.register(new VirtualKeyspace(KS_NAME, ImmutableList.of(table))); } private String getValue(Field f) { Object untypedValue = table.getValue(f); String value = null; if (untypedValue != null) { if (untypedValue.getClass().isArray()) { value = Arrays.toString((Object[]) untypedValue); } else value = untypedValue.toString(); } return value; } @Test public void testSelectAll() throws Throwable { int paging = (int) (Math.random() * 100 + 1); ResultSet result = executeNetWithPaging("SELECT * FROM vts.settings", paging); int i = 0; for (Row r : result) { i++; String name = r.getString("name"); Field f = SettingsTable.FIELDS.get(name); if (f != null) // skip overrides Assert.assertEquals(getValue(f), r.getString("value")); } Assert.assertTrue(SettingsTable.FIELDS.size() <= i); } @Test public void testSelectPartition() throws Throwable { List<Field> fields = Arrays.stream(Config.class.getFields()) .filter(f -> !Modifier.isStatic(f.getModifiers())) .collect(Collectors.toList()); for (Field f : fields) { if (table.overrides.containsKey(f.getName())) continue; String q = "SELECT * FROM vts.settings WHERE name = '"+f.getName()+'\''; assertRowsNet(executeNet(q), new Object[] {f.getName(), getValue(f)}); } } @Test public void testSelectEmpty() throws Throwable { String q = "SELECT * FROM vts.settings WHERE name = 'EMPTY'"; assertRowsNet(executeNet(q)); } @Test public void testSelectOverride() throws Throwable { String q = "SELECT * FROM vts.settings WHERE name = 'server_encryption_options_enabled'"; assertRowsNet(executeNet(q), new Object[] {"server_encryption_options_enabled", "false"}); q = "SELECT * FROM vts.settings WHERE name = 'server_encryption_options_XYZ'"; assertRowsNet(executeNet(q)); } private void check(String setting, String expected) throws Throwable { String q = "SELECT * FROM vts.settings WHERE name = '"+setting+'\''; assertRowsNet(executeNet(q), new Object[] {setting, expected}); } @Test public void testEncryptionOverride() throws Throwable { String pre = "server_encryption_options_"; check(pre + "enabled", "false"); String all = "SELECT * FROM vts.settings WHERE " + "name > 'server_encryption' AND name < 'server_encryptionz' ALLOW FILTERING"; config.server_encryption_options = config.server_encryption_options.withEnabled(true); Assert.assertEquals(9, executeNet(all).all().size()); check(pre + "enabled", "true"); check(pre + "algorithm", null); config.server_encryption_options = config.server_encryption_options.withAlgorithm("SUPERSSL"); check(pre + "algorithm", "SUPERSSL"); check(pre + "cipher_suites", "[]"); config.server_encryption_options = config.server_encryption_options.withCipherSuites("c1", "c2"); check(pre + "cipher_suites", "[c1, c2]"); check(pre + "protocol", config.server_encryption_options.protocol); config.server_encryption_options = config.server_encryption_options.withProtocol("TLSv5"); check(pre + "protocol", "TLSv5"); check(pre + "optional", "false"); config.server_encryption_options = config.server_encryption_options.withOptional(true); check(pre + "optional", "true"); check(pre + "client_auth", "false"); config.server_encryption_options = config.server_encryption_options.withRequireClientAuth(true); check(pre + "client_auth", "true"); check(pre + "endpoint_verification", "false"); config.server_encryption_options = config.server_encryption_options.withRequireEndpointVerification(true); check(pre + "endpoint_verification", "true"); check(pre + "internode_encryption", "none"); config.server_encryption_options = config.server_encryption_options.withInternodeEncryption(InternodeEncryption.all); check(pre + "internode_encryption", "all"); check(pre + "legacy_ssl_storage_port", "false"); config.server_encryption_options = config.server_encryption_options.withLegacySslStoragePort(true); check(pre + "legacy_ssl_storage_port", "true"); } @Test public void testAuditOverride() throws Throwable { String pre = "audit_logging_options_"; check(pre + "enabled", "false"); String all = "SELECT * FROM vts.settings WHERE " + "name > 'audit_logging' AND name < 'audit_loggingz' ALLOW FILTERING"; config.audit_logging_options.enabled = true; Assert.assertEquals(9, executeNet(all).all().size()); check(pre + "enabled", "true"); check(pre + "logger", "BinAuditLogger"); config.audit_logging_options.logger = "logger"; check(pre + "logger", "logger"); config.audit_logging_options.audit_logs_dir = "dir"; check(pre + "audit_logs_dir", "dir"); check(pre + "included_keyspaces", ""); config.audit_logging_options.included_keyspaces = "included_keyspaces"; check(pre + "included_keyspaces", "included_keyspaces"); check(pre + "excluded_keyspaces", "system,system_schema,system_virtual_schema"); config.audit_logging_options.excluded_keyspaces = "excluded_keyspaces"; check(pre + "excluded_keyspaces", "excluded_keyspaces"); check(pre + "included_categories", ""); config.audit_logging_options.included_categories = "included_categories"; check(pre + "included_categories", "included_categories"); check(pre + "excluded_categories", ""); config.audit_logging_options.excluded_categories = "excluded_categories"; check(pre + "excluded_categories", "excluded_categories"); check(pre + "included_users", ""); config.audit_logging_options.included_users = "included_users"; check(pre + "included_users", "included_users"); check(pre + "excluded_users", ""); config.audit_logging_options.excluded_users = "excluded_users"; check(pre + "excluded_users", "excluded_users"); } @Test public void testTransparentEncryptionOptionsOverride() throws Throwable { String pre = "transparent_data_encryption_options_"; check(pre + "enabled", "false"); String all = "SELECT * FROM vts.settings WHERE " + "name > 'transparent_data_encryption_options' AND " + "name < 'transparent_data_encryption_optionsz' ALLOW FILTERING"; config.transparent_data_encryption_options.enabled = true; Assert.assertEquals(4, executeNet(all).all().size()); check(pre + "enabled", "true"); check(pre + "cipher", "AES/CBC/PKCS5Padding"); config.transparent_data_encryption_options.cipher = "cipher"; check(pre + "cipher", "cipher"); check(pre + "chunk_length_kb", "64"); config.transparent_data_encryption_options.chunk_length_kb = 5; check(pre + "chunk_length_kb", "5"); check(pre + "iv_length", "16"); config.transparent_data_encryption_options.iv_length = 7; check(pre + "iv_length", "7"); } }
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import se.sitic.megatron.core.AppProperties; import se.sitic.megatron.core.CommandLineParseException; import se.sitic.megatron.core.EmailAddressBatchUpdater; import se.sitic.megatron.core.JobInfoWriter; import se.sitic.megatron.core.JobListWriter; import se.sitic.megatron.core.JobScheduler; import se.sitic.megatron.core.MegatronException; import se.sitic.megatron.core.NetnameUpdater; import se.sitic.megatron.core.StatsRssGenerator; import se.sitic.megatron.core.TypedProperties; import se.sitic.megatron.core.WhoisWriter; import se.sitic.megatron.db.DbManager; import se.sitic.megatron.db.ImportBgpTable; import se.sitic.megatron.db.ImportSystemData; import se.sitic.megatron.entity.Job; import se.sitic.megatron.entity.Priority; import se.sitic.megatron.report.IReportGenerator; import se.sitic.megatron.ui.OrganizationHandler; import se.sitic.megatron.util.Constants; import se.sitic.megatron.util.FileUtil; import se.sitic.megatron.util.StringUtil; import se.sitic.megatron.util.Version; /** * Main class for Megatron. This class is called from the CLI. */ public class Megatron { /** Key in system properties for log4j config file. */ private static final String LOG4J_FILE_KEY = "megatron.log4jfile"; // Note: // * --overwrite is not used. use --delete plus re-run instead. // * --export may be used with --output-dir or use filename in config // * Log job + mail job is not allowed, because it breaks preview. // * --mail requires --id plus and job. --no-db is not allowed. private static final String USAGE = "_______ _______ ______ _______ _______ ______ _____ __ _" + Constants.LINE_BREAK + "| | | |______ | ____ |_____| | |_____/ | | | \\ |" + Constants.LINE_BREAK + "| | | |______ |_____| | | | | \\_ |_____| | \\_|" + Constants.LINE_BREAK + "" + Constants.LINE_BREAK + "Usage: megatron.sh [options] logfiles(s)" + Constants.LINE_BREAK + "" + Constants.LINE_BREAK + "Options:" + Constants.LINE_BREAK + " -v, --version Print application version and exit." + Constants.LINE_BREAK + " -h, --help Print this help message." + Constants.LINE_BREAK + " -s, --slurp Process files in the slurp directory." + Constants.LINE_BREAK + " -l, --list-jobs List processed log jobs. No. of days may be specified." + Constants.LINE_BREAK + " -w, --whois Print whois report for specified IPs or hostnames." + Constants.LINE_BREAK + " -e, --export Export log records to file." + Constants.LINE_BREAK + " -d, --delete Delete job including log records." + Constants.LINE_BREAK + " -D, --delete-all Delete job plus mail jobs." + Constants.LINE_BREAK + " -j, --job Specifies job, e.g. 'shadowserver-drone_2009-06-22_084510'." + Constants.LINE_BREAK + " -t, --job-type Specifies job type for input files, e.g. 'shadowserver-drone'." + Constants.LINE_BREAK + " -o, --output-dir Specifies directory for export files." + Constants.LINE_BREAK + " -i, --id Specifies RTIR id." + Constants.LINE_BREAK + " -p, --prio Specifies priority for log records to be emailed or exported." + Constants.LINE_BREAK + " -P, --list-prios List priorities." + Constants.LINE_BREAK + " -I, --job-info Print info about specified log job." + Constants.LINE_BREAK + " -n, --no-db Skip writes to the database." + Constants.LINE_BREAK + " -S, --stdout Writes to stdout instead of export file." + Constants.LINE_BREAK + " -1, --mail-dry-run Create a mail report but does not send any mail." + Constants.LINE_BREAK + " -2, --mail-dry-run2 As '--mail-dry-run' but more verbose." + Constants.LINE_BREAK + " -m, --mail Send mails for a job." + Constants.LINE_BREAK + " -b, --use-org2 Use secondary organization when mailing." + Constants.LINE_BREAK + "" + Constants.LINE_BREAK + "Admin Options:" + Constants.LINE_BREAK + " --import-contacts Import organizations to the database." + Constants.LINE_BREAK + " --import-bgp Import BGP dump file (specified in config)." + Constants.LINE_BREAK + " --update-netname Update netname field from whois queries." + Constants.LINE_BREAK + " --add-addresses Add email addresses listed in specified file." + Constants.LINE_BREAK + " --delete-addresses Delete email addresses listed in specified file." + Constants.LINE_BREAK + " --create-rss Create RSS with Megatron statistics."+ Constants.LINE_BREAK + " --create-reports Create report files (json, xml, html, etc.)."+ Constants.LINE_BREAK + " --create-report Run a specific report."+ Constants.LINE_BREAK + " --ui-org Administration of organizations (command line interface)." + Constants.LINE_BREAK + "" + Constants.LINE_BREAK + "Examples:" + Constants.LINE_BREAK + " Process file and save result in the database:" + Constants.LINE_BREAK + " megatron.sh --job-type shadowserver-drone 2009-06-22-drone-report-se.csv" + Constants.LINE_BREAK + " Preview of mail to be sent:" + Constants.LINE_BREAK + " megatron.sh --job shadowserver-drone_2009-06-22_160142 --id 4242 --mail-dry-run" + Constants.LINE_BREAK + " Send mails for the job:" + Constants.LINE_BREAK + " megatron.sh --job shadowserver-drone_2009-06-22_160142 --id 4242 --mail" + Constants.LINE_BREAK + " As above, but sends only to organizations with a prio of 50 or above:" + Constants.LINE_BREAK + " megatron.sh --job shadowserver-drone_2009-06-22_160142 --id 4242 --prio 50 --mail" + Constants.LINE_BREAK + " Display information, e.g. high priority organizations, about specified job:" + Constants.LINE_BREAK + " megatron.sh --job-info shadowserver-drone_2009-06-15_124508" + Constants.LINE_BREAK + " Delete specified job:" + Constants.LINE_BREAK + " megatron.sh --delete shadowserver-drone_2009-06-15_124508" + Constants.LINE_BREAK + " Display log jobs created the last 4 days:" + Constants.LINE_BREAK + " megatron.sh --list-jobs 4" + Constants.LINE_BREAK + " Process files and exports them to a different format:" + Constants.LINE_BREAK + " megatron.sh --export --job-type whois-cymru-verbose --no-db file1.txt file2.txt" + Constants.LINE_BREAK + " Add email addresses listed in file to the database:" + Constants.LINE_BREAK + " megatron.sh --add-addresses new-addresses.txt" + Constants.LINE_BREAK + " Start admin-UI for organizations, IP-blocks, ASNs, and domain names:" + Constants.LINE_BREAK + " megatron.sh --ui-org" + Constants.LINE_BREAK + " Print whois report for specified IPs (hostnames or URLs will also work):" + Constants.LINE_BREAK + " megatron.sh --whois 192.121.218.90 1.1.1.1 2.2.2.2 8.8.8.8" + Constants.LINE_BREAK + " Print whois report for specified file with IPs, hostnames, or URLs:" + Constants.LINE_BREAK + " megatron.sh --whois infected.txt" + Constants.LINE_BREAK + " Run the organization report (emails an abuse-report to selected organizations):" + Constants.LINE_BREAK + " megatron.sh --create-report se.sitic.megatron.report.OrganizationReportGenerator" + Constants.LINE_BREAK + " Process files in the slurp directory and exports them to a different format:" + Constants.LINE_BREAK + " megatron.sh --slurp --no-db --export" + Constants.LINE_BREAK + " Process files in the slurp directory and save result in the database:" + Constants.LINE_BREAK + " megatron.sh --slurp" + Constants.LINE_BREAK; private static final String CLI_ERROR = "@errorMsg@" + Constants.LINE_BREAK + "--help will show help message." + Constants.LINE_BREAK + "" + Constants.LINE_BREAK; /** * Main. */ public static void main(String[] args) { Logger log = null; try { Megatron megatron = new Megatron(); // -- Read config files and parse command line try { AppProperties.getInstance().init(args); } catch (CommandLineParseException e) { if (e.getAction() == CommandLineParseException.SHOW_USAGE_ACTION) { System.out.println(USAGE); System.exit(0); } else if (e.getAction() == CommandLineParseException.SHOW_VERSION_ACTION) { System.out.println(Version.getVersionInfo()); System.exit(0); } else { String errorMsg = (e.getMessage() != null) ? e.getMessage() : ""; String msg = StringUtil.replace(CLI_ERROR, "@errorMsg@", errorMsg); System.err.println(msg); System.exit(1); } } catch (MegatronException e) { String msg = "Error: Cannot initialize configuration: " + e.getMessage(); System.err.println(msg); e.printStackTrace(); System.exit(1); } // -- Init logging megatron.ensureDirs(); try { megatron.initLogging(); } catch (FileNotFoundException e) { String msg = "Error: Cannot initialize logging: " + e.getMessage(); System.err.println(msg); e.printStackTrace(); System.exit(2); } log = Logger.getLogger(Megatron.class); log.info(megatron.getVersion() + " started."); megatron.processCommands(); log.info(Version.getAppName() + " finished."); System.exit(0); } catch (Throwable e) { String msg = (e instanceof MegatronException) ? "Error: " + e.getMessage() : "Error (unhandled exception): " + e.getMessage(); if (log != null) { // Big Brother looks for "fatal" errors. log.fatal(msg, e); } // Write message to console (without a stack trace, which may scare the user) System.err.println(msg); Throwable cause = e.getCause(); while (cause != null) { msg = cause.getMessage(); if (StringUtil.isNullOrEmpty(msg) || msg.equalsIgnoreCase("null")) { msg = "[Message not available]"; } System.err.println(" " + msg); cause = cause.getCause(); } try { String dir = AppProperties.getInstance().getGlobalProperties().getString(AppProperties.LOG_DIR_KEY, "[property missing]"); // hardcoded; filename is specified in log4j.properties String filename = "megatron.log"; File logFile = new File(dir, filename); System.err.println("See log file for more info: " + logFile.getAbsoluteFile()); } catch (Exception e2) { // ignored } System.exit(100); } } private void initLogging() throws FileNotFoundException { String log4jFilename = System.getProperty(LOG4J_FILE_KEY); String defaultFilename = AppProperties.getInstance().getGlobalProperties().getString(AppProperties.LOG4J_FILE_KEY, null); log4jFilename = (log4jFilename != null) ? log4jFilename : defaultFilename; File file = new File(log4jFilename); if (!file.exists()) { String msg = "Cannot find log4j config-file: " + file.getAbsoluteFile() + ". Working directory for Megatron is probably wrong."; throw new FileNotFoundException(msg); } PropertyConfigurator.configure(log4jFilename); } /** * Creates, if necessary, directories required by the application. */ private void ensureDirs() throws IOException { TypedProperties globalProps = AppProperties.getInstance().getGlobalProperties(); String dir = null; dir = globalProps.getString(AppProperties.LOG_DIR_KEY, null); FileUtil.ensureDir(dir); dir = globalProps.getOutputDir(); FileUtil.ensureDir(dir); dir = globalProps.getString(AppProperties.SLURP_DIR_KEY, null); FileUtil.ensureDir(dir); } private String getVersion() { return Version.getVersion(true); } /** * Process commands in the command line. */ private void processCommands() throws MegatronException { TypedProperties globalProps = AppProperties.getInstance().getGlobalProperties(); if (globalProps.isWhois()) { // inputFiles contains IPs and hostnames WhoisWriter writer = new WhoisWriter(globalProps, true); writer.execute(); return; } List<String> inputFiles = AppProperties.getInstance().getInputFiles(); if (inputFiles.size() > 0) { for (Iterator<String> iterator = inputFiles.iterator(); iterator.hasNext();) { File file = new File(iterator.next()); String jobType = AppProperties.getInstance().mapFilenameToJobType(file.getName(), false); if (jobType == null) { throw new MegatronException("Cannot find a job-type. Use '--job-type' to specify one."); } TypedProperties props = AppProperties.getInstance().createTypedPropertiesForCli(jobType); JobScheduler.getInstance().processFile(props, file); } } else if (globalProps.isListJobs()) { JobListWriter writer = new JobListWriter(globalProps, true); writer.execute(); } else if (globalProps.isListPrios()) { listPrio(globalProps); } else if (globalProps.isJobInfo()) { JobInfoWriter writer = new JobInfoWriter(globalProps); writer.execute(); } else if (globalProps.isSlurp()) { JobScheduler.getInstance().processSlurpDirectory(); } else if (globalProps.isExport()) { String jobName = globalProps.getJob(); if (jobName == null) { throw new MegatronException("Invalid command line: No job ('--job') specified."); } String jobType = getJobType(globalProps, jobName); TypedProperties props = AppProperties.getInstance().createTypedPropertiesForCli(jobType); JobScheduler.getInstance().processFileExport(props, jobName); } else if (globalProps.isMail() || globalProps.isMailDryRun() || globalProps.isMailDryRun2()) { // check CLI args String id = globalProps.getParentTicketId(); if (id == null) { throw new MegatronException("Invalid command line: No RTIR-id ('--id') specified."); } String jobName = globalProps.getJob(); if (jobName == null) { throw new MegatronException("Invalid command line: No job ('--job') specified."); } if (globalProps.isNoDb()) { throw new MegatronException("Invalid command line: --no-db cannot be used when mailing."); } // run mail job String jobType = getJobType(globalProps, jobName); TypedProperties props = AppProperties.getInstance().createTypedPropertiesForCli(jobType); JobScheduler.getInstance().processMailJob(props, jobName); } else if (globalProps.isImportContacts()) { ImportSystemData dataImporter = new ImportSystemData(globalProps); dataImporter.importFile(); } else if (globalProps.isImportBgp()) { ImportBgpTable importer = new ImportBgpTable(globalProps); importer.importFile(); } else if (globalProps.isUpdateNetname()) { NetnameUpdater updater = new NetnameUpdater(globalProps); updater.update(); } else if (globalProps.isAddAddresses()) { EmailAddressBatchUpdater updater = new EmailAddressBatchUpdater(globalProps); updater.addAddresses(globalProps.getAddressesFile()); } else if (globalProps.isDeleteAddresses()) { EmailAddressBatchUpdater updater = new EmailAddressBatchUpdater(globalProps); updater.deleteAddresses(globalProps.getAddressesFile()); } else if (globalProps.isCreateStatsRss()) { StatsRssGenerator generator = new StatsRssGenerator(globalProps); generator.createFile(); } else if (globalProps.isCreateFlashXml() || globalProps.isCreateReports() || (globalProps.getCreateReport() != null)) { String classNames[] = null; if (globalProps.getCreateReport() != null) { classNames = new String[1]; classNames[0] = globalProps.getCreateReport(); } else { classNames = globalProps.getStringList(AppProperties.REPORT_CLASS_NAMES_KEY, new String[0]); } List<IReportGenerator> reportGenerators = createReportGenerators(classNames); if (reportGenerators.isEmpty()) { throw new MegatronException("No report generators specified. See '" + AppProperties.REPORT_CLASS_NAMES_KEY + "'." ); } for (Iterator<IReportGenerator> iterator = reportGenerators.iterator(); iterator.hasNext(); ) { iterator.next().createFiles(); } } else if (globalProps.isUiOrg()) { OrganizationHandler uiOrg = new OrganizationHandler(globalProps); uiOrg.startUI(); } else if (globalProps.isDelete() || globalProps.isDeleteAll()) { String jobName = globalProps.getJob(); if (jobName == null) { throw new MegatronException("Invalid command line: No job ('--job') specified."); } if (globalProps.isNoDb()) { throw new MegatronException("Invalid command line: --no-db cannot be used when deleting."); } if (globalProps.isDeleteAll()) { JobScheduler.getInstance().deleteAll(globalProps, jobName); } else { JobScheduler.getInstance().delete(globalProps, jobName); } System.out.println("Job deleted: " + jobName); } else { // nothing to do; show usage System.out.println(USAGE); } } /** * Fetches job type from db for specified job name. */ private String getJobType(TypedProperties globalProps, String jobName) throws MegatronException { DbManager dbManager = null; try { dbManager = DbManager.createDbManager(globalProps); Job job = dbManager.searchLogJob(jobName); if (job == null) { String msg = "Cannot find job: " + jobName; throw new MegatronException(msg); } String result = job.getJobType().getName(); if (Constants.DEFAULT_JOB_TYPE.equals(result)) { // use job type in job name if job type not specified in db String[] headTail = StringUtil.splitHeadTail(jobName, "_", false); result = headTail[0]; } return result; } finally { if (dbManager != null) { dbManager.close(); } } } /** * List all priorites to stdout. */ private void listPrio(TypedProperties globalProps) throws MegatronException { DbManager dbManager = null; try { dbManager = DbManager.createDbManager(globalProps); List<Priority> prios = dbManager.getAllPriorities(); System.out.println("+------+----------------------------------------------------------------------------+"); System.out.println("| Prio | Name |"); System.out.println("+------+----------------------------------------------------------------------------+"); for (Priority prio: prios) { System.out.printf("| %4d | %-74s |\n", prio.getPrio(), prio.getName()); } System.out.println("+------+----------------------------------------------------------------------------+"); } finally { if (dbManager != null) { dbManager.close(); } } } private List<IReportGenerator> createReportGenerators(String[] classNames) throws MegatronException { List<IReportGenerator> result = new ArrayList<IReportGenerator>(); for (int i = 0; i < classNames.length; i++) { String className = classNames[i]; if (className.trim().length() == 0) { continue; } try { Class<?> clazz = Class.forName(className); IReportGenerator reportGenerator = (IReportGenerator)clazz.newInstance(); reportGenerator.init(); result.add(reportGenerator); } catch (MegatronException e) { String msg = "Cannot initialize report generator class: " + className; throw new MegatronException(msg, e); } catch (Exception e) { // ClassNotFoundException, InstantiationException, IllegalAccessException String msg = "Cannot instantiate report generator class: " + className; throw new MegatronException(msg, e); } } return result; } }
/* ObjectReferenceCommandSet.java -- class to implement the ObjectReference Command Set Copyright (C) 2005 Free Software Foundation This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.classpath.jdwp.processor; import gnu.classpath.jdwp.JdwpConstants; import gnu.classpath.jdwp.VMVirtualMachine; import gnu.classpath.jdwp.exception.InvalidFieldException; import gnu.classpath.jdwp.exception.JdwpException; import gnu.classpath.jdwp.exception.JdwpInternalErrorException; import gnu.classpath.jdwp.exception.NotImplementedException; import gnu.classpath.jdwp.id.ObjectId; import gnu.classpath.jdwp.id.ReferenceTypeId; import gnu.classpath.jdwp.util.Value; import gnu.classpath.jdwp.util.MethodResult; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; /** * A class representing the ObjectReference Command Set. * * @author Aaron Luchko <[email protected]> */ public class ObjectReferenceCommandSet extends CommandSet { public boolean runCommand(ByteBuffer bb, DataOutputStream os, byte command) throws JdwpException { try { switch (command) { case JdwpConstants.CommandSet.ObjectReference.REFERENCE_TYPE: executeReferenceType(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.GET_VALUES: executeGetValues(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.SET_VALUES: executeSetValues(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.MONITOR_INFO: executeMonitorInfo(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.INVOKE_METHOD: executeInvokeMethod(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.DISABLE_COLLECTION: executeDisableCollection(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.ENABLE_COLLECTION: executeEnableCollection(bb, os); break; case JdwpConstants.CommandSet.ObjectReference.IS_COLLECTED: executeIsCollected(bb, os); break; default: throw new NotImplementedException("Command " + command + " not found in ObjectReference Command Set."); } } catch (IOException ex) { // The DataOutputStream we're using isn't talking to a socket at all // So if we throw an IOException we're in serious trouble throw new JdwpInternalErrorException(ex); } return false; } private void executeReferenceType(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); Object obj = oid.getObject(); Class clazz = obj.getClass(); ReferenceTypeId refId = idMan.getReferenceTypeId(clazz); refId.writeTagged(os); } private void executeGetValues(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); Object obj = oid.getObject(); int numFields = bb.getInt(); os.writeInt(numFields); // Looks pointless but this is the protocol for (int i = 0; i < numFields; i++) { Field field = (Field) idMan.readObjectId(bb).getObject(); try { field.setAccessible(true); // Might be a private field Object value = field.get(obj); Value.writeTaggedValue(os, value); } catch (IllegalArgumentException ex) { // I suppose this would best qualify as an invalid field then throw new InvalidFieldException(ex); } catch (IllegalAccessException ex) { // Since we set it as accessible this really shouldn't happen throw new JdwpInternalErrorException(ex); } } } private void executeSetValues(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); Object obj = oid.getObject(); int numFields = bb.getInt(); for (int i = 0; i < numFields; i++) { Field field = (Field) idMan.readObjectId(bb).getObject(); Object value = Value.getUntaggedObj(bb, field.getType()); try { field.setAccessible(true); // Might be a private field field.set(obj, value); } catch (IllegalArgumentException ex) { // I suppose this would best qualify as an invalid field then throw new InvalidFieldException(ex); } catch (IllegalAccessException ex) { // Since we set it as accessible this really shouldn't happen throw new JdwpInternalErrorException(ex); } } } private void executeMonitorInfo(ByteBuffer bb, DataOutputStream os) throws JdwpException { // This command is optional, determined by VirtualMachines CapabilitiesNew // so we'll leave it till later to implement throw new NotImplementedException( "Command ExecuteMonitorInfo not implemented."); } private void executeInvokeMethod(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); Object obj = oid.getObject(); ObjectId tid = idMan.readObjectId(bb); Thread thread = (Thread) tid.getObject(); ReferenceTypeId rid = idMan.readReferenceTypeId(bb); Class clazz = rid.getType(); ObjectId mid = idMan.readObjectId(bb); Method method = (Method) mid.getObject(); int args = bb.getInt(); Object[] values = new Object[args]; for (int i = 0; i < args; i++) { values[i] = Value.getObj(bb); } int invokeOptions = bb.getInt(); boolean suspend = ((invokeOptions & JdwpConstants.InvokeOptions.INVOKE_SINGLE_THREADED) != 0); if (suspend) { // We must suspend all other running threads first VMVirtualMachine.suspendAllThreads (); } boolean nonVirtual = ((invokeOptions & JdwpConstants.InvokeOptions.INVOKE_NONVIRTUAL) != 0); MethodResult mr = VMVirtualMachine.executeMethod(obj, thread, clazz, method, values, nonVirtual); Object value = mr.getReturnedValue(); Exception exception = mr.getThrownException(); ObjectId eId = idMan.getObjectId(exception); Value.writeTaggedValue(os, value); eId.writeTagged(os); } private void executeDisableCollection(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); oid.disableCollection(); } private void executeEnableCollection(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); oid.enableCollection(); } private void executeIsCollected(ByteBuffer bb, DataOutputStream os) throws JdwpException, IOException { ObjectId oid = idMan.readObjectId(bb); boolean collected = (oid.getReference().get () == null); os.writeBoolean(collected); } }
/* Copyright 2010-present Local Matters, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.localmatters.serializer.util; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.collections.CollectionUtils; import org.localmatters.serializer.test.domain.DummyEnum; import org.localmatters.serializer.test.domain.DummyObject; import org.localmatters.serializer.test.domain.DummyObject.Address; import org.localmatters.serializer.test.domain.DummyObject.Orders; import org.localmatters.serializer.test.domain.ObjectWithGenerics; import org.localmatters.serializer.test.domain.ParameterizedObject; /** * Tests the <code>ReflectionUtils</code> */ public class ReflectionUtilsTest extends TestCase { /** * Tests the instantiation of this class (for code completion) */ public void testInstantiation() { assertNotNull(new ReflectionUtils() {}); } /** * Tests getting the primitive class */ public void testGetPrimitiveClass() { assertSame(boolean.class, ReflectionUtils.getPrimitiveClass(Boolean.class)); assertSame(float.class, ReflectionUtils.getPrimitiveClass(Float.class)); assertSame(long.class, ReflectionUtils.getPrimitiveClass(Long.class)); assertSame(int.class, ReflectionUtils.getPrimitiveClass(Integer.class)); assertSame(short.class, ReflectionUtils.getPrimitiveClass(Short.class)); assertSame(byte.class, ReflectionUtils.getPrimitiveClass(Byte.class)); assertSame(double.class, ReflectionUtils.getPrimitiveClass(Double.class)); assertSame(char.class, ReflectionUtils.getPrimitiveClass(Character.class)); assertNull(ReflectionUtils.getPrimitiveClass(int.class)); assertNull(ReflectionUtils.getPrimitiveClass(String.class)); assertNull(ReflectionUtils.getPrimitiveClass(Date.class)); assertNull(ReflectionUtils.getPrimitiveClass(DummyEnum.class)); assertNull(ReflectionUtils.getPrimitiveClass(DummyObject.class)); assertNull(ReflectionUtils.getPrimitiveClass(ReflectionUtils.class)); assertNull(ReflectionUtils.getPrimitiveClass(Object.class)); } /** * Tests checking whether a class is a primitive number or one of their * equivalent wrapper classes */ public void testIsNumeric() { assertTrue(ReflectionUtils.isNumeric(Float.class)); assertTrue(ReflectionUtils.isNumeric(float.class)); assertTrue(ReflectionUtils.isNumeric(Long.class)); assertTrue(ReflectionUtils.isNumeric(long.class)); assertTrue(ReflectionUtils.isNumeric(Integer.class)); assertTrue(ReflectionUtils.isNumeric(int.class)); assertTrue(ReflectionUtils.isNumeric(Short.class)); assertTrue(ReflectionUtils.isNumeric(short.class)); assertTrue(ReflectionUtils.isNumeric(Double.class)); assertTrue(ReflectionUtils.isNumeric(double.class)); assertTrue(ReflectionUtils.isNumeric(Byte.class)); assertTrue(ReflectionUtils.isNumeric(byte.class)); assertFalse(ReflectionUtils.isNumeric(Boolean.class)); assertFalse(ReflectionUtils.isNumeric(boolean.class)); assertFalse(ReflectionUtils.isNumeric(Character.class)); assertFalse(ReflectionUtils.isNumeric(char.class)); assertFalse(ReflectionUtils.isNumeric(String.class)); assertFalse(ReflectionUtils.isNumeric(Date.class)); assertFalse(ReflectionUtils.isNumeric(DummyEnum.class)); assertFalse(ReflectionUtils.isNumeric(DummyObject.class)); assertFalse(ReflectionUtils.isNumeric(ReflectionUtils.class)); assertFalse(ReflectionUtils.isNumeric(Object.class)); } /** * Tests checking whether a class is the primitive boolean or its Boolean * wrapper */ public void testIsBoolean() { assertTrue(ReflectionUtils.isBoolean(Boolean.class)); assertTrue(ReflectionUtils.isBoolean(boolean.class)); assertFalse(ReflectionUtils.isBoolean(Float.class)); assertFalse(ReflectionUtils.isBoolean(float.class)); assertFalse(ReflectionUtils.isBoolean(Long.class)); assertFalse(ReflectionUtils.isBoolean(long.class)); assertFalse(ReflectionUtils.isBoolean(Integer.class)); assertFalse(ReflectionUtils.isBoolean(int.class)); assertFalse(ReflectionUtils.isBoolean(Short.class)); assertFalse(ReflectionUtils.isBoolean(short.class)); assertFalse(ReflectionUtils.isBoolean(Double.class)); assertFalse(ReflectionUtils.isBoolean(double.class)); assertFalse(ReflectionUtils.isBoolean(Byte.class)); assertFalse(ReflectionUtils.isBoolean(byte.class)); assertFalse(ReflectionUtils.isBoolean(Character.class)); assertFalse(ReflectionUtils.isBoolean(char.class)); assertFalse(ReflectionUtils.isBoolean(String.class)); assertFalse(ReflectionUtils.isBoolean(Date.class)); assertFalse(ReflectionUtils.isBoolean(DummyEnum.class)); assertFalse(ReflectionUtils.isBoolean(DummyObject.class)); assertFalse(ReflectionUtils.isBoolean(ReflectionUtils.class)); assertFalse(ReflectionUtils.isBoolean(Object.class)); } /** * Tests checking whether a class is a primitive or one of their equivalent * wrapper classes */ public void testIsPrimitiveOrWrapper() { assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Float.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(float.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Long.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(long.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Integer.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(int.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Short.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(short.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Double.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(double.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Byte.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(byte.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Boolean.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(boolean.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(Character.class)); assertTrue(ReflectionUtils.isPrimitiveOrWrapper(char.class)); assertFalse(ReflectionUtils.isNumeric(String.class)); assertFalse(ReflectionUtils.isNumeric(Date.class)); assertFalse(ReflectionUtils.isNumeric(DummyEnum.class)); assertFalse(ReflectionUtils.isNumeric(DummyObject.class)); assertFalse(ReflectionUtils.isNumeric(ReflectionUtils.class)); assertFalse(ReflectionUtils.isNumeric(Object.class)); } /** * Tests checking whether the instances of the given class can be represent * by a simple value */ public void testIsSimple() { assertTrue(ReflectionUtils.isSimple(Float.class)); assertTrue(ReflectionUtils.isSimple(float.class)); assertTrue(ReflectionUtils.isSimple(Long.class)); assertTrue(ReflectionUtils.isSimple(long.class)); assertTrue(ReflectionUtils.isSimple(Integer.class)); assertTrue(ReflectionUtils.isSimple(int.class)); assertTrue(ReflectionUtils.isSimple(Short.class)); assertTrue(ReflectionUtils.isSimple(short.class)); assertTrue(ReflectionUtils.isSimple(Double.class)); assertTrue(ReflectionUtils.isSimple(double.class)); assertTrue(ReflectionUtils.isSimple(Byte.class)); assertTrue(ReflectionUtils.isSimple(byte.class)); assertTrue(ReflectionUtils.isSimple(Boolean.class)); assertTrue(ReflectionUtils.isSimple(boolean.class)); assertTrue(ReflectionUtils.isSimple(Character.class)); assertTrue(ReflectionUtils.isSimple(char.class)); assertTrue(ReflectionUtils.isSimple(String.class)); assertTrue(ReflectionUtils.isSimple(Date.class)); assertTrue(ReflectionUtils.isSimple(DummyEnum.class)); assertTrue(ReflectionUtils.isSimple(Locale.class)); assertFalse(ReflectionUtils.isSimple(Object.class)); assertFalse(ReflectionUtils.isSimple(DummyObject.class)); assertFalse(ReflectionUtils.isSimple(ReflectionUtils.class)); } /** * Test getting the type arguments for a type * @throws Exception When the test fails */ public void testGetTypeArgumentsForType() throws Exception { assertNull(ReflectionUtils.getTypeArgumentsForType(String.class)); assertNull(ReflectionUtils.getTypeArgumentsForType(List.class)); assertNull(ReflectionUtils.getTypeArgumentsForType(Map.class)); Type[] types = ReflectionUtils.getTypeArgumentsForType(ParameterizedObject.class); assertNotNull(types); assertEquals(1, types.length); assertSame(String.class, types[0]); Class<?> cl = ObjectWithGenerics.class; Method method = cl.getMethod("getList", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNull(types); method = cl.getMethod("getListOfString", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(1, types.length); assertSame(String.class, types[0]); method = cl.getMethod("getListOfListOfString", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(1, types.length); assertTrue(types[0] instanceof ParameterizedType); ParameterizedType type = (ParameterizedType) types[0]; assertSame(List.class, type.getRawType()); types = ReflectionUtils.getTypeArgumentsForType(type); assertNotNull(types); assertEquals(1, types.length); assertSame(String.class, types[0]); method = cl.getMethod("getListOfParameterizedObject", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(1, types.length); assertTrue(types[0] instanceof Class<?>); Class<?> klass = (Class<?>) types[0]; types = ReflectionUtils.getTypeArgumentsForType(klass); assertNotNull(types); assertEquals(1, types.length); assertSame(String.class, types[0]); method = cl.getMethod("getListOfMapOfStringAndList", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(1, types.length); assertTrue(types[0] instanceof ParameterizedType); type = (ParameterizedType) types[0]; assertSame(Map.class, type.getRawType()); types = ReflectionUtils.getTypeArgumentsForType(type); assertNotNull(types); assertEquals(2, types.length); assertSame(String.class, types[0]); assertSame(List.class, types[1]); method = cl.getMethod("getMap", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(2, types.length); assertFalse(types[0] instanceof Class<?>); assertFalse(types[0] instanceof ParameterizedType); assertFalse(types[1] instanceof Class<?>); assertFalse(types[1] instanceof ParameterizedType); method = cl.getMethod("getMapOfStringAndDouble", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(2, types.length); assertTrue(types[0] instanceof Class<?>); assertSame(String.class, types[0]); assertTrue(types[1] instanceof Class<?>); assertSame(Double.class, types[1]); method = cl.getMethod("getArray", (Class<?>[]) null); types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType()); assertNotNull(types); assertEquals(1, types.length); assertTrue(types[0] instanceof Class<?>); assertSame(String.class, types[0]); } /** * Tests retrieving the getter methods of a class */ public void testGetGetters() { Collection<Method> getters = ReflectionUtils.getGetters(DummyObject.class); assertEquals(7, CollectionUtils.size(getters)); Iterator<Method> itr = getters.iterator(); assertEquals("getAddresses", itr.next().getName()); assertEquals("getAddressesRaw", itr.next().getName()); assertEquals("getId", itr.next().getName()); assertEquals("getName", itr.next().getName()); assertEquals("getOrders", itr.next().getName()); assertEquals("getOrdersByAddresses", itr.next().getName()); assertEquals("getOrdersList", itr.next().getName()); assertFalse(itr.hasNext()); getters = ReflectionUtils.getGetters(Address.class); assertEquals(5, CollectionUtils.size(getters)); itr = getters.iterator(); assertEquals("getCity", itr.next().getName()); assertEquals("getState", itr.next().getName()); assertEquals("getStreet", itr.next().getName()); assertEquals("getZ", itr.next().getName()); assertEquals("getZip", itr.next().getName()); assertFalse(itr.hasNext()); getters = ReflectionUtils.getGetters(Orders.class); assertEquals(1, CollectionUtils.size(getters)); itr = getters.iterator(); assertEquals("isEmpty", itr.next().getName()); assertFalse(itr.hasNext()); } /** * Tests retrieving the getter methods field name */ public void testGetGetterFieldName() throws Exception { Collection<Method> getters = ReflectionUtils.getGetters(Address.class); assertEquals(5, CollectionUtils.size(getters)); Iterator<Method> itr = getters.iterator(); assertEquals("city", ReflectionUtils.getGetterFieldName(itr.next())); assertEquals("state", ReflectionUtils.getGetterFieldName(itr.next())); assertEquals("street", ReflectionUtils.getGetterFieldName(itr.next())); assertEquals("z", ReflectionUtils.getGetterFieldName(itr.next())); assertEquals("zip", ReflectionUtils.getGetterFieldName(itr.next())); assertFalse(itr.hasNext()); assertNull(ReflectionUtils.getGetterFieldName(Address.class.getMethod("getClass", (Class<?>[]) null))); assertNull(ReflectionUtils.getGetterFieldName(Address.class.getMethod("toString", (Class<?>[]) null))); } }
package za.org.grassroot.webapp.model.rest; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.common.collect.Sets; import za.org.grassroot.core.domain.Event; import za.org.grassroot.core.domain.Notification; import za.org.grassroot.core.domain.Task; import za.org.grassroot.core.domain.Todo; import za.org.grassroot.core.domain.notification.EventNotification; import za.org.grassroot.core.domain.notification.TodoNotification; import za.org.grassroot.core.enums.EventLogType; import za.org.grassroot.core.enums.NotificationDetailedType; import za.org.grassroot.core.enums.TaskType; import za.org.grassroot.core.util.DateTimeUtil; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by paballo on 2016/04/13. */ @JsonInclude(JsonInclude.Include.NON_NULL) public class NotificationDTO { // private static final Logger logger = LoggerFactory.getLogger(NotificationDTO.class); private final String uid; // i.e., uid of the notification itself private final String notificationType; private final boolean delivered; private final boolean read; private final boolean viewedAndroid; private final String groupUid; private final String title; private final String imageUrl; private final String defaultImage; private String entityUid; // i.e., uid of the event/etc that the logbook was attached to private String message; private String createdDatetime; private String deadlineDateTime; private String entityType; private String changeType; // should start including join request notifications & rsvp totals at some point public static final Set<NotificationDetailedType> notificationsForAndroidList = Collections.unmodifiableSet(Sets.newHashSet( NotificationDetailedType.TODO_INFO, NotificationDetailedType.TODO_REMINDER, NotificationDetailedType.EVENT_INFO, NotificationDetailedType.EVENT_CHANGED, NotificationDetailedType.EVENT_CANCELLED, NotificationDetailedType.EVENT_REMINDER, NotificationDetailedType.VOTE_RESULTS, NotificationDetailedType.MEETING_RSVP_TOTALS)); private final static Pattern dialMatcher = Pattern.compile("([\\.,]\\s[Dd].+\\*134\\*1994#.+)"); public static boolean isNotificationOfTypeForDTO(Notification notification) { return notificationsForAndroidList.contains(notification.getNotificationDetailedType()); } public static NotificationDTO convertToDto(Notification notification) { if (notification instanceof EventNotification) { Event event = ((EventNotification) notification).getEvent(); return new NotificationDTO(notification, event); } else if(notification instanceof TodoNotification){ Todo todo = ((TodoNotification) notification).getTodo(); return new NotificationDTO(notification,todo); } else { throw new IllegalArgumentException("Error! Notification DTO called on unsupported notification type"); } } private NotificationDTO(Notification notification, Task task) { this.uid = notification.getUid(); this.createdDatetime = convertInstantToStringISO(notification.getCreatedDateTime()); this.delivered = notification.isDelivered(); this.read = notification.isRead(); this.viewedAndroid = notification.isViewedOnAndroid(); this.notificationType = notification.getNotificationDetailedType().toString(); this.title = task.getAncestorGroup().getGroupName(); this.groupUid = task.getAncestorGroup().getUid(); this.imageUrl = task.getAncestorGroup().getImageUrl(); this.defaultImage = task.getAncestorGroup().getDefaultImage().toString(); } public NotificationDTO(Notification notification, Event event) { this(notification, (Task) event); this.entityUid = event.getUid(); this.deadlineDateTime = convertInstantToStringISO(event.getDeadlineTime()); this.message = stripDialSuffix(stripTitleFromMessage(title, notification.getMessage())); this.entityType = event.getEventType().toString(); // todo: something strange with a single notification null event log appeared on staging server (cannot reproduce) ... introducing this until certain fixed this.changeType = notification.getEventLog() == null ? EventLogType.CREATED.toString() : notification.getEventLog().getEventLogType().toString(); } public NotificationDTO(Notification notification, Todo todo){ this(notification, (Task) todo); this.entityUid = todo.getUid(); this.deadlineDateTime = convertInstantToStringISO(todo.getDeadlineTime()); final String originalMessage = (notification.getMessage() != null) ? notification.getMessage() : notification.getTodoLog().getMessage(); this.message = stripDialSuffix(stripTitleFromMessage(title, originalMessage)); this.entityType = TaskType.TODO.toString(); this.changeType = notification.getTodoLog().getType().toString(); } private String convertInstantToStringISO(Instant instant) { return DateTimeUtil.convertToUserTimeZone(instant, DateTimeUtil.getSAST()).format(DateTimeFormatter.ISO_DATE_TIME); } private String stripTitleFromMessage(final String title, final String message) { if (!message.contains(title)) { return message; } else { final Pattern groupNamePatter = Pattern.compile("^" + title + "\\s?:\\s+?"); final Matcher m = groupNamePatter.matcher(message); if (m.find()) { return message.substring(m.end()); } else { return message; } } } private String stripDialSuffix(final String message) { final Matcher m = dialMatcher.matcher(message); if (m.find()) { return message.substring(0, m.start()); } else { return message; } } public String getEntityType() { return entityType; } public String getUid() { return uid; } public String getEntityUid() { return entityUid; } public String getTitle() { return title; } public String getMessage() { return message; } public String getCreatedDatetime() { return createdDatetime; } public String getNotificationType() { return notificationType; } public boolean isDelivered() { return delivered; } public boolean isRead() { return read; } public boolean isViewedAndroid() { return viewedAndroid; } public String getGroupUid() { return groupUid; } public String getDeadlineDateTime() { return deadlineDateTime; } public String getChangeType() { return changeType; } public String getImageUrl() { return imageUrl; } public String getDefaultImage() { return defaultImage; } }
/* * Copyright 2019 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.common.hbase; import com.google.common.collect.Lists; import com.navercorp.pinpoint.common.hbase.parallel.ParallelResultScanner; import com.navercorp.pinpoint.common.hbase.parallel.ScanTaskException; import com.navercorp.pinpoint.common.profiler.concurrent.ExecutorFactory; import com.navercorp.pinpoint.common.profiler.concurrent.PinpointThreadFactory; import com.navercorp.pinpoint.common.util.StopWatch; import com.sematext.hbase.wd.AbstractRowKeyDistributor; import com.sematext.hbase.wd.DistributedScanner; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * @author emeroad * @author HyunGil Jeong * @author minwoo.jung */ public class HbaseTemplate2 extends HbaseAccessor implements HbaseOperations2, InitializingBean, DisposableBean { private static final int DEFAULT_MAX_THREADS_FOR_PARALLEL_SCANNER = 128; private static final int DEFAULT_MAX_THREADS_PER_PARALLEL_SCAN = 1; private static final long DEFAULT_DESTORY_TIMEOUT = 2000; private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final boolean debugEnabled = this.logger.isDebugEnabled(); private final AtomicBoolean isClose = new AtomicBoolean(false); private ExecutorService executor; private boolean enableParallelScan = false; private int maxThreads = DEFAULT_MAX_THREADS_FOR_PARALLEL_SCANNER; private int maxThreadsPerParallelScan = DEFAULT_MAX_THREADS_PER_PARALLEL_SCAN; private HBaseAsyncOperation asyncOperation = DisabledHBaseAsyncOperation.INSTANCE; public HbaseTemplate2() { } private Table getTable(TableName tableName) { return getTableFactory().getTable(tableName); } public void setEnableParallelScan(boolean enableParallelScan) { this.enableParallelScan = enableParallelScan; } public void setMaxThreads(int maxThreads) { this.maxThreads = maxThreads; } public void setMaxThreadsPerParallelScan(int maxThreadsPerParallelScan) { this.maxThreadsPerParallelScan = maxThreadsPerParallelScan; } public void setAsyncOperation(HBaseAsyncOperation asyncOperation) { this.asyncOperation = Objects.requireNonNull(asyncOperation, "asyncOperation"); } @Override public void afterPropertiesSet() { Configuration configuration = getConfiguration(); Objects.requireNonNull(configuration, "configuration is required"); Objects.requireNonNull(getTableFactory(), "tableFactory is required"); PinpointThreadFactory parallelScannerThreadFactory = new PinpointThreadFactory("Pinpoint-parallel-scanner", true); if (this.maxThreadsPerParallelScan <= 1) { this.enableParallelScan = false; this.executor = Executors.newSingleThreadExecutor(parallelScannerThreadFactory); } else { this.executor = ExecutorFactory.newFixedThreadPool(this.maxThreads, 1024, parallelScannerThreadFactory); } } @Override public void destroy() throws Exception { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (isClose.compareAndSet(false, true)) { logger.info("HBaseTemplate2.destroy()"); final ExecutorService executor = this.executor; if (executor != null) { executor.shutdown(); try { executor.awaitTermination(DEFAULT_DESTORY_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } long remainingTime = Math.max(DEFAULT_DESTORY_TIMEOUT - stopWatch.stop(), 100); awaitAsyncPutOpsCleared(remainingTime, 50); } } private boolean awaitAsyncPutOpsCleared(long waitTimeout, long checkUnitTime) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); while (true) { Long currentPutOpsCount = asyncOperation.getCurrentOpsCount(); if (logger.isWarnEnabled()) { logger.warn("count {}", currentPutOpsCount); } if (currentPutOpsCount <= 0L) { return true; } if (stopWatch.stop() > waitTimeout) { return false; } try { Thread.sleep(checkUnitTime); } catch (InterruptedException e) { // ignore } } } private void assertAccessAvailable() { if (isClose.get()) { throw new HBaseAccessException("Already closed."); } } @Override public <T> T find(TableName tableName, String family, final ResultsExtractor<T> action) { Scan scan = new Scan(); scan.addFamily(family.getBytes(getCharset())); return find(tableName, scan, action); } @Override public <T> T find(TableName tableName, String family, String qualifier, final ResultsExtractor<T> action) { Scan scan = new Scan(); scan.addColumn(family.getBytes(getCharset()), qualifier.getBytes(getCharset())); return find(tableName, scan, action); } @Override public <T> T find(TableName tableName, final Scan scan, final ResultsExtractor<T> action) { assertAccessAvailable(); return execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { final ResultScanner scanner = table.getScanner(scan); try { return action.extractData(scanner); } finally { scanner.close(); } } }); } @Override public <T> List<T> find(TableName tableName, String family, final RowMapper<T> action) { Scan scan = new Scan(); scan.addFamily(family.getBytes(getCharset())); return find(tableName, scan, action); } @Override public <T> List<T> find(TableName tableName, String family, String qualifier, final RowMapper<T> action) { Scan scan = new Scan(); scan.addColumn(family.getBytes(getCharset()), qualifier.getBytes(getCharset())); return find(tableName, scan, action); } @Override public <T> List<T> find(TableName tableName, final Scan scan, final RowMapper<T> action) { return find(tableName, scan, new RowMapperResultsExtractor<>(action)); } @Override public <T> T get(TableName tableName, String rowName, final RowMapper<T> mapper) { return get(tableName, rowName, null, null, mapper); } @Override public <T> T get(TableName tableName, String rowName, String familyName, final RowMapper<T> mapper) { return get(tableName, rowName, familyName, null, mapper); } @Override public <T> T get(TableName tableName, final String rowName, final String familyName, final String qualifier, final RowMapper<T> mapper) { assertAccessAvailable(); return execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { Get get = new Get(rowName.getBytes(getCharset())); if (familyName != null) { byte[] family = familyName.getBytes(getCharset()); if (qualifier != null) { get.addColumn(family, qualifier.getBytes(getCharset())); } else { get.addFamily(family); } } Result result = table.get(get); return mapper.mapRow(result, 0); } }); } @Override public <T> T get(TableName tableName, byte[] rowName, RowMapper<T> mapper) { return get(tableName, rowName, null, null, mapper); } @Override public <T> T get(TableName tableName, byte[] rowName, byte[] familyName, RowMapper<T> mapper) { return get(tableName, rowName, familyName, null, mapper); } @Override public <T> T get(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final RowMapper<T> mapper) { assertAccessAvailable(); return execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { Get get = new Get(rowName); if (familyName != null) { if (qualifier != null) { get.addColumn(familyName, qualifier); } else { get.addFamily(familyName); } } Result result = table.get(get); return mapper.mapRow(result, 0); } }); } @Override public <T> T get(TableName tableName, final Get get, final RowMapper<T> mapper) { assertAccessAvailable(); return execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { Result result = table.get(get); return mapper.mapRow(result, 0); } }); } @Override public <T> List<T> get(TableName tableName, final List<Get> getList, final RowMapper<T> mapper) { assertAccessAvailable(); return execute(tableName, new TableCallback<List<T>>() { @Override public List<T> doInTable(Table table) throws Throwable { Result[] result = table.get(getList); List<T> list = new ArrayList<>(result.length); for (int i = 0; i < result.length; i++) { T t = mapper.mapRow(result[i], i); list.add(t); } return list; } }); } @Override public void put(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final byte[] value) { put(tableName, rowName, familyName, qualifier, null, value); } @Override public void put(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final Long timestamp, final byte[] value) { assertAccessAvailable(); execute(tableName, new TableCallback() { @Override public Object doInTable(Table table) throws Throwable { Put put = createPut(rowName, familyName, timestamp, qualifier, value); table.put(put); return null; } }); } @Override public <T> void put(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final T value, final ValueMapper<T> mapper) { put(tableName, rowName, familyName, qualifier, null, value, mapper); } @Override public <T> void put(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final Long timestamp, final T value, final ValueMapper<T> mapper) { assertAccessAvailable(); execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { byte[] bytes = mapper.mapValue(value); Put put = createPut(rowName, familyName, timestamp, qualifier, bytes); table.put(put); return null; } }); } @Override public void put(TableName tableName, final Put put) { assertAccessAvailable(); execute(tableName, new TableCallback() { @Override public Object doInTable(Table table) throws Throwable { table.put(put); return null; } }); } @Override public void put(TableName tableName, final List<Put> puts) { assertAccessAvailable(); execute(tableName, new TableCallback() { @Override public Object doInTable(Table table) throws Throwable { table.put(puts); return null; } }); } @Override public boolean asyncPut(TableName tableName, byte[] rowName, byte[] familyName, byte[] qualifier, byte[] value) { return asyncPut(tableName, rowName, familyName, qualifier, null, value); } @Override public boolean asyncPut(TableName tableName, byte[] rowName, byte[] familyName, byte[] qualifier, Long timestamp, byte[] value) { Put put = createPut(rowName, familyName, timestamp, qualifier, value); return asyncPut(tableName, put); } @Override public <T> boolean asyncPut(TableName tableName, byte[] rowName, byte[] familyName, byte[] qualifier, T value, ValueMapper<T> mapper) { return asyncPut(tableName, rowName, familyName, qualifier, null, value, mapper); } @Override public <T> boolean asyncPut(TableName tableName, byte[] rowName, byte[] familyName, byte[] qualifier, Long timestamp, T value, ValueMapper<T> mapper) { byte[] bytes = mapper.mapValue(value); Put put = createPut(rowName, familyName, timestamp, qualifier, bytes); return asyncPut(tableName, put); } @Override public boolean asyncPut(TableName tableName, Put put) { assertAccessAvailable(); if (asyncOperation.isAvailable()) { return asyncOperation.put(tableName, put); } else { put(tableName, put); return true; } } @Override public List<Put> asyncPut(TableName tableName, List<Put> puts) { assertAccessAvailable(); if (asyncOperation.isAvailable()) { return asyncOperation.put(tableName, puts); } else { put(tableName, puts); return Collections.emptyList(); } } private Put createPut(byte[] rowName, byte[] familyName, Long timestamp, byte[] qualifier, byte[] value) { Put put = new Put(rowName); if (familyName != null) { if (timestamp == null) { put.addColumn(familyName, qualifier, value); } else { put.addColumn(familyName, qualifier, timestamp, value); } } return put; } @Override public void delete(TableName tableName, final Delete delete) { assertAccessAvailable(); execute(tableName, new TableCallback() { @Override public Object doInTable(Table table) throws Throwable { table.delete(delete); return null; } }); } @Override public void delete(TableName tableName, final List<Delete> deletes) { assertAccessAvailable(); execute(tableName, new TableCallback() { @Override public Object doInTable(Table table) throws Throwable { table.delete(deletes); return null; } }); } @Override public <T> List<T> find(TableName tableName, final List<Scan> scanList, final ResultsExtractor<T> action) { assertAccessAvailable(); return execute(tableName, new TableCallback<List<T>>() { @Override public List<T> doInTable(Table table) throws Throwable { List<T> result = new ArrayList<>(scanList.size()); for (Scan scan : scanList) { final ResultScanner scanner = table.getScanner(scan); try { T t = action.extractData(scanner); result.add(t); } finally { scanner.close(); } } return result; } }); } @Override public <T> List<List<T>> find(TableName tableName, List<Scan> scanList, RowMapper<T> action) { return find(tableName, scanList, new RowMapperResultsExtractor<>(action)); } @Override public <T> List<T> findParallel(final TableName tableName, final List<Scan> scans, final ResultsExtractor<T> action) { assertAccessAvailable(); if (!this.enableParallelScan || scans.size() == 1) { return find(tableName, scans, action); } List<T> results = new ArrayList<>(scans.size()); List<Callable<T>> callables = new ArrayList<>(scans.size()); for (final Scan scan : scans) { callables.add(new Callable<T>() { @Override public T call() throws Exception { return execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { final ResultScanner scanner = table.getScanner(scan); try { return action.extractData(scanner); } finally { scanner.close(); } } }); } }); } List<List<Callable<T>>> callablePartitions = Lists.partition(callables, this.maxThreadsPerParallelScan); for (List<Callable<T>> callablePartition : callablePartitions) { try { List<Future<T>> futures = this.executor.invokeAll(callablePartition); for (Future<T> future : futures) { results.add(future.get()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("interrupted while findParallel [{}].", tableName); return Collections.emptyList(); } catch (ExecutionException e) { logger.warn("findParallel [{}], error : {}", tableName, e); return Collections.emptyList(); } } return results; } @Override public <T> List<List<T>> findParallel(TableName tableName, final List<Scan> scans, final RowMapper<T> action) { return findParallel(tableName, scans, new RowMapperResultsExtractor<>(action)); } @Override public <T> List<T> find(TableName tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final RowMapper<T> action) { final ResultsExtractor<List<T>> resultsExtractor = new RowMapperResultsExtractor<>(action); return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor); } @Override public <T> List<T> find(TableName tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final int limit, final RowMapper<T> action) { final ResultsExtractor<List<T>> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit); return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor); } @Override public <T> List<T> find(TableName tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, int limit, final RowMapper<T> action, final LimitEventHandler limitEventHandler) { final LimitRowMapperResultsExtractor<T> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit, limitEventHandler); return executeDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor); } @Override public <T> T find(TableName tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final ResultsExtractor<T> action) { return executeDistributedScan(tableName, scan, rowKeyDistributor, action); } protected final <T> T executeDistributedScan(TableName tableName, final Scan scan, final AbstractRowKeyDistributor rowKeyDistributor, final ResultsExtractor<T> action) { assertAccessAvailable(); return execute(tableName, new TableCallback<T>() { @Override public T doInTable(Table table) throws Throwable { StopWatch watch = null; if (debugEnabled) { watch = new StopWatch(); watch.start(); } final ResultScanner[] splitScanners = splitScan(table, scan, rowKeyDistributor); final ResultScanner scanner = new DistributedScanner(rowKeyDistributor, splitScanners); if (debugEnabled) { logger.debug("DistributedScanner createTime: {}ms", watch.stop()); watch.start(); } try { return action.extractData(scanner); } finally { scanner.close(); if (debugEnabled) { logger.debug("DistributedScanner scanTime: {}ms", watch.stop()); } } } }); } private ResultScanner[] splitScan(Table table, Scan originalScan, AbstractRowKeyDistributor rowKeyDistributor) throws IOException { Scan[] scans = rowKeyDistributor.getDistributedScans(originalScan); final int length = scans.length; for (int i = 0; i < length; i++) { Scan scan = scans[i]; // other properties are already set upon construction scan.setId(scan.getId() + "-" + i); } ResultScanner[] scanners = new ResultScanner[length]; boolean success = false; try { for (int i = 0; i < length; i++) { scanners[i] = table.getScanner(scans[i]); } success = true; } finally { if (!success) { closeScanner(scanners); } } return scanners; } private void closeScanner(ResultScanner[] scannerList) { for (ResultScanner scanner : scannerList) { if (scanner != null) { try { scanner.close(); } catch (Exception e) { logger.warn("Scanner.close() error Caused:{}", e.getMessage(), e); } } } } @Override public <T> List<T> findParallel(TableName tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, RowMapper<T> action, int numParallelThreads) { if (!this.enableParallelScan || numParallelThreads <= 1) { // use DistributedScanner if parallel scan is disabled or if called to use a single thread return find(tableName, scan, rowKeyDistributor, action); } else { int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan; final ResultsExtractor<List<T>> resultsExtractor = new RowMapperResultsExtractor<>(action); return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed); } } @Override public <T> List<T> findParallel(TableName tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, int limit, RowMapper<T> action, int numParallelThreads) { if (!this.enableParallelScan || numParallelThreads <= 1) { // use DistributedScanner if parallel scan is disabled or if called to use a single thread return find(tableName, scan, rowKeyDistributor, limit, action); } else { int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan; final ResultsExtractor<List<T>> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit); return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed); } } @Override public <T> List<T> findParallel(TableName tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, int limit, RowMapper<T> action, LimitEventHandler limitEventHandler, int numParallelThreads) { if (!this.enableParallelScan || numParallelThreads <= 1) { // use DistributedScanner if parallel scan is disabled or if called to use a single thread return find(tableName, scan, rowKeyDistributor, limit, action, limitEventHandler); } else { int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan; final LimitRowMapperResultsExtractor<T> resultsExtractor = new LimitRowMapperResultsExtractor<>(action, limit, limitEventHandler); return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, resultsExtractor, numThreadsUsed); } } @Override public <T> T findParallel(TableName tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> action, int numParallelThreads) { if (!this.enableParallelScan || numParallelThreads <= 1) { // use DistributedScanner if parallel scan is disabled or if called to use a single thread return find(tableName, scan, rowKeyDistributor, action); } else { int numThreadsUsed = numParallelThreads < this.maxThreadsPerParallelScan ? numParallelThreads : this.maxThreadsPerParallelScan; return executeParallelDistributedScan(tableName, scan, rowKeyDistributor, action, numThreadsUsed); } } protected final <T> T executeParallelDistributedScan(TableName tableName, Scan scan, AbstractRowKeyDistributor rowKeyDistributor, ResultsExtractor<T> action, int numParallelThreads) { assertAccessAvailable(); try { StopWatch watch = null; if (debugEnabled) { watch = new StopWatch(); watch.start(); } ParallelResultScanner scanner = new ParallelResultScanner(tableName, this, this.executor, scan, rowKeyDistributor, numParallelThreads); if (debugEnabled) { logger.debug("ParallelDistributedScanner createTime: {}ms", watch.stop()); watch.start(); } try { return action.extractData(scanner); } finally { scanner.close(); if (debugEnabled) { logger.debug("ParallelDistributedScanner scanTime: {}ms", watch.stop()); } } } catch (Throwable th) { Throwable throwable = th; if (th instanceof ScanTaskException) { throwable = th.getCause(); } if (throwable instanceof Error) { throw ((Error) th); } if (throwable instanceof RuntimeException) { throw ((RuntimeException) th); } throw new HbaseSystemException((Exception) throwable); } } @Override public Result increment(TableName tableName, final Increment increment) { assertAccessAvailable(); return execute(tableName, new TableCallback<Result>() { @Override public Result doInTable(Table table) throws Throwable { return table.increment(increment); } }); } @Override public List<Result> increment(final TableName tableName, final List<Increment> incrementList) { assertAccessAvailable(); return execute(tableName, new TableCallback<List<Result>>() { @Override public List<Result> doInTable(Table table) throws Throwable { final List<Result> resultList = new ArrayList<>(incrementList.size()); Exception lastException = null; for (Increment increment : incrementList) { try { Result result = table.increment(increment); resultList.add(result); } catch (IOException e) { logger.warn("{} increment error Caused:{}", tableName, e.getMessage(), e); lastException = e; } } if (lastException != null) { throw lastException; } return resultList; } }); } @Override public long incrementColumnValue(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final long amount) { assertAccessAvailable(); return execute(tableName, new TableCallback<Long>() { @Override public Long doInTable(Table table) throws Throwable { return table.incrementColumnValue(rowName, familyName, qualifier, amount); } }); } @Override public long incrementColumnValue(TableName tableName, final byte[] rowName, final byte[] familyName, final byte[] qualifier, final long amount, final boolean writeToWAL) { assertAccessAvailable(); return execute(tableName, new TableCallback<Long>() { @Override public Long doInTable(Table table) throws Throwable { return table.incrementColumnValue(rowName, familyName, qualifier, amount, writeToWAL? Durability.SKIP_WAL: Durability.USE_DEFAULT); } }); } @Override public <T> T execute(TableName tableName, TableCallback<T> action) { Objects.requireNonNull(tableName, "tableName"); Objects.requireNonNull(action, "action"); assertAccessAvailable(); Table table = getTable(tableName); try { T result = action.doInTable(table); return result; } catch (Throwable e) { if (e instanceof Error) { throw ((Error) e); } if (e instanceof RuntimeException) { throw ((RuntimeException) e); } throw new HbaseSystemException((Exception) e); } finally { releaseTable(table); } } private void releaseTable(Table table) { getTableFactory().releaseTable(table); } }
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.rdfservice.filter; import static org.junit.Assert.assertEquals; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Before; import org.junit.Test; import stubs.org.apache.jena.rdf.model.LiteralStub; import org.apache.jena.rdf.model.Literal; import edu.cornell.mannlib.vitro.testing.AbstractTestClass; /** * This is the matching order we expect to see: * * <pre> * exact match to preferred, by order. * partial match to preferred, by order. * vanilla or null (no language) * no match * </pre> */ public class LanguageFilteringRDFServiceTest extends AbstractTestClass { private static final Log log = LogFactory .getLog(LanguageFilteringRDFServiceTest.class); private static final String COLLATOR_CLASSNAME = "edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringRDFService$RowIndexedLiteralSortByLang"; private static final String RIL_CLASSNAME = "edu.cornell.mannlib.vitro.webapp.rdfservice.filter.LanguageFilteringRDFService$RowIndexedLiteral"; private LanguageFilteringRDFService filteringRDFService; private List<Object> listOfRowIndexedLiterals; private int literalIndex; private List<String> preferredLanguages; private List<String> availableLanguages; private List<String> expectedSortOrders; @Before public void setup() { // setLoggerLevel(this.getClass(), Level.DEBUG); // setLoggerLevel(LanguageFilteringRDFService.class, Level.DEBUG); } // ---------------------------------------------------------------------- // The tests // ---------------------------------------------------------------------- @Test public void singleMatch() { preferredLanguages = list("en-US"); availableLanguages = list("en-US"); expectedSortOrders = list("en-US"); testArbitraryOrder(); } @Test public void singleNoMatch() { preferredLanguages = list("en-US"); availableLanguages = list("es-MX"); expectedSortOrders = list("es-MX"); testArbitraryOrder(); } @Test public void doubleMatch() { preferredLanguages = list("en-US", "es-MX"); availableLanguages = list("en-US", "es-MX"); expectedSortOrders = list("en-US", "es-MX"); testBothWays(); } @Test public void noMatches() { preferredLanguages = list("es-MX"); availableLanguages = list("en-US", "fr-FR"); expectedSortOrders = list("en-US", "fr-FR"); testArbitraryOrder(); } @Test public void partialMatches() { preferredLanguages = list("en", "es"); availableLanguages = list("en-US", "es-MX"); expectedSortOrders = list("en-US", "es-MX"); testBothWays(); } @Test public void matchIsBetterThanNoMatch() { preferredLanguages = list("en-US", "es-MX"); availableLanguages = list("en-US", "fr-FR"); expectedSortOrders = list("en-US", "fr-FR"); testBothWays(); } @Test public void matchIsBetterThanPartialMatch() { preferredLanguages = list("es-ES", "en-US"); availableLanguages = list("en-US", "es-MX"); expectedSortOrders = list("en-US", "es-MX"); testBothWays(); } @Test public void exactMatchIsBetterThanPartialMatch() { preferredLanguages = list("es"); availableLanguages = list("es", "es-MX"); expectedSortOrders = list("es", "es-MX"); testBothWays(); } @Test public void matchIsBetterThanVanilla() { preferredLanguages = list("en-US"); availableLanguages = list("en-US", ""); expectedSortOrders = list("en-US", ""); testBothWays(); } @Test public void partialMatchIsBetterThanVanilla() { preferredLanguages = list("es-MX"); availableLanguages = list("es-ES", ""); expectedSortOrders = list("es-ES", ""); testBothWays(); } @Test public void vanillaIsBetterThanNoMatch() { preferredLanguages = list("es-MX"); availableLanguages = list("en-US", ""); expectedSortOrders = list("", "en-US"); testBothWays(); } @Test public void omnibus() { preferredLanguages = list("es-MX", "es", "en-UK", "es-PE", "fr"); availableLanguages = list("es-MX", "es", "fr", "es-ES", "fr-FR", "", "de-DE"); expectedSortOrders = list("es-MX", "es", "fr", "es-ES", "fr-FR", "", "de-DE"); testBothWays(); } // ---------------------------------------------------------------------- // Helper methods // ---------------------------------------------------------------------- /** * Sort the available languages as they are presented. Then reverse them and * sort again. */ private void testBothWays() { createLanguageFilter(); buildListOfLiterals(); sortListOfLiterals(); assertLanguageOrder("sort literals"); buildReversedListOfLiterals(); sortListOfLiterals(); assertLanguageOrder("sort reversed literals"); } /** * Sort the available languages, without caring what the eventual sorted * order is. Really, this is just a test to see that no exceptions are * thrown, and no languages are "lost in translation". */ private void testArbitraryOrder() { createLanguageFilter(); buildListOfLiterals(); sortListOfLiterals(); assertLanguages("sort literals"); buildReversedListOfLiterals(); sortListOfLiterals(); assertLanguages("sort reversed literals"); } private List<String> list(String... strings) { return new ArrayList<String>(Arrays.asList(strings)); } private void createLanguageFilter() { filteringRDFService = new LanguageFilteringRDFService(null, preferredLanguages); } private void buildListOfLiterals() { List<Object> list = new ArrayList<Object>(); for (String language : availableLanguages) { list.add(buildRowIndexedLiteral(language)); } listOfRowIndexedLiterals = list; } private void buildReversedListOfLiterals() { List<Object> list = new ArrayList<Object>(); for (String language : availableLanguages) { list.add(0, buildRowIndexedLiteral(language)); } listOfRowIndexedLiterals = list; } private void sortListOfLiterals() { log.debug("before sorting: " + languagesFromLiterals(listOfRowIndexedLiterals)); Comparator<Object> comparator = buildRowIndexedLiteralSortByLang(); listOfRowIndexedLiterals.sort(comparator); } private void assertLanguageOrder(String message) { List<String> expectedLanguages = expectedSortOrders; log.debug("expected order: " + expectedLanguages); List<String> actualLanguages = languagesFromLiterals(listOfRowIndexedLiterals); log.debug("actual order: " + actualLanguages); assertEquals(message, expectedLanguages, actualLanguages); } private void assertLanguages(String message) { Set<String> expectedLanguages = new HashSet<String>(expectedSortOrders); log.debug("expected languages: " + expectedLanguages); Set<String> actualLanguages = new HashSet<String>( languagesFromLiterals(listOfRowIndexedLiterals)); log.debug("actual languages: " + actualLanguages); assertEquals(message, expectedLanguages, actualLanguages); } private List<String> languagesFromLiterals(List<Object> literals) { List<String> actualLanguages = new ArrayList<String>(); for (Object ril : literals) { actualLanguages.add(getLanguageFromRowIndexedLiteral(ril)); } return actualLanguages; } // ---------------------------------------------------------------------- // Reflection methods to get around "private" declarations. // ---------------------------------------------------------------------- private Object buildRowIndexedLiteral(String language) { try { Class<?> clazz = Class.forName(RIL_CLASSNAME); Class<?>[] argTypes = { LanguageFilteringRDFService.class, Literal.class, Integer.TYPE }; Constructor<?> constructor = clazz.getDeclaredConstructor(argTypes); constructor.setAccessible(true); Literal l = new LiteralStub(language); int i = literalIndex++; return constructor.newInstance(filteringRDFService, l, i); } catch (Exception e) { throw new RuntimeException( "Could not create a row-indexed literal", e); } } @SuppressWarnings("unchecked") private Comparator<Object> buildRowIndexedLiteralSortByLang() { try { Class<?> clazz = Class.forName(COLLATOR_CLASSNAME); Class<?>[] argTypes = { LanguageFilteringRDFService.class, List.class }; Constructor<?> constructor = clazz.getDeclaredConstructor(argTypes); constructor.setAccessible(true); return (Comparator<Object>) constructor .newInstance(filteringRDFService, new AcceptableLanguages( preferredLanguages)); } catch (Exception e) { throw new RuntimeException("Could not create a collator", e); } } private String getLanguageFromRowIndexedLiteral(Object ril) { try { Method m = ril.getClass().getDeclaredMethod("getLiteral"); m.setAccessible(true); Literal l = (Literal) m.invoke(ril); return l.getLanguage(); } catch (Exception e) { throw new RuntimeException( "Could not get the Literal from a RowIndexedLiteral", e); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hadoop.fs.contract; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileAlreadyExistsException; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import java.io.FileNotFoundException; import java.io.IOException; import static org.apache.hadoop.fs.contract.ContractTestUtils.dataset; import static org.apache.hadoop.fs.contract.ContractTestUtils.getFileStatusEventually; import static org.apache.hadoop.fs.contract.ContractTestUtils.skip; import static org.apache.hadoop.fs.contract.ContractTestUtils.touch; import static org.apache.hadoop.fs.contract.ContractTestUtils.writeDataset; import static org.apache.hadoop.fs.contract.ContractTestUtils.writeTextFile; /** * Test creating files, overwrite options etc. */ public abstract class AbstractContractCreateTest extends AbstractFSContractTestBase { /** * How long to wait for a path to become visible. */ public static final int CREATE_TIMEOUT = 15000; protected Path path(String filepath, boolean useBuilder) throws IOException { return super.path(filepath + (useBuilder ? "" : "-builder")); } private void testCreateNewFile(boolean useBuilder) throws Throwable { describe("Foundational 'create a file' test, using builder API=" + useBuilder); Path path = path("testCreateNewFile", useBuilder); byte[] data = dataset(256, 'a', 'z'); writeDataset(getFileSystem(), path, data, data.length, 1024 * 1024, false, useBuilder); ContractTestUtils.verifyFileContents(getFileSystem(), path, data); } @Test public void testCreateNewFile() throws Throwable { testCreateNewFile(true); testCreateNewFile(false); } private void testCreateFileOverExistingFileNoOverwrite(boolean useBuilder) throws Throwable { describe("Verify overwriting an existing file fails, using builder API=" + useBuilder); Path path = path("testCreateFileOverExistingFileNoOverwrite", useBuilder); byte[] data = dataset(256, 'a', 'z'); writeDataset(getFileSystem(), path, data, data.length, 1024, false); byte[] data2 = dataset(10 * 1024, 'A', 'Z'); try { writeDataset(getFileSystem(), path, data2, data2.length, 1024, false, useBuilder); fail("writing without overwrite unexpectedly succeeded"); } catch (FileAlreadyExistsException expected) { //expected handleExpectedException(expected); } catch (IOException relaxed) { handleRelaxedException("Creating a file over a file with overwrite==false", "FileAlreadyExistsException", relaxed); } } @Test public void testCreateFileOverExistingFileNoOverwrite() throws Throwable { testCreateFileOverExistingFileNoOverwrite(false); testCreateFileOverExistingFileNoOverwrite(true); } private void testOverwriteExistingFile(boolean useBuilder) throws Throwable { describe("Overwrite an existing file and verify the new data is there, " + "use builder API=" + useBuilder); Path path = path("testOverwriteExistingFile", useBuilder); byte[] data = dataset(256, 'a', 'z'); writeDataset(getFileSystem(), path, data, data.length, 1024, false, useBuilder); ContractTestUtils.verifyFileContents(getFileSystem(), path, data); byte[] data2 = dataset(10 * 1024, 'A', 'Z'); writeDataset(getFileSystem(), path, data2, data2.length, 1024, true, useBuilder); ContractTestUtils.verifyFileContents(getFileSystem(), path, data2); } /** * This test catches some eventual consistency problems that blobstores exhibit, * as we are implicitly verifying that updates are consistent. This * is why different file lengths and datasets are used * @throws Throwable */ @Test public void testOverwriteExistingFile() throws Throwable { testOverwriteExistingFile(false); testOverwriteExistingFile(true); } private void testOverwriteEmptyDirectory(boolean useBuilder) throws Throwable { describe("verify trying to create a file over an empty dir fails, " + "use builder API=" + useBuilder); Path path = path("testOverwriteEmptyDirectory"); mkdirs(path); assertIsDirectory(path); byte[] data = dataset(256, 'a', 'z'); try { writeDataset(getFileSystem(), path, data, data.length, 1024, true, useBuilder); assertIsDirectory(path); fail("write of file over empty dir succeeded"); } catch (FileAlreadyExistsException expected) { //expected handleExpectedException(expected); } catch (FileNotFoundException e) { handleRelaxedException("overwriting a dir with a file ", "FileAlreadyExistsException", e); } catch (IOException e) { handleRelaxedException("overwriting a dir with a file ", "FileAlreadyExistsException", e); } assertIsDirectory(path); } @Test public void testOverwriteEmptyDirectory() throws Throwable { testOverwriteEmptyDirectory(false); testOverwriteEmptyDirectory(true); } private void testOverwriteNonEmptyDirectory(boolean useBuilder) throws Throwable { describe("verify trying to create a file over a non-empty dir fails, " + "use builder API=" + useBuilder); Path path = path("testOverwriteNonEmptyDirectory"); mkdirs(path); try { assertIsDirectory(path); } catch (AssertionError failure) { if (isSupported(CREATE_OVERWRITES_DIRECTORY)) { // file/directory hack surfaces here throw new AssumptionViolatedException(failure.toString(), failure); } // else: rethrow throw failure; } Path child = new Path(path, "child"); writeTextFile(getFileSystem(), child, "child file", true); byte[] data = dataset(256, 'a', 'z'); try { writeDataset(getFileSystem(), path, data, data.length, 1024, true, useBuilder); FileStatus status = getFileSystem().getFileStatus(path); boolean isDir = status.isDirectory(); if (!isDir && isSupported(CREATE_OVERWRITES_DIRECTORY)) { // For some file systems, downgrade to a skip so that the failure is // visible in test results. skip("This Filesystem allows a file to overwrite a directory"); } fail("write of file over dir succeeded"); } catch (FileAlreadyExistsException expected) { //expected handleExpectedException(expected); } catch (FileNotFoundException e) { handleRelaxedException("overwriting a dir with a file ", "FileAlreadyExistsException", e); } catch (IOException e) { handleRelaxedException("overwriting a dir with a file ", "FileAlreadyExistsException", e); } assertIsDirectory(path); assertIsFile(child); } @Test public void testOverwriteNonEmptyDirectory() throws Throwable { testOverwriteNonEmptyDirectory(false); testOverwriteNonEmptyDirectory(true); } @Test public void testCreatedFileIsImmediatelyVisible() throws Throwable { describe("verify that a newly created file exists as soon as open returns"); Path path = path("testCreatedFileIsImmediatelyVisible"); try(FSDataOutputStream out = getFileSystem().create(path, false, 4096, (short) 1, 1024)) { if (!getFileSystem().exists(path)) { if (isSupported(CREATE_VISIBILITY_DELAYED)) { // For some file systems, downgrade to a skip so that the failure is // visible in test results. skip("This Filesystem delays visibility of newly created files"); } assertPathExists("expected path to be visible before anything written", path); } } } @Test public void testCreatedFileIsVisibleOnFlush() throws Throwable { describe("verify that a newly created file exists once a flush has taken " + "place"); Path path = path("testCreatedFileIsVisibleOnFlush"); FileSystem fs = getFileSystem(); try(FSDataOutputStream out = fs.create(path, false, 4096, (short) 1, 1024)) { out.write('a'); out.flush(); if (!fs.exists(path)) { if (isSupported(IS_BLOBSTORE) || isSupported(CREATE_VISIBILITY_DELAYED)) { // object store or some file systems: downgrade to a skip so that the // failure is visible in test results skip("For object store or some file systems, newly created files are" + " not immediately visible"); } assertPathExists("expected path to be visible before file closed", path); } } } @Test public void testCreatedFileIsEventuallyVisible() throws Throwable { describe("verify a written to file is visible after the stream is closed"); Path path = path("testCreatedFileIsEventuallyVisible"); FileSystem fs = getFileSystem(); try( FSDataOutputStream out = fs.create(path, false, 4096, (short) 1, 1024) ) { out.write(0x01); out.close(); getFileStatusEventually(fs, path, CREATE_TIMEOUT); } } @Test public void testFileStatusBlocksizeNonEmptyFile() throws Throwable { describe("validate the block size of a filesystem and files within it"); FileSystem fs = getFileSystem(); long rootPath = fs.getDefaultBlockSize(path("/")); assertTrue("Root block size is invalid " + rootPath, rootPath > 0); Path path = path("testFileStatusBlocksizeNonEmptyFile"); byte[] data = dataset(256, 'a', 'z'); writeDataset(fs, path, data, data.length, 1024 * 1024, false); validateBlockSize(fs, path, 1); } @Test public void testFileStatusBlocksizeEmptyFile() throws Throwable { describe("check that an empty file may return a 0-byte blocksize"); FileSystem fs = getFileSystem(); Path path = path("testFileStatusBlocksizeEmptyFile"); ContractTestUtils.touch(fs, path); validateBlockSize(fs, path, 0); } private void validateBlockSize(FileSystem fs, Path path, int minValue) throws IOException, InterruptedException { FileStatus status = getFileStatusEventually(fs, path, CREATE_TIMEOUT); String statusDetails = status.toString(); assertTrue("File status block size too low: " + statusDetails + " min value: " + minValue, status.getBlockSize() >= minValue); long defaultBlockSize = fs.getDefaultBlockSize(path); assertTrue("fs.getDefaultBlockSize(" + path + ") size " + defaultBlockSize + " is below the minimum of " + minValue, defaultBlockSize >= minValue); } @Test public void testCreateMakesParentDirs() throws Throwable { describe("check that after creating a file its parent directories exist"); FileSystem fs = getFileSystem(); Path grandparent = path("testCreateCreatesAndPopulatesParents"); Path parent = new Path(grandparent, "parent"); Path child = new Path(parent, "child"); touch(fs, child); assertEquals("List status of parent should include the 1 child file", 1, fs.listStatus(parent).length); assertTrue("Parent directory does not appear to be a directory", fs.getFileStatus(parent).isDirectory()); assertEquals("List status of grandparent should include the 1 parent dir", 1, fs.listStatus(grandparent).length); assertTrue("Grandparent directory does not appear to be a directory", fs.getFileStatus(grandparent).isDirectory()); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.ambari.server.controller.logging; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.ambari.server.configuration.Configuration; import org.apache.ambari.server.controller.AmbariManagementController; import org.apache.ambari.server.security.encryption.CredentialStoreService; import org.apache.ambari.server.state.Cluster; import org.apache.ambari.server.state.Clusters; import org.apache.ambari.server.state.Config; import org.apache.ambari.server.state.Service; import org.apache.ambari.server.state.ServiceComponentHost; import org.apache.ambari.server.state.State; import org.easymock.EasyMockSupport; import org.junit.Test; public class LoggingRequestHelperFactoryImplTest { @Test public void testHelperCreation() throws Exception { final String expectedClusterName = "testclusterone"; final String expectedHostName = "c6410.ambari.apache.org"; final String expectedPortNumber = "61889"; final int expectedConnectTimeout = 3000; final int expectedReadTimeout = 3000; EasyMockSupport mockSupport = new EasyMockSupport(); AmbariManagementController controllerMock = mockSupport.createMock(AmbariManagementController.class); Clusters clustersMock = mockSupport.createMock(Clusters.class); Cluster clusterMock = mockSupport.createMock(Cluster.class); Config logSearchEnvConfig = mockSupport.createMock(Config.class); ServiceComponentHost serviceComponentHostMock = mockSupport.createMock(ServiceComponentHost.class); CredentialStoreService credentialStoreServiceMock = mockSupport.createMock(CredentialStoreService.class); Configuration serverConfigMock = mockSupport.createMock(Configuration.class); Map<String, String> testProperties = new HashMap<String, String>(); testProperties.put("logsearch_ui_port", expectedPortNumber); expect(controllerMock.getClusters()).andReturn(clustersMock).atLeastOnce(); expect(controllerMock.getCredentialStoreService()).andReturn(credentialStoreServiceMock).atLeastOnce(); expect(clustersMock.getCluster(expectedClusterName)).andReturn(clusterMock).atLeastOnce(); expect(clusterMock.getDesiredConfigByType("logsearch-env")).andReturn(logSearchEnvConfig).atLeastOnce(); expect(clusterMock.getServiceComponentHosts("LOGSEARCH", "LOGSEARCH_SERVER")).andReturn(Collections.singletonList(serviceComponentHostMock)).atLeastOnce(); expect(clusterMock.getServices()).andReturn(Collections.singletonMap("LOGSEARCH", (Service) null)).atLeastOnce(); expect(logSearchEnvConfig.getProperties()).andReturn(testProperties).atLeastOnce(); expect(serviceComponentHostMock.getHostName()).andReturn(expectedHostName).atLeastOnce(); expect(serviceComponentHostMock.getState()).andReturn(State.STARTED).atLeastOnce(); expect(serverConfigMock.getLogSearchPortalConnectTimeout()).andReturn(expectedConnectTimeout); expect(serverConfigMock.getLogSearchPortalReadTimeout()).andReturn(expectedReadTimeout); mockSupport.replayAll(); LoggingRequestHelperFactory helperFactory = new LoggingRequestHelperFactoryImpl(); // set the configuration mock using the concrete type ((LoggingRequestHelperFactoryImpl)helperFactory).setAmbariServerConfiguration(serverConfigMock); LoggingRequestHelper helper = helperFactory.getHelper(controllerMock, expectedClusterName); assertNotNull("LoggingRequestHelper object returned by the factory was null", helper); assertTrue("Helper created was not of the expected type", helper instanceof LoggingRequestHelperImpl); assertEquals("Helper factory did not set the expected connect timeout on the helper instance", expectedConnectTimeout, ((LoggingRequestHelperImpl)helper).getLogSearchConnectTimeoutInMilliseconds()); assertEquals("Helper factory did not set the expected read timeout on the helper instance", expectedReadTimeout, ((LoggingRequestHelperImpl)helper).getLogSearchReadTimeoutInMilliseconds()); mockSupport.verifyAll(); } @Test public void testHelperCreationLogSearchServerNotStarted() throws Exception { final String expectedClusterName = "testclusterone"; final String expectedHostName = "c6410.ambari.apache.org"; final String expectedPortNumber = "61889"; EasyMockSupport mockSupport = new EasyMockSupport(); AmbariManagementController controllerMock = mockSupport.createMock(AmbariManagementController.class); Clusters clustersMock = mockSupport.createMock(Clusters.class); Cluster clusterMock = mockSupport.createMock(Cluster.class); Config logSearchEnvConfig = mockSupport.createMock(Config.class); ServiceComponentHost serviceComponentHostMock = mockSupport.createMock(ServiceComponentHost.class); Configuration serverConfigMock = mockSupport.createMock(Configuration.class); Map<String, String> testProperties = new HashMap<String, String>(); testProperties.put("logsearch_ui_port", expectedPortNumber); expect(controllerMock.getClusters()).andReturn(clustersMock).atLeastOnce(); expect(clustersMock.getCluster(expectedClusterName)).andReturn(clusterMock).atLeastOnce(); expect(clusterMock.getDesiredConfigByType("logsearch-env")).andReturn(logSearchEnvConfig).atLeastOnce(); expect(clusterMock.getServiceComponentHosts("LOGSEARCH", "LOGSEARCH_SERVER")).andReturn(Collections.singletonList(serviceComponentHostMock)).atLeastOnce(); expect(clusterMock.getServices()).andReturn(Collections.singletonMap("LOGSEARCH", (Service) null)).atLeastOnce(); // set the LOGSEARCH_SERVER's state to INSTALLED, to simulate the case where // the server is installed, but not started expect(serviceComponentHostMock.getState()).andReturn(State.INSTALLED).atLeastOnce(); mockSupport.replayAll(); LoggingRequestHelperFactory helperFactory = new LoggingRequestHelperFactoryImpl(); // set the configuration mock using the concrete type ((LoggingRequestHelperFactoryImpl)helperFactory).setAmbariServerConfiguration(serverConfigMock); LoggingRequestHelper helper = helperFactory.getHelper(controllerMock, expectedClusterName); assertNull("LoggingRequestHelper object returned by the factory should have been null", helper); mockSupport.verifyAll(); } @Test public void testHelperCreationWithNoLogSearchServersAvailable() throws Exception { final String expectedClusterName = "testclusterone"; EasyMockSupport mockSupport = new EasyMockSupport(); AmbariManagementController controllerMock = mockSupport.createMock(AmbariManagementController.class); Clusters clustersMock = mockSupport.createMock(Clusters.class); Cluster clusterMock = mockSupport.createMock(Cluster.class); Config logSearchEnvConfig = mockSupport.createMock(Config.class); Configuration serverConfigMock = mockSupport.createMock(Configuration.class); expect(controllerMock.getClusters()).andReturn(clustersMock).atLeastOnce(); expect(clustersMock.getCluster(expectedClusterName)).andReturn(clusterMock).atLeastOnce(); expect(clusterMock.getDesiredConfigByType("logsearch-env")).andReturn(logSearchEnvConfig).atLeastOnce(); expect(clusterMock.getServiceComponentHosts("LOGSEARCH", "LOGSEARCH_SERVER")).andReturn(Collections.<ServiceComponentHost>emptyList()).atLeastOnce(); expect(clusterMock.getServices()).andReturn(Collections.singletonMap("LOGSEARCH", (Service)null)).atLeastOnce(); mockSupport.replayAll(); LoggingRequestHelperFactory helperFactory = new LoggingRequestHelperFactoryImpl(); // set the configuration mock using the concrete type ((LoggingRequestHelperFactoryImpl)helperFactory).setAmbariServerConfiguration(serverConfigMock); LoggingRequestHelper helper = helperFactory.getHelper(controllerMock, expectedClusterName); assertNull("LoggingRequestHelper object returned by the factory should have been null", helper); mockSupport.verifyAll(); } @Test public void testHelperCreationWithNoLogSearchServiceDeployed() throws Exception { final String expectedClusterName = "testclusterone"; EasyMockSupport mockSupport = new EasyMockSupport(); AmbariManagementController controllerMock = mockSupport.createMock(AmbariManagementController.class); Clusters clustersMock = mockSupport.createMock(Clusters.class); Cluster clusterMock = mockSupport.createMock(Cluster.class); Configuration serverConfigMock = mockSupport.createMock(Configuration.class); expect(controllerMock.getClusters()).andReturn(clustersMock).atLeastOnce(); expect(clustersMock.getCluster(expectedClusterName)).andReturn(clusterMock).atLeastOnce(); // do not include LOGSEARCH in this map, to simulate the case when LogSearch is not deployed expect(clusterMock.getServices()).andReturn(Collections.singletonMap("HDFS", (Service)null)).atLeastOnce(); mockSupport.replayAll(); LoggingRequestHelperFactory helperFactory = new LoggingRequestHelperFactoryImpl(); // set the configuration mock using the concrete type ((LoggingRequestHelperFactoryImpl)helperFactory).setAmbariServerConfiguration(serverConfigMock); LoggingRequestHelper helper = helperFactory.getHelper(controllerMock, expectedClusterName); assertNull("LoggingRequestHelper object returned by the factory should have been null", helper); mockSupport.verifyAll(); } @Test public void testHelperCreationWithNoAmbariServerConfiguration() throws Exception { final String expectedClusterName = "testclusterone"; EasyMockSupport mockSupport = new EasyMockSupport(); AmbariManagementController controllerMock = mockSupport.createMock(AmbariManagementController.class); mockSupport.replayAll(); LoggingRequestHelperFactory helperFactory = new LoggingRequestHelperFactoryImpl(); // set the configuration mock using the concrete type // set the configuration object to null, to simulate an error in dependency injection ((LoggingRequestHelperFactoryImpl)helperFactory).setAmbariServerConfiguration(null); LoggingRequestHelper helper = helperFactory.getHelper(controllerMock, expectedClusterName); assertNull("LoggingRequestHelper object returned by the factory should have been null", helper); mockSupport.verifyAll(); } }
/* * See LICENSE file in distribution for copyright and licensing information. */ package ioke.lang; import java.io.InputStreamReader; import java.io.StringReader; import java.util.List; import java.util.ArrayList; import java.util.Properties; import ioke.lang.exceptions.ControlFlow; /** * @author <a href="mailto:[email protected]">Ola Bini</a> */ public class Main { private final static String HELP = "Usage: ioke [switches] -- [programfile] [arguments]\n" + " -Cdirectory execute with directory as CWD\n" + " -d debug, set debug flag\n" + " -e script execute the script. if provided, no program file is necessary.\n" + " there can be many of these provided on the same command line.\n" + " -h, --help help, this message\n" + " -Idir add directory to 'System loadPath'. May be used more than once\n" + " --copyright print the copyright\n" + " --version print current version\n"; public static void main(String[] args) throws Throwable { Runtime r = new Runtime(); r.init(); final IokeObject context = r.ground; final Message mx = new Message(r, ".", null, true); mx.setLine(0); mx.setPosition(0); final IokeObject message = r.createMessage(mx); boolean debug = false; String cwd = null; List<String> scripts = new ArrayList<String>(); List<String> loadDirs = new ArrayList<String>(); try { int start = 0; boolean done = false; boolean readStdin = false; boolean printedSomething = false; for(;!done && start<args.length;start++) { String arg = args[start]; if(arg.length() > 0) { if(arg.charAt(0) != '-') { done = true; break; } else { if(arg.equals("--")) { done = true; } else if(arg.equals("-d")) { debug = true; r.debug = true; } else if(arg.startsWith("-e")) { if(arg.length() == 2) { scripts.add(args[++start]); } else { scripts.add(arg.substring(2)); } } else if(arg.startsWith("-I")) { if(arg.length() == 2) { loadDirs.add(args[++start]); } else { loadDirs.add(arg.substring(2)); } } else if(arg.equals("-h") || arg.equals("--help")) { System.err.print(HELP); return; } else if(arg.equals("--version")) { System.err.println(getVersion()); printedSomething = true; } else if(arg.equals("--copyright")) { System.err.print(COPYRIGHT); printedSomething = true; } else if(arg.equals("-")) { readStdin = true; } else if(arg.charAt(1) == 'C') { if(arg.length() == 2) { cwd = args[++start]; } else { cwd = arg.substring(2); } } else { final IokeObject condition = IokeObject.as(IokeObject.getCellChain(r.condition, message, context, "Error", "CommandLine", "DontUnderstandOption"), null).mimic(message, context); condition.setCell("message", message); condition.setCell("context", context); condition.setCell("receiver", context); condition.setCell("option", r.newText(arg)); r.errorCondition(condition); } } } } if(cwd != null) { r.setCurrentWorkingDirectory(cwd); } ((IokeSystem)IokeObject.data(r.system)).setCurrentProgram("-e"); ((IokeSystem)IokeObject.data(r.system)).addLoadPath(System.getProperty("ioke.lib", ".") + "/ioke"); ((IokeSystem)IokeObject.data(r.system)).addLoadPath("lib/ioke"); for(String ss : loadDirs) { ((IokeSystem)IokeObject.data(r.system)).addLoadPath(ss); } for(String script : scripts) { r.evaluateStream("-e", new StringReader(script), message, context); } if(readStdin) { ((IokeSystem)IokeObject.data(r.system)).setCurrentProgram("<stdin>"); r.evaluateStream("<stdin>", new InputStreamReader(System.in, "UTF-8"), message, context); } if(args.length > start) { if(args.length > (start+1)) { for(int i=start+1,j=args.length; i<j; i++) { r.addArgument(args[i]); } } String file = args[start]; if(file.startsWith("\"")) { file = file.substring(1, file.length()); } if(file.length() > 1 && file.charAt(file.length()-1) == '"') { file = file.substring(0, file.length()-1); } ((IokeSystem)IokeObject.data(r.system)).setCurrentProgram(file); r.evaluateFile(file, message, context); } else { if(!readStdin && scripts.size() == 0 && !printedSomething) { r.evaluateString("use(\"builtin/iik\"). IIk mainLoop", message, context); } } r.tearDown(); } catch(ControlFlow.Exit e) { int exitVal = e.getExitValue(); try { r.tearDown(); } catch(ControlFlow.Exit e2) { exitVal = e2.getExitValue(); } System.exit(exitVal); } catch(ControlFlow e) { String name = e.getClass().getName(); System.err.println("unexpected control flow: " + name.substring(name.indexOf("$") + 1).toLowerCase()); if(debug) { e.printStackTrace(System.err); } System.exit(1); } } public static String getVersion() { try { Properties props = new Properties(); props.load(Main.class.getResourceAsStream("/ioke/lang/version.properties")); String version = props.getProperty("ioke.build.versionString"); String date = props.getProperty("ioke.build.date"); String commit = props.getProperty("ioke.build.commit"); return version + " [" + date + " -- " + commit + "]"; } catch(Exception e) { } return ""; } private final static String COPYRIGHT = "Copyright (c) 2008 Ola Bini, [email protected]\n"+ "\n"+ "Permission is hereby granted, free of charge, to any person obtaining a copy\n"+ "of this software and associated documentation files (the \"Software\"), to deal\n"+ "in the Software without restriction, including without limitation the rights\n"+ "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"+ "copies of the Software, and to permit persons to whom the Software is\n"+ "furnished to do so, subject to the following conditions:\n"+ "\n"+ "The above copyright notice and this permission notice shall be included in\n"+ "all copies or substantial portions of the Software.\n"+ "\n"+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"+ "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"+ "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"+ "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"+ "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"+ "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"+ "THE SOFTWARE.\n"; }// Main
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.elasticsearch.search.aggregations.support; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.RandomAccessOrds; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Scorer; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.lucene.ScorerAware; import org.elasticsearch.index.fielddata.AtomicOrdinalsFieldData; import org.elasticsearch.index.fielddata.AtomicParentChildFieldData; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexGeoPointFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.fielddata.IndexOrdinalsFieldData; import org.elasticsearch.index.fielddata.IndexParentChildFieldData; import org.elasticsearch.index.fielddata.MultiGeoPointValues; import org.elasticsearch.index.fielddata.SortedBinaryDocValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.fielddata.SortingBinaryDocValues; import org.elasticsearch.index.fielddata.SortingNumericDocValues; import org.elasticsearch.index.fielddata.SortingNumericDoubleValues; import org.elasticsearch.index.fielddata.plain.ParentChildIndexFieldData; import org.elasticsearch.script.LeafSearchScript; import org.elasticsearch.script.SearchScript; import org.elasticsearch.search.aggregations.support.ValuesSource.WithScript.BytesValues; import org.elasticsearch.search.aggregations.support.values.ScriptBytesValues; import org.elasticsearch.search.aggregations.support.values.ScriptDoubleValues; import org.elasticsearch.search.aggregations.support.values.ScriptLongValues; import java.io.IOException; public abstract class ValuesSource { /** * Get the current {@link BytesValues}. */ public abstract SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException; public abstract Bits docsWithValue(LeafReaderContext context) throws IOException; /** Whether this values source needs scores. */ public boolean needsScores() { return false; } public static abstract class Bytes extends ValuesSource { public static final WithOrdinals EMPTY = new WithOrdinals() { @Override public RandomAccessOrds ordinalsValues(LeafReaderContext context) { return DocValues.emptySortedSet(); } @Override public RandomAccessOrds globalOrdinalsValues(LeafReaderContext context) { return DocValues.emptySortedSet(); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return org.elasticsearch.index.fielddata.FieldData.emptySortedBinary(context.reader().maxDoc()); } }; @Override public Bits docsWithValue(LeafReaderContext context) throws IOException { final SortedBinaryDocValues bytes = bytesValues(context); if (org.elasticsearch.index.fielddata.FieldData.unwrapSingleton(bytes) != null) { return org.elasticsearch.index.fielddata.FieldData.unwrapSingletonBits(bytes); } else { return org.elasticsearch.index.fielddata.FieldData.docsWithValue(bytes, context.reader().maxDoc()); } } public static abstract class WithOrdinals extends Bytes { @Override public Bits docsWithValue(LeafReaderContext context) { final RandomAccessOrds ordinals = ordinalsValues(context); if (DocValues.unwrapSingleton(ordinals) != null) { return DocValues.docsWithValue(DocValues.unwrapSingleton(ordinals), context.reader().maxDoc()); } else { return DocValues.docsWithValue(ordinals, context.reader().maxDoc()); } } public abstract RandomAccessOrds ordinalsValues(LeafReaderContext context); public abstract RandomAccessOrds globalOrdinalsValues(LeafReaderContext context); public long globalMaxOrd(IndexSearcher indexSearcher) { IndexReader indexReader = indexSearcher.getIndexReader(); if (indexReader.leaves().isEmpty()) { return 0; } else { LeafReaderContext atomicReaderContext = indexReader.leaves().get(0); RandomAccessOrds values = globalOrdinalsValues(atomicReaderContext); return values.getValueCount(); } } public static class FieldData extends WithOrdinals { protected final IndexOrdinalsFieldData indexFieldData; public FieldData(IndexOrdinalsFieldData indexFieldData) { this.indexFieldData = indexFieldData; } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) { final AtomicOrdinalsFieldData atomicFieldData = indexFieldData.load(context); return atomicFieldData.getBytesValues(); } @Override public RandomAccessOrds ordinalsValues(LeafReaderContext context) { final AtomicOrdinalsFieldData atomicFieldData = indexFieldData.load(context); return atomicFieldData.getOrdinalsValues(); } @Override public RandomAccessOrds globalOrdinalsValues(LeafReaderContext context) { final IndexOrdinalsFieldData global = indexFieldData.loadGlobal((DirectoryReader)context.parent.reader()); final AtomicOrdinalsFieldData atomicFieldData = global.load(context); return atomicFieldData.getOrdinalsValues(); } } } public static class ParentChild extends Bytes { protected final ParentChildIndexFieldData indexFieldData; public ParentChild(ParentChildIndexFieldData indexFieldData) { this.indexFieldData = indexFieldData; } public long globalMaxOrd(IndexSearcher indexSearcher, String type) { DirectoryReader indexReader = (DirectoryReader) indexSearcher.getIndexReader(); if (indexReader.leaves().isEmpty()) { return 0; } else { LeafReaderContext atomicReaderContext = indexReader.leaves().get(0); IndexParentChildFieldData globalFieldData = indexFieldData.loadGlobal(indexReader); AtomicParentChildFieldData afd = globalFieldData.load(atomicReaderContext); SortedDocValues values = afd.getOrdinalsValues(type); return values.getValueCount(); } } public SortedDocValues globalOrdinalsValues(String type, LeafReaderContext context) { final IndexParentChildFieldData global = indexFieldData.loadGlobal((DirectoryReader)context.parent.reader()); final AtomicParentChildFieldData atomicFieldData = global.load(context); return atomicFieldData.getOrdinalsValues(type); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) { final AtomicParentChildFieldData atomicFieldData = indexFieldData.load(context); return atomicFieldData.getBytesValues(); } } public static class FieldData extends Bytes { protected final IndexFieldData<?> indexFieldData; public FieldData(IndexFieldData<?> indexFieldData) { this.indexFieldData = indexFieldData; } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) { return indexFieldData.load(context).getBytesValues(); } } public static class Script extends Bytes { private final SearchScript script; public Script(SearchScript script) { this.script = script; } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return new ScriptBytesValues(script.getLeafSearchScript(context)); } @Override public boolean needsScores() { return script.needsScores(); } } } public static abstract class Numeric extends ValuesSource { public static final Numeric EMPTY = new Numeric() { @Override public boolean isFloatingPoint() { return false; } @Override public SortedNumericDocValues longValues(LeafReaderContext context) { return DocValues.emptySortedNumeric(context.reader().maxDoc()); } @Override public SortedNumericDoubleValues doubleValues(LeafReaderContext context) throws IOException { return org.elasticsearch.index.fielddata.FieldData.emptySortedNumericDoubles(context.reader().maxDoc()); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return org.elasticsearch.index.fielddata.FieldData.emptySortedBinary(context.reader().maxDoc()); } }; /** Whether the underlying data is floating-point or not. */ public abstract boolean isFloatingPoint(); /** Get the current {@link SortedNumericDocValues}. */ public abstract SortedNumericDocValues longValues(LeafReaderContext context) throws IOException; /** Get the current {@link SortedNumericDoubleValues}. */ public abstract SortedNumericDoubleValues doubleValues(LeafReaderContext context) throws IOException; @Override public Bits docsWithValue(LeafReaderContext context) throws IOException { if (isFloatingPoint()) { final SortedNumericDoubleValues values = doubleValues(context); if (org.elasticsearch.index.fielddata.FieldData.unwrapSingleton(values) != null) { return org.elasticsearch.index.fielddata.FieldData.unwrapSingletonBits(values); } else { return org.elasticsearch.index.fielddata.FieldData.docsWithValue(values, context.reader().maxDoc()); } } else { final SortedNumericDocValues values = longValues(context); if (DocValues.unwrapSingleton(values) != null) { return DocValues.unwrapSingletonBits(values); } else { return DocValues.docsWithValue(values, context.reader().maxDoc()); } } } public static class WithScript extends Numeric { private final Numeric delegate; private final SearchScript script; public WithScript(Numeric delegate, SearchScript script) { this.delegate = delegate; this.script = script; } @Override public boolean isFloatingPoint() { return true; // even if the underlying source produces longs, scripts can change them to doubles } @Override public boolean needsScores() { return script.needsScores(); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return new ValuesSource.WithScript.BytesValues(delegate.bytesValues(context), script.getLeafSearchScript(context)); } @Override public SortedNumericDocValues longValues(LeafReaderContext context) throws IOException { return new LongValues(delegate.longValues(context), script.getLeafSearchScript(context)); } @Override public SortedNumericDoubleValues doubleValues(LeafReaderContext context) throws IOException { return new DoubleValues(delegate.doubleValues(context), script.getLeafSearchScript(context)); } static class LongValues extends SortingNumericDocValues implements ScorerAware { private final SortedNumericDocValues longValues; private final LeafSearchScript script; public LongValues(SortedNumericDocValues values, LeafSearchScript script) { this.longValues = values; this.script = script; } @Override public void setDocument(int doc) { longValues.setDocument(doc); resize(longValues.count()); script.setDocument(doc); for (int i = 0; i < count(); ++i) { script.setNextAggregationValue(longValues.valueAt(i)); values[i] = script.runAsLong(); } sort(); } @Override public void setScorer(Scorer scorer) { script.setScorer(scorer); } } static class DoubleValues extends SortingNumericDoubleValues implements ScorerAware { private final SortedNumericDoubleValues doubleValues; private final LeafSearchScript script; public DoubleValues(SortedNumericDoubleValues values, LeafSearchScript script) { this.doubleValues = values; this.script = script; } @Override public void setDocument(int doc) { doubleValues.setDocument(doc); resize(doubleValues.count()); script.setDocument(doc); for (int i = 0; i < count(); ++i) { script.setNextAggregationValue(doubleValues.valueAt(i)); values[i] = script.runAsDouble(); } sort(); } @Override public void setScorer(Scorer scorer) { script.setScorer(scorer); } } } public static class FieldData extends Numeric { protected final IndexNumericFieldData indexFieldData; public FieldData(IndexNumericFieldData indexFieldData) { this.indexFieldData = indexFieldData; } @Override public boolean isFloatingPoint() { return indexFieldData.getNumericType().isFloatingPoint(); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) { return indexFieldData.load(context).getBytesValues(); } @Override public SortedNumericDocValues longValues(LeafReaderContext context) { return indexFieldData.load(context).getLongValues(); } @Override public SortedNumericDoubleValues doubleValues(LeafReaderContext context) { return indexFieldData.load(context).getDoubleValues(); } } public static class Script extends Numeric { private final SearchScript script; private final ValueType scriptValueType; public Script(SearchScript script, ValueType scriptValueType) { this.script = script; this.scriptValueType = scriptValueType; } @Override public boolean isFloatingPoint() { return scriptValueType != null ? scriptValueType.isFloatingPoint() : true; } @Override public SortedNumericDocValues longValues(LeafReaderContext context) throws IOException { return new ScriptLongValues(script.getLeafSearchScript(context)); } @Override public SortedNumericDoubleValues doubleValues(LeafReaderContext context) throws IOException { return new ScriptDoubleValues(script.getLeafSearchScript(context)); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return new ScriptBytesValues(script.getLeafSearchScript(context)); } @Override public boolean needsScores() { return script.needsScores(); } } } // No need to implement ReaderContextAware here, the delegate already takes care of updating data structures public static class WithScript extends Bytes { private final ValuesSource delegate; private final SearchScript script; public WithScript(ValuesSource delegate, SearchScript script) { this.delegate = delegate; this.script = script; } @Override public boolean needsScores() { return script.needsScores(); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return new BytesValues(delegate.bytesValues(context), script.getLeafSearchScript(context)); } static class BytesValues extends SortingBinaryDocValues implements ScorerAware { private final SortedBinaryDocValues bytesValues; private final LeafSearchScript script; public BytesValues(SortedBinaryDocValues bytesValues, LeafSearchScript script) { this.bytesValues = bytesValues; this.script = script; } @Override public void setDocument(int docId) { bytesValues.setDocument(docId); count = bytesValues.count(); grow(); for (int i = 0; i < count; ++i) { final BytesRef value = bytesValues.valueAt(i); script.setNextAggregationValue(value.utf8ToString()); values[i].copyChars(script.run().toString()); } sort(); } @Override public void setScorer(Scorer scorer) { script.setScorer(scorer); } } } public static abstract class GeoPoint extends ValuesSource { public static final GeoPoint EMPTY = new GeoPoint() { @Override public MultiGeoPointValues geoPointValues(LeafReaderContext context) { return org.elasticsearch.index.fielddata.FieldData.emptyMultiGeoPoints(context.reader().maxDoc()); } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) throws IOException { return org.elasticsearch.index.fielddata.FieldData.emptySortedBinary(context.reader().maxDoc()); } }; @Override public Bits docsWithValue(LeafReaderContext context) { final MultiGeoPointValues geoPoints = geoPointValues(context); if (org.elasticsearch.index.fielddata.FieldData.unwrapSingleton(geoPoints) != null) { return org.elasticsearch.index.fielddata.FieldData.unwrapSingletonBits(geoPoints); } else { return org.elasticsearch.index.fielddata.FieldData.docsWithValue(geoPoints, context.reader().maxDoc()); } } public abstract MultiGeoPointValues geoPointValues(LeafReaderContext context); public static class Fielddata extends GeoPoint { protected final IndexGeoPointFieldData indexFieldData; public Fielddata(IndexGeoPointFieldData indexFieldData) { this.indexFieldData = indexFieldData; } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) { return indexFieldData.load(context).getBytesValues(); } public org.elasticsearch.index.fielddata.MultiGeoPointValues geoPointValues(LeafReaderContext context) { return indexFieldData.load(context).getGeoPointValues(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.ode.il.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.utils.SystemUtils; /** * Configuration object used for configuring the intergration layer. The propereties are those likely to be common to all layers. * * @author mszefler */ public class OdeConfigProperties { private static final long serialVersionUID = 1L; private static final Log __log = LogFactory.getLog(OdeConfigProperties.class); public static final String PROP_DB_MODE = "db.mode"; public static final String PROP_DB_EXTERNAL_DS = "db.ext.dataSource"; public static final String PROP_DB_EMBEDDED_NAME = "db.emb.name"; public static final String PROP_DB_INTERNAL_URL = "db.int.jdbcurl"; public static final String PROP_DB_INTERNAL_DRIVER = "db.int.driver"; public static final String PROP_DB_INTERNAL_PASSWORD = "db.int.password"; public static final String PROP_DB_INTERNAL_USER = "db.int.username"; public static final String PROP_DB_LOGGING = "db.logging"; public static final String PROP_TX_FACTORY_CLASS = "tx.factory.class"; public static final String PROP_POOL_MAX = "db.pool.max"; public static final String PROP_POOL_MIN = "db.pool.min"; public static final String PROP_DB_POOL_BLOCKING = "db.pool.blocking"; public static final String PROP_THREAD_POOL_SIZE = "threads.pool.size"; public static final String PROP_CONNECTOR_PORT = "jca.port"; public static final String PROP_CONNECTOR_NAME = "jca.name"; public static final String PROP_WORKING_DIR = "working.dir"; public static final String PROP_DEPLOY_DIR = "deploy.dir"; public static final String PROP_EVENT_LISTENERS = "event.listeners"; public static final String PROP_MEX_INTERCEPTORS = "mex.interceptors"; public static final String PROP_MEX_INMEM_TTL = "mex.inmem.ttl"; public static final String PROP_PROCESS_DEHYDRATION = "process.dehydration"; public static final String PROP_PROCESS_DEHYDRATION_MAXIMUM_AGE = "process.dehydration.maximum.age"; public static final String PROP_PROCESS_DEHYDRATION_MAXIMUM_COUNT = "process.dehydration.maximum.count"; public static final String PROP_PROCESS_HYDRATION_LAZY = "process.hydration.lazy"; public static final String PROP_PROCESS_HYDRATION_LAZY_MINIMUM_SIZE = "process.hydration.lazy.minimum.size"; public static final String PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_COUNT = "process.hydration.throttled.maximum.count"; public static final String PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_SIZE = "process.hydration.throttled.maximum.size"; public static final String PROP_PROCESS_INSTANCE_THROTTLED_MAXIMUM_COUNT = "process.instance.throttled.maximum.count"; public static final String PROP_DAOCF = "dao.factory"; public static final String PROP_MIGRATION_TRANSACTION_TIMEOUT = "migration.transaction.timeout"; public static final String DEFAULT_TX_FACTORY_CLASS_NAME = "org.apache.ode.il.EmbeddedGeronimoFactory"; private File _cfgFile; private String _prefix; private Properties _props; /** Default defaults for the database embedded name and dao connection factory class. */ private static String __dbEmbName = "derby-jpadb"; private static String __daoCfClass = "org.apache.ode.dao.jpa.BPELDAOConnectionFactoryImpl"; static { String odep = System.getProperty("ode.persistence"); if (odep != null && "hibernate".equalsIgnoreCase(odep)) { __log.debug("Using HIBERNATE due to system property override!"); __dbEmbName = "hibdb"; __daoCfClass = "org.apache.ode.daohib.bpel.BpelDAOConnectionFactoryImpl"; } } /** * Possible database modes. */ public enum DatabaseMode { /** External data-source (managed by app server) */ EXTERNAL, /** Internal data-source (User provides database info, Ode provides connection pool) */ INTERNAL, /** Embedded database (Ode provides default embedded database with connection pool) */ EMBEDDED } public OdeConfigProperties(File cfgFile, String prefix) { _cfgFile = cfgFile; _prefix = prefix; _props = new Properties(); } public OdeConfigProperties(Properties props, String prefix) { _cfgFile = null; _prefix = prefix; _props = props; } public File getFile() { return _cfgFile; } public void load() throws IOException { if (_cfgFile.exists()) { __log.debug("config file exists: " + _cfgFile); FileInputStream fis = null; try { fis = new FileInputStream(_cfgFile); _props.load(fis); } finally { if (fis != null) try { fis.close(); } catch (Exception ex) { ex.printStackTrace(); } } } else { __log.debug("config file does not exists: " + _cfgFile); throw new FileNotFoundException("" + _cfgFile); } for (Object key : _props.keySet()) { String value = (String) _props.get(key); value = SystemUtils.replaceSystemProperties(value); _props.put(key, value); } } /** * Should the internal database be used, or are the datasources provided? * * @return db mode */ public String getDbEmbeddedName() { return getProperty(OdeConfigProperties.PROP_DB_EMBEDDED_NAME, __dbEmbName); } public DatabaseMode getDbMode() { return DatabaseMode.valueOf(getProperty(OdeConfigProperties.PROP_DB_MODE, DatabaseMode.EMBEDDED.toString()).trim() .toUpperCase()); } public String getDAOConnectionFactory() { return getProperty(PROP_DAOCF, __daoCfClass); } public String getDbDataSource() { return getProperty(OdeConfigProperties.PROP_DB_EXTERNAL_DS, "java:comp/env/jdbc/ode-ds"); } public String getDbIntenralJdbcUrl() { return getProperty(OdeConfigProperties.PROP_DB_INTERNAL_URL, "jdbc:derby://localhost/ode"); } public String getDbInternalMCFClass() { return getProperty("db.int.mcf"); } public Properties getDbInternalMCFProperties() { String prefix = _prefix + "db.int.mcf."; Properties p = new Properties(); for (Map.Entry<Object, Object> e : _props.entrySet()) { String s = "" + e.getKey(); if (s.startsWith(prefix)) { p.put(s.substring(prefix.length()), e.getValue()); } } return p; } /** * JDBC driver class (for use in INTERNAL mode). * * @return */ public String getDbInternalJdbcDriverClass() { return getProperty(OdeConfigProperties.PROP_DB_INTERNAL_DRIVER, "org.apache.derby.jdbc.ClientDriver"); } public boolean getPoolBlocking() { return Boolean.valueOf(getProperty(PROP_DB_POOL_BLOCKING,"false")); } public int getThreadPoolMaxSize() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_THREAD_POOL_SIZE, "0")); } public int getPoolMaxSize() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_POOL_MAX, "10")); } public int getPoolMinSize() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_POOL_MIN, "1")); } public int getConnectorPort() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_CONNECTOR_PORT, "2099")); } public String getConnectorName() { return getProperty(OdeConfigProperties.PROP_CONNECTOR_NAME, "ode"); } public String getWorkingDir() { return getProperty(OdeConfigProperties.PROP_WORKING_DIR); } public String getDeployDir() { return getProperty(OdeConfigProperties.PROP_DEPLOY_DIR); } public String getTxFactoryClass() { return getProperty(OdeConfigProperties.PROP_TX_FACTORY_CLASS, DEFAULT_TX_FACTORY_CLASS_NAME); } public String getEventListeners() { return getProperty(PROP_EVENT_LISTENERS); } public String getMessageExchangeInterceptors() { return getProperty(PROP_MEX_INTERCEPTORS); } public long getInMemMexTtl() { return Long.valueOf(getProperty(PROP_MEX_INMEM_TTL, ""+10*60*1000)); } public boolean isDehydrationEnabled() { return Boolean.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_DEHYDRATION, "false")); } public long getDehydrationMaximumAge() { return Long.valueOf(getProperty(PROP_PROCESS_DEHYDRATION_MAXIMUM_AGE, ""+20*60*1000)); } public int getDehydrationMaximumCount() { return Integer.valueOf(getProperty(PROP_PROCESS_DEHYDRATION_MAXIMUM_COUNT, ""+1000)); } public boolean isHydrationLazy() { return Boolean.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_LAZY, "true")); } public int getHydrationLazyMinimumSize() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_LAZY_MINIMUM_SIZE, String.valueOf(0))); } public int getProcessThrottledMaximumCount() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_COUNT, String.valueOf(Integer.MAX_VALUE))); } public int getInstanceThrottledMaximumCount() { return Integer.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_INSTANCE_THROTTLED_MAXIMUM_COUNT, String.valueOf(Integer.MAX_VALUE))); } public long getProcessThrottledMaximumSize() { return Long.valueOf(getProperty(OdeConfigProperties.PROP_PROCESS_HYDRATION_THROTTLED_MAXIMUM_SIZE, String.valueOf(Long.MAX_VALUE))); } public boolean isProcessSizeThrottled() { return getProcessThrottledMaximumSize() == Long.MAX_VALUE; } public boolean isDbLoggingEnabled() { return Boolean.valueOf(getProperty(OdeConfigProperties.PROP_DB_LOGGING, "false")); } public String getProperty(String pname) { return _props.getProperty(_prefix + pname); } public String getProperty(String key, String dflt) { return _props.getProperty(_prefix + key, dflt); } public Properties getProperties() { return _props; } public String getDbInternalUserName() { return getProperty(PROP_DB_INTERNAL_USER); } public String getDbInternalPassword() { return getProperty(PROP_DB_INTERNAL_PASSWORD); } public int getMigrationTransactionTimeout() { return Integer.valueOf(getProperty(PROP_MIGRATION_TRANSACTION_TIMEOUT, String.valueOf(0))); } }
/* * #%L * carewebframework * %% * Copyright (C) 2008 - 2017 Regenstrief Institute, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This Source Code Form is also subject to the terms of the Health-Related * Additional Disclaimer of Warranty and Limitation of Liability available at * * http://www.carewebframework.org/licensing/disclaimer. * * #L% */ package org.carewebframework.rpms.plugin.chat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.carewebframework.api.context.UserContext; import org.carewebframework.api.domain.IUser; import org.carewebframework.api.event.IEventManager; import org.carewebframework.api.event.IGenericEvent; import org.carewebframework.api.messaging.Recipient; import org.carewebframework.api.messaging.Recipient.RecipientType; import org.carewebframework.api.spring.SpringUtil; import org.carewebframework.common.DateUtil; import org.carewebframework.common.StrUtil; import org.carewebframework.ui.action.ActionRegistry; import org.carewebframework.ui.zk.MessageWindow; import org.carewebframework.ui.zk.MessageWindow.MessageInfo; import org.carewebframework.vista.mbroker.BrokerSession; /** * Chat service. */ public class ChatService implements IGenericEvent<String> { private static final String EVENT_CHAT_SERVICE = "VCCHAT.SERVICE"; private final IEventManager eventManager; private final BrokerSession brokerSession; private final List<SessionController> sessions = new ArrayList<SessionController>(); private boolean listening; private IUser user; private static final AtomicInteger lastId = new AtomicInteger(); /** * Returns an instance of the chat service. * * @return The chat service. */ public static ChatService getInstance() { return SpringUtil.getBean("vcChatService", ChatService.class); } /** * Creates the chat service, supplying the broker and event manager instances. * * @param brokerSession The broker session. * @param eventManager The event manager. */ public ChatService(BrokerSession brokerSession, IEventManager eventManager) { this.brokerSession = brokerSession; this.eventManager = eventManager; } /** * Initialization of service. */ public void init() { user = UserContext.getActiveUser(); doSubscribe(true); ActionRegistry.register(false, "vcchat.create.session", "@vcchat.action.create.session", "zscript:" + ChatService.class.getName() + ".getInstance().createSession();"); } /** * Tear-down of service. Closes any open sessions. */ public void destroy() { doSubscribe(false); for (SessionController session : new ArrayList<SessionController>(sessions)) { session.close(); } } /** * Subscribe to / unsubscribe from all events of interest. * * @param subscribe If true, subscribe to events. If false, unsubscribe. */ private void doSubscribe(boolean subscribe) { if (subscribe) { eventManager.subscribe(EVENT_CHAT_SERVICE, this); } else { eventManager.unsubscribe(EVENT_CHAT_SERVICE, this); } } /** * Returns the root identifier for sessions created by this service. * * @return Session root. */ public String getSessionRoot() { return Integer.toString(brokerSession.getId()); } /** * Creates a new session id. * * @return New session id. */ private String newSessionId() { return getSessionRoot() + "-" + lastId.incrementAndGet(); } /** * Creates a new session with a new session id. * * @return The newly created session. */ public SessionController createSession() { return createSession(newSessionId()); } /** * Creates a new session with the specified session id. * * @param sessionId The session id to associate with the new session. * @return The newly created session. */ public SessionController createSession(String sessionId) { SessionController controller = SessionController.create(sessionId); sessions.add(controller); return controller; } /** * Called by a session controller when it closes. * * @param session Session being closed. */ protected void onSessionClosed(SessionController session) { sessions.remove(session); } /** * Respond to events: * <p> * VCCHAT.SERVICE.INVITE - An invitation has been received to join a dialog. Event stub format * is: Chat Session ID^Requester name * <p> * VCCHAT.SERVICE.ACCEPT - This client has accepted the invitation to join. Event stub format * is: Chat Session ID */ @Override public void eventCallback(String eventName, String eventData) { String action = StrUtil.piece(eventName, ".", 3); if ("INVITE".equals(action)) { String[] pcs = StrUtil.split(eventData, StrUtil.U); MessageInfo mi = new MessageInfo(StrUtil.formatMessage("@vcchat.invitation.message", pcs[1]), StrUtil.formatMessage("@vcchat.invitation.caption"), null, 999999, null, "cwf.fireLocalEvent('VCCHAT.SERVICE.ACCEPT', '" + pcs[0] + "'); return true;"); eventManager.fireLocalEvent(MessageWindow.EVENT_SHOW, mi); ; } else if ("ACCEPT".equals(action)) { createSession(eventData); } } /** * Returns true if the service is actively listening for events. * * @return True if the service is actively listening. */ public boolean isListening() { return listening; } /** * Sets the listening state of the service. When set to false, the service stops listening to * all chat-related events. * * @param listening The listening state. */ public void setListening(boolean listening) { this.listening = listening; doSubscribe(listening); } /** * Returns a list of participants. This is really a list of subscribers to a specified event. * * @param participants Collection to receive the participant list. * @param eventName The name of the event whose subscribers are sought. This will normally be * the event that a session controller uses to monitor chat-related activity. If * null, all chat service subscribers are returned. * @return Same as the participants argument. */ public Collection<Participant> getParticipants(Collection<Participant> participants, String eventName) { participants.clear(); List<String> lst = brokerSession.callRPCList("RGNETBEV GETSUBSC", null, eventName == null ? EVENT_CHAT_SERVICE : eventName); for (String data : lst) { participants.add(new Participant(data)); } return participants; } /** * Sends a message via the specified event. * * @param eventName Event to use to deliver the message. * @param text The message text. */ public void sendMessage(String eventName, String text) { if (text != null && !text.isEmpty()) { eventManager.fireRemoteEvent(eventName, user.getFullName() + " @ " + DateUtil.formatDate(brokerSession.getHostTime()) + "\r\n" + text); } } /** * Sends an invitation request to the specified invitees. * * @param sessionId The id of the chat session making the invitation. * @param invitees The list of invitees. This will be used to constraint delivery of the * invitation event to only those subscribers. */ public void invite(String sessionId, Collection<Participant> invitees) { if (invitees == null || invitees.isEmpty()) { return; } List<Recipient> recipients = new ArrayList<>(); for (Participant invitee : invitees) { recipients.add(new Recipient(RecipientType.SESSION, invitee.getSession())); } eventManager.fireRemoteEvent("VCCHAT.SERVICE.INVITE", sessionId + StrUtil.U + user.getFullName(), (Recipient[]) recipients.toArray()); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.mergerows; import java.util.List; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.injection.Injection; import org.pentaho.di.core.injection.InjectionSupported; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaString; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.TransMeta.TransformationType; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepIOMeta; import org.pentaho.di.trans.step.StepIOMetaInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.errorhandling.Stream; import org.pentaho.di.trans.step.errorhandling.StreamIcon; import org.pentaho.di.trans.step.errorhandling.StreamInterface; import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; /* * Created on 02-jun-2003 * */ @InjectionSupported( localizationPrefix = "MergeRows.Injection." ) public class MergeRowsMeta extends BaseStepMeta implements StepMetaInterface { private static Class<?> PKG = MergeRowsMeta.class; // for i18n purposes, needed by Translator2!! @Injection( name = "FLAG_FIELD" ) private String flagField; @Injection( name = "KEY_FIELDS" ) private String[] keyFields; @Injection( name = "VALUE_FIELDS" ) private String[] valueFields; /** * @return Returns the keyFields. */ public String[] getKeyFields() { return keyFields; } /** * @param keyFields * The keyFields to set. */ public void setKeyFields( String[] keyFields ) { this.keyFields = keyFields; } /** * @return Returns the valueFields. */ public String[] getValueFields() { return valueFields; } /** * @param valueFields * The valueFields to set. */ public void setValueFields( String[] valueFields ) { this.valueFields = valueFields; } public MergeRowsMeta() { super(); // allocate BaseStepMeta } @Override public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException { readData( stepnode ); } /** * @return Returns the flagField. */ public String getFlagField() { return flagField; } /** * @param flagField * The flagField to set. */ public void setFlagField( String flagField ) { this.flagField = flagField; } public void allocate( int nrKeys, int nrValues ) { keyFields = new String[nrKeys]; valueFields = new String[nrValues]; } @Override public Object clone() { MergeRowsMeta retval = (MergeRowsMeta) super.clone(); int nrKeys = keyFields.length; int nrValues = valueFields.length; retval.allocate( nrKeys, nrValues ); System.arraycopy( keyFields, 0, retval.keyFields, 0, nrKeys ); System.arraycopy( valueFields, 0, retval.valueFields, 0, nrValues ); return retval; } @Override public String getXML() { StringBuilder retval = new StringBuilder(); retval.append( " <keys>" + Const.CR ); for ( int i = 0; i < keyFields.length; i++ ) { retval.append( " " + XMLHandler.addTagValue( "key", keyFields[i] ) ); } retval.append( " </keys>" + Const.CR ); retval.append( " <values>" + Const.CR ); for ( int i = 0; i < valueFields.length; i++ ) { retval.append( " " + XMLHandler.addTagValue( "value", valueFields[i] ) ); } retval.append( " </values>" + Const.CR ); retval.append( XMLHandler.addTagValue( "flag_field", flagField ) ); List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); retval.append( XMLHandler.addTagValue( "reference", infoStreams.get( 0 ).getStepname() ) ); retval.append( XMLHandler.addTagValue( "compare", infoStreams.get( 1 ).getStepname() ) ); retval.append( " <compare>" + Const.CR ); retval.append( " </compare>" + Const.CR ); return retval.toString(); } private void readData( Node stepnode ) throws KettleXMLException { try { Node keysnode = XMLHandler.getSubNode( stepnode, "keys" ); Node valuesnode = XMLHandler.getSubNode( stepnode, "values" ); int nrKeys = XMLHandler.countNodes( keysnode, "key" ); int nrValues = XMLHandler.countNodes( valuesnode, "value" ); allocate( nrKeys, nrValues ); for ( int i = 0; i < nrKeys; i++ ) { Node keynode = XMLHandler.getSubNodeByNr( keysnode, "key", i ); keyFields[i] = XMLHandler.getNodeValue( keynode ); } for ( int i = 0; i < nrValues; i++ ) { Node valuenode = XMLHandler.getSubNodeByNr( valuesnode, "value", i ); valueFields[i] = XMLHandler.getNodeValue( valuenode ); } flagField = XMLHandler.getTagValue( stepnode, "flag_field" ); List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface referenceStream = infoStreams.get( 0 ); StreamInterface compareStream = infoStreams.get( 1 ); compareStream.setSubject( XMLHandler.getTagValue( stepnode, "compare" ) ); referenceStream.setSubject( XMLHandler.getTagValue( stepnode, "reference" ) ); } catch ( Exception e ) { throw new KettleXMLException( BaseMessages.getString( PKG, "MergeRowsMeta.Exception.UnableToLoadStepInfo" ), e ); } } @Override public void setDefault() { flagField = "flagfield"; allocate( 0, 0 ); } @Override public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException { try { int nrKeys = rep.countNrStepAttributes( id_step, "key_field" ); int nrValues = rep.countNrStepAttributes( id_step, "value_field" ); allocate( nrKeys, nrValues ); for ( int i = 0; i < nrKeys; i++ ) { keyFields[i] = rep.getStepAttributeString( id_step, i, "key_field" ); } for ( int i = 0; i < nrValues; i++ ) { valueFields[i] = rep.getStepAttributeString( id_step, i, "value_field" ); } flagField = rep.getStepAttributeString( id_step, "flag_field" ); List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface referenceStream = infoStreams.get( 0 ); StreamInterface compareStream = infoStreams.get( 1 ); referenceStream.setSubject( rep.getStepAttributeString( id_step, "reference" ) ); compareStream.setSubject( rep.getStepAttributeString( id_step, "compare" ) ); } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( PKG, "MergeRowsMeta.Exception.UnexpectedErrorReadingStepInfo" ), e ); } } @Override public void searchInfoAndTargetSteps( List<StepMeta> steps ) { for ( StreamInterface stream : getStepIOMeta().getInfoStreams() ) { stream.setStepMeta( StepMeta.findStep( steps, (String) stream.getSubject() ) ); } } @Override public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException { try { for ( int i = 0; i < keyFields.length; i++ ) { rep.saveStepAttribute( id_transformation, id_step, i, "key_field", keyFields[i] ); } for ( int i = 0; i < valueFields.length; i++ ) { rep.saveStepAttribute( id_transformation, id_step, i, "value_field", valueFields[i] ); } rep.saveStepAttribute( id_transformation, id_step, "flag_field", flagField ); List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface referenceStream = infoStreams.get( 0 ); StreamInterface compareStream = infoStreams.get( 1 ); rep.saveStepAttribute( id_transformation, id_step, "reference", referenceStream.getStepname() ); rep.saveStepAttribute( id_transformation, id_step, "compare", compareStream.getStepname() ); } catch ( Exception e ) { throw new KettleException( BaseMessages.getString( PKG, "MergeRowsMeta.Exception.UnableToSaveStepInfo" ) + id_step, e ); } } public boolean chosesTargetSteps() { return false; } public String[] getTargetSteps() { return null; } @Override public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException { // We don't have any input fields here in "r" as they are all info fields. // So we just merge in the info fields. // if ( info != null ) { boolean found = false; for ( int i = 0; i < info.length && !found; i++ ) { if ( info[i] != null ) { r.mergeRowMeta( info[i] ); found = true; } } } if ( Utils.isEmpty( flagField ) ) { throw new KettleStepException( BaseMessages.getString( PKG, "MergeRowsMeta.Exception.FlagFieldNotSpecified" ) ); } ValueMetaInterface flagFieldValue = new ValueMetaString( flagField ); flagFieldValue.setOrigin( name ); r.addValueMeta( flagFieldValue ); } @Override public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space, Repository repository, IMetaStore metaStore ) { CheckResult cr; List<StreamInterface> infoStreams = getStepIOMeta().getInfoStreams(); StreamInterface referenceStream = infoStreams.get( 0 ); StreamInterface compareStream = infoStreams.get( 1 ); if ( referenceStream.getStepname() != null && compareStream.getStepname() != null ) { cr = new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG, "MergeRowsMeta.CheckResult.SourceStepsOK" ), stepMeta ); remarks.add( cr ); } else if ( referenceStream.getStepname() == null && compareStream.getStepname() == null ) { cr = new CheckResult( CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString( PKG, "MergeRowsMeta.CheckResult.SourceStepsMissing" ), stepMeta ); remarks.add( cr ); } else { cr = new CheckResult( CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString( PKG, "MergeRowsMeta.CheckResult.OneSourceStepMissing" ), stepMeta ); remarks.add( cr ); } } @Override public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans trans ) { return new MergeRows( stepMeta, stepDataInterface, cnr, tr, trans ); } @Override public StepDataInterface getStepData() { return new MergeRowsData(); } /** * Returns the Input/Output metadata for this step. */ @Override public StepIOMetaInterface getStepIOMeta() { if ( ioMeta == null ) { ioMeta = new StepIOMeta( true, true, false, false, false, false ); ioMeta.addStream( new Stream( StreamType.INFO, null, BaseMessages.getString( PKG, "MergeRowsMeta.InfoStream.FirstStream.Description" ), StreamIcon.INFO, null ) ); ioMeta.addStream( new Stream( StreamType.INFO, null, BaseMessages.getString( PKG, "MergeRowsMeta.InfoStream.SecondStream.Description" ), StreamIcon.INFO, null ) ); } return ioMeta; } @Override public void resetStepIoMeta() { } @Override public TransformationType[] getSupportedTransformationTypes() { return new TransformationType[] { TransformationType.Normal, }; } }
package com.example.bluetoothgatt; import android.annotation.TargetApi; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.ParcelUuid; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * Created by Dave Smith * Double Encore, Inc. * BeaconActivity */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class BeaconLollipopActivity extends Activity { private static final String TAG = "BeaconActivity"; private BluetoothAdapter mBluetoothAdapter; private BluetoothLeScanner mBluetoothLeScanner; /* Collect unique devices discovered, keyed by address */ private HashMap<String, TemperatureBeacon> mBeacons; private BeaconAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarIndeterminate(true); /* * We are going to display all the device beacons that we discover * in a list, using a custom adapter implementation */ ListView list = new ListView(this); mAdapter = new BeaconAdapter(this); list.setAdapter(mAdapter); setContentView(list); /* * Bluetooth in Android 4.3+ is accessed via the BluetoothManager, rather than * the old static BluetoothAdapter.getInstance() */ BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); mBluetoothAdapter = manager.getAdapter(); mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); mBeacons = new HashMap<String, TemperatureBeacon>(); } @Override protected void onResume() { super.onResume(); /* * We need to enforce that Bluetooth is first enabled, and take the * user to settings to enable it if they have not done so. */ if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { //Bluetooth is disabled Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(enableBtIntent); finish(); return; } /* * Check for Bluetooth LE Support. In production, our manifest entry will keep this * from installing on these devices, but this will allow test devices or other * sideloads to report whether or not the feature exists. */ if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "No LE Support.", Toast.LENGTH_SHORT).show(); finish(); return; } //Begin scanning for LE devices startScan(); } @Override protected void onPause() { super.onPause(); //Cancel scan in progress stopScan(); } private void startScan() { //Scan for devices advertising the thermometer service ScanFilter beaconFilter = new ScanFilter.Builder() .setServiceUuid(TemperatureBeacon.THERM_SERVICE) .build(); ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>(); filters.add(beaconFilter); ScanSettings settings = new ScanSettings.Builder() .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build(); mBluetoothLeScanner.startScan(filters, settings, mScanCallback); } private void stopScan() { mBluetoothLeScanner.stopScan(mScanCallback); } private ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { Log.d(TAG, "onScanResult"); processResult(result); } @Override public void onBatchScanResults(List<ScanResult> results) { Log.d(TAG, "onBatchScanResults: "+results.size()+" results"); for (ScanResult result : results) { processResult(result); } } @Override public void onScanFailed(int errorCode) { Log.w(TAG, "LE Scan Failed: "+errorCode); } private void processResult(ScanResult result) { Log.i(TAG, "New LE Device: " + result.getDevice().getName() + " @ " + result.getRssi()); /* * Create a new beacon from the list of obtains AD structures * and pass it up to the main thread */ TemperatureBeacon beacon = new TemperatureBeacon(result.getScanRecord(), result.getDevice().getAddress(), result.getRssi()); mHandler.sendMessage(Message.obtain(null, 0, beacon)); } }; /* * We have a Handler to process scan results on the main thread, * add them to our list adapter, and update the view */ private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { TemperatureBeacon beacon = (TemperatureBeacon) msg.obj; mBeacons.put(beacon.getName(), beacon); mAdapter.setNotifyOnChange(false); mAdapter.clear(); mAdapter.addAll(mBeacons.values()); mAdapter.notifyDataSetChanged(); } }; /* * A custom adapter implementation that displays the TemperatureBeacon * element data in columns, and also varies the text color of each row * by the temperature values of the beacon */ private static class BeaconAdapter extends ArrayAdapter<TemperatureBeacon> { public BeaconAdapter(Context context) { super(context, 0); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()) .inflate(R.layout.item_beacon_list, parent, false); } TemperatureBeacon beacon = getItem(position); //Set color based on temperature final int textColor = getTemperatureColor(beacon.getCurrentTemp()); TextView nameView = (TextView) convertView.findViewById(R.id.text_name); nameView.setText(beacon.getName()); nameView.setTextColor(textColor); TextView tempView = (TextView) convertView.findViewById(R.id.text_temperature); tempView.setText(String.format("%.1f\u00B0C", beacon.getCurrentTemp())); tempView.setTextColor(textColor); TextView addressView = (TextView) convertView.findViewById(R.id.text_address); addressView.setText(beacon.getAddress()); addressView.setTextColor(textColor); TextView rssiView = (TextView) convertView.findViewById(R.id.text_rssi); rssiView.setText(String.format("%ddBm", beacon.getSignal())); rssiView.setTextColor(textColor); return convertView; } private int getTemperatureColor(float temperature) { //Color range from 0 - 40 degC float clipped = Math.max(0f, Math.min(40f, temperature)); float scaled = ((40f - clipped) / 40f) * 255f; int blue = Math.round(scaled); int red = 255 - blue; return Color.rgb(red, 0, blue); } } }
// Copyright 2012 Massachusetts Institute of Technology. All Rights Reserved. package com.google.appinventor.client.boxes; import com.google.appinventor.client.Images; import com.google.appinventor.client.Ode; import com.google.appinventor.client.TranslationDesignerPallete; import com.google.appinventor.client.editor.simple.components.MockForm; import com.google.appinventor.client.editor.youngandroid.BlockDrawerSelectionListener; import com.google.appinventor.client.explorer.SourceStructureExplorer; import com.google.appinventor.client.explorer.SourceStructureExplorerItem; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.client.widgets.boxes.Box; import com.google.common.collect.Maps; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.TreeItem; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static com.google.appinventor.client.Ode.MESSAGES; /** * Box implementation for block selector. Shows a tree containing the built-in * blocks as well as the components for the current form. Clicking on an item * opens the blocks drawer for the item (or closes it if it was already open). * This box shares screen real estate with the SourceStructureBox. It uses a * SourceStructureExplorer to handle the components part of the tree. * * @author [email protected] (Sharon Perl) * */ public final class BlockSelectorBox extends Box { private static class BlockSelectorItem implements SourceStructureExplorerItem { BlockSelectorItem() { } @Override public void onSelected() { } @Override public void onStateChange(boolean open) { } @Override public boolean canRename() { return false; } @Override public void rename() { } @Override public boolean canDelete() { return false; } @Override public void delete() { } } // Singleton block selector box instance // Starts out not visible. call setVisible(true) to make it visible private static final BlockSelectorBox INSTANCE = new BlockSelectorBox(); private static final String BUILTIN_DRAWER_NAMES[] = { "Control", "Logic", "Math", "Text", "Lists", "Colors", "Variables", "Procedures" }; private static final Images images = Ode.getImageBundle(); private static final Map<String, ImageResource> bundledImages = Maps.newHashMap(); // Source structure explorer (for components and built-in blocks) private final SourceStructureExplorer sourceStructureExplorer; private List<BlockDrawerSelectionListener> drawerListeners; /** * Return the singleton BlockSelectorBox box. * * @return block selector box */ public static BlockSelectorBox getBlockSelectorBox() { return INSTANCE; } /** * Creates new block selector box. */ private BlockSelectorBox() { super(MESSAGES.blockSelectorBoxCaption(), 300, // height false, // minimizable false); // removable sourceStructureExplorer = new SourceStructureExplorer(); setContent(sourceStructureExplorer); setVisible(false); drawerListeners = new ArrayList<BlockDrawerSelectionListener>(); } private static void initBundledImages() { bundledImages.put("Control", images.control()); bundledImages.put("Logic", images.logic()); bundledImages.put("Math", images.math()); bundledImages.put("Text", images.text()); bundledImages.put("Lists", images.lists()); bundledImages.put("Colors", images.colors()); bundledImages.put("Variables", images.variables()); bundledImages.put("Procedures", images.procedures()); } /** * Returns source structure explorer associated with box. * * @return source structure explorer */ public SourceStructureExplorer getSourceStructureExplorer() { return sourceStructureExplorer; } /** * Constructs a tree item for built-in blocks. * * @return tree item */ public TreeItem getBuiltInBlocksTree() { initBundledImages(); TreeItem builtinNode = new TreeItem(new HTML("<span>" + MESSAGES.builtinBlocksLabel() + "</span>")); for (final String drawerName : BUILTIN_DRAWER_NAMES) { Image drawerImage = new Image(bundledImages.get(drawerName)); TreeItem itemNode = new TreeItem(new HTML("<span>" + drawerImage + getBuiltinDrawerNames(drawerName) + "</span>")); SourceStructureExplorerItem sourceItem = new BlockSelectorItem() { @Override public void onSelected() { fireBuiltinDrawerSelected(drawerName); } }; itemNode.setUserObject(sourceItem); builtinNode.addItem(itemNode); } builtinNode.setState(true); return builtinNode; } /** * Given the drawerName, return the name in current language setting */ private String getBuiltinDrawerNames(String drawerName) { String name; OdeLog.wlog("getBuiltinDrawerNames: drawerName = " + drawerName); if (drawerName.equals("Control")) { name = MESSAGES.builtinControlLabel(); } else if (drawerName.equals("Logic")) { name = MESSAGES.builtinLogicLabel(); } else if (drawerName.equals("Math")) { name = MESSAGES.builtinMathLabel(); } else if (drawerName.equals("Text")) { name = MESSAGES.builtinTextLabel(); } else if (drawerName.equals("Lists")) { name = MESSAGES.builtinListsLabel(); } else if (drawerName.equals("Colors")) { name = MESSAGES.builtinColorsLabel(); } else if (drawerName.equals("Variables")) { name = MESSAGES.builtinVariablesLabel(); } else if (drawerName.equals("Procedures")) { name = MESSAGES.builtinProceduresLabel(); } else { name = drawerName; } return name; } /** * Constructs a tree item for generic ("Advanced") component blocks for * component types that appear in form. * * @param form * only component types that appear in this Form will be included * @return tree item for this form */ public TreeItem getGenericComponentsTree(MockForm form) { Map<String, String> typesAndIcons = Maps.newHashMap(); form.collectTypesAndIcons(typesAndIcons); TreeItem advanced = new TreeItem(new HTML("<span>" + MESSAGES.anyComponentLabel() + "</span>")); List<String> typeList = new ArrayList<String>(typesAndIcons.keySet()); Collections.sort(typeList); for (final String typeName : typeList) { TreeItem itemNode = new TreeItem(new HTML("<span>" + typesAndIcons.get(typeName) + MESSAGES.textAnyComponentLabel() + TranslationDesignerPallete.getCorrespondingString(typeName) + "</span>")); SourceStructureExplorerItem sourceItem = new BlockSelectorItem() { @Override public void onSelected() { fireGenericDrawerSelected(typeName); } }; itemNode.setUserObject(sourceItem); advanced.addItem(itemNode); } return advanced; } public void addBlockDrawerSelectionListener(BlockDrawerSelectionListener listener) { drawerListeners.add(listener); } public void removeBlockDrawerSelectionListener(BlockDrawerSelectionListener listener) { drawerListeners.remove(listener); } private void fireBuiltinDrawerSelected(String drawerName) { for (BlockDrawerSelectionListener listener : drawerListeners) { listener.onBuiltinDrawerSelected(drawerName); } } private void fireGenericDrawerSelected(String drawerName) { for (BlockDrawerSelectionListener listener : drawerListeners) { listener.onGenericDrawerSelected(drawerName); } } }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.modules.core; import javax.annotation.Nullable; import java.util.Comparator; import java.util.PriorityQueue; import java.util.concurrent.atomic.AtomicBoolean; import android.util.SparseArray; import android.view.Choreographer; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.WritableArray; import com.facebook.react.uimanager.ReactChoreographer; import com.facebook.react.common.SystemClock; import com.facebook.infer.annotation.Assertions; /** * Native module for JS timer execution. Timers fire on frame boundaries. */ public final class Timing extends ReactContextBaseJavaModule implements LifecycleEventListener { private static class Timer { private final int mCallbackID; private final boolean mRepeat; private final int mInterval; private long mTargetTime; private Timer(int callbackID, long initialTargetTime, int duration, boolean repeat) { mCallbackID = callbackID; mTargetTime = initialTargetTime; mInterval = duration; mRepeat = repeat; } } private class FrameCallback implements Choreographer.FrameCallback { /** * Calls all timers that have expired since the last time this frame callback was called. */ @Override public void doFrame(long frameTimeNanos) { if (isPaused.get()) { return; } long frameTimeMillis = frameTimeNanos / 1000000; WritableArray timersToCall = null; synchronized (mTimerGuard) { while (!mTimers.isEmpty() && mTimers.peek().mTargetTime < frameTimeMillis) { Timer timer = mTimers.poll(); if (timersToCall == null) { timersToCall = Arguments.createArray(); } timersToCall.pushInt(timer.mCallbackID); if (timer.mRepeat) { timer.mTargetTime = frameTimeMillis + timer.mInterval; mTimers.add(timer); } else { mTimerIdsToTimers.remove(timer.mCallbackID); } } } if (timersToCall != null) { Assertions.assertNotNull(mJSTimersModule).callTimers(timersToCall); } Assertions.assertNotNull(mReactChoreographer) .postFrameCallback(ReactChoreographer.CallbackType.TIMERS_EVENTS, this); } } private final Object mTimerGuard = new Object(); private final PriorityQueue<Timer> mTimers; private final SparseArray<Timer> mTimerIdsToTimers; private final AtomicBoolean isPaused = new AtomicBoolean(false); private final FrameCallback mFrameCallback = new FrameCallback(); private @Nullable ReactChoreographer mReactChoreographer; private @Nullable JSTimersExecution mJSTimersModule; private boolean mFrameCallbackPosted = false; public Timing(ReactApplicationContext reactContext) { super(reactContext); // We store timers sorted by finish time. mTimers = new PriorityQueue<Timer>( 11, // Default capacity: for some reason they don't expose a (Comparator) constructor new Comparator<Timer>() { @Override public int compare(Timer lhs, Timer rhs) { long diff = lhs.mTargetTime - rhs.mTargetTime; if (diff == 0) { return 0; } else if (diff < 0) { return -1; } else { return 1; } } }); mTimerIdsToTimers = new SparseArray<Timer>(); } @Override public void initialize() { // Safe to acquire choreographer here, as initialize() is invoked from UI thread. mReactChoreographer = ReactChoreographer.getInstance(); mJSTimersModule = getReactApplicationContext().getCatalystInstance() .getJSModule(JSTimersExecution.class); getReactApplicationContext().addLifecycleEventListener(this); setChoreographerCallback(); } @Override public void onHostPause() { isPaused.set(true); clearChoreographerCallback(); } @Override public void onHostDestroy() { clearChoreographerCallback(); } @Override public void onHostResume() { isPaused.set(false); // TODO(5195192) Investigate possible problems related to restarting all tasks at the same // moment setChoreographerCallback(); } @Override public void onCatalystInstanceDestroy() { clearChoreographerCallback(); } private void setChoreographerCallback() { if (!mFrameCallbackPosted) { Assertions.assertNotNull(mReactChoreographer).postFrameCallback( ReactChoreographer.CallbackType.TIMERS_EVENTS, mFrameCallback); mFrameCallbackPosted = true; } } private void clearChoreographerCallback() { if (mFrameCallbackPosted) { Assertions.assertNotNull(mReactChoreographer).removeFrameCallback( ReactChoreographer.CallbackType.TIMERS_EVENTS, mFrameCallback); mFrameCallbackPosted = false; } } @Override public String getName() { return "RKTiming"; } @ReactMethod public void createTimer( final int callbackID, final int duration, final double jsSchedulingTime, final boolean repeat) { // Adjust for the amount of time it took for native to receive the timer registration call long adjustedDuration = (long) Math.max( 0, jsSchedulingTime - SystemClock.currentTimeMillis() + duration); long initialTargetTime = SystemClock.nanoTime() / 1000000 + adjustedDuration; Timer timer = new Timer(callbackID, initialTargetTime, duration, repeat); synchronized (mTimerGuard) { mTimers.add(timer); mTimerIdsToTimers.put(callbackID, timer); } } @ReactMethod public void deleteTimer(int timerId) { synchronized (mTimerGuard) { Timer timer = mTimerIdsToTimers.get(timerId); if (timer != null) { // We may have already called/removed it mTimerIdsToTimers.remove(timerId); mTimers.remove(timer); } } } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.adapters.saml; import org.apache.catalina.Context; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.authenticator.FormAuthenticator; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.keycloak.adapters.spi.AuthChallenge; import org.keycloak.adapters.spi.AuthOutcome; import org.keycloak.adapters.spi.HttpFacade; import org.keycloak.adapters.spi.InMemorySessionIdMapper; import org.keycloak.adapters.spi.SessionIdMapper; import org.keycloak.adapters.saml.config.parsers.DeploymentBuilder; import org.keycloak.adapters.saml.config.parsers.ResourceLoader; import org.keycloak.adapters.tomcat.CatalinaHttpFacade; import org.keycloak.adapters.tomcat.CatalinaUserSessionManagement; import org.keycloak.adapters.tomcat.GenericPrincipalFactory; import org.keycloak.saml.common.exceptions.ParsingException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; /** * Keycloak authentication valve * * @author <a href="mailto:[email protected]">Davide Ungari</a> * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public abstract class AbstractSamlAuthenticatorValve extends FormAuthenticator implements LifecycleListener { public static final String TOKEN_STORE_NOTE = "TOKEN_STORE_NOTE"; private final static Logger log = Logger.getLogger(""+AbstractSamlAuthenticatorValve.class); protected CatalinaUserSessionManagement userSessionManagement = new CatalinaUserSessionManagement(); protected SamlDeploymentContext deploymentContext; protected SessionIdMapper mapper = new InMemorySessionIdMapper(); @Override public void lifecycleEvent(LifecycleEvent event) { if (Lifecycle.START_EVENT.equals(event.getType())) { cache = false; } else if (Lifecycle.AFTER_START_EVENT.equals(event.getType())) { keycloakInit(); } else if (event.getType() == Lifecycle.BEFORE_STOP_EVENT) { beforeStop(); } } protected void logoutInternal(Request request) { CatalinaHttpFacade facade = new CatalinaHttpFacade(null, request); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); SamlSessionStore tokenStore = getSessionStore(request, facade, deployment); tokenStore.logoutAccount(); request.setUserPrincipal(null); } @SuppressWarnings("UseSpecificCatch") public void keycloakInit() { // Possible scenarios: // 1) The deployment has a keycloak.config.resolver specified and it exists: // Outcome: adapter uses the resolver // 2) The deployment has a keycloak.config.resolver and isn't valid (doesn't exists, isn't a resolver, ...) : // Outcome: adapter is left unconfigured // 3) The deployment doesn't have a keycloak.config.resolver , but has a keycloak.json (or equivalent) // Outcome: adapter uses it // 4) The deployment doesn't have a keycloak.config.resolver nor keycloak.json (or equivalent) // Outcome: adapter is left unconfigured String configResolverClass = context.getServletContext().getInitParameter("keycloak.config.resolver"); if (configResolverClass != null) { try { throw new RuntimeException("Not implemented yet"); //KeycloakConfigResolver configResolver = (KeycloakConfigResolver) context.getLoader().getClassLoader().loadClass(configResolverClass).newInstance(); //deploymentContext = new SamlDeploymentContext(configResolver); //log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass); } catch (Exception ex) { log.log(Level.FINE, "The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[]{configResolverClass, ex.getMessage()}); //deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment()); } } else { InputStream is = getConfigInputStream(context); final SamlDeployment deployment; if (is == null) { log.info("No adapter configuration. Keycloak is unconfigured and will deny all requests."); deployment = new DefaultSamlDeployment(); } else { try { ResourceLoader loader = new ResourceLoader() { @Override public InputStream getResourceAsStream(String resource) { return context.getServletContext().getResourceAsStream(resource); } }; deployment = new DeploymentBuilder().build(is, loader); } catch (ParsingException e) { throw new RuntimeException(e); } } deploymentContext = new SamlDeploymentContext(deployment); log.fine("Keycloak is using a per-deployment configuration."); } context.getServletContext().setAttribute(SamlDeploymentContext.class.getName(), deploymentContext); } protected void beforeStop() { } private static InputStream getConfigFromServletContext(ServletContext servletContext) { String xml = servletContext.getInitParameter(AdapterConstants.AUTH_DATA_PARAM_NAME); if (xml == null) { return null; } log.finest("**** using " + AdapterConstants.AUTH_DATA_PARAM_NAME); log.finest(xml); return new ByteArrayInputStream(xml.getBytes()); } private static InputStream getConfigInputStream(Context context) { InputStream is = getConfigFromServletContext(context.getServletContext()); if (is == null) { String path = context.getServletContext().getInitParameter("keycloak.config.file"); if (path == null) { log.fine("**** using /WEB-INF/keycloak-saml.xml"); is = context.getServletContext().getResourceAsStream("/WEB-INF/keycloak-saml.xml"); } else { try { is = new FileInputStream(path); } catch (FileNotFoundException e) { log.log(Level.SEVERE, "NOT FOUND {0}", path); throw new RuntimeException(e); } } } return is; } @Override public void invoke(Request request, Response response) throws IOException, ServletException { log.fine("*********************** SAML ************"); CatalinaHttpFacade facade = new CatalinaHttpFacade(response, request); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); if (request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml")) { if (deployment != null && deployment.isConfigured()) { SamlSessionStore tokenStore = getSessionStore(request, facade, deployment); SamlAuthenticator authenticator = new CatalinaSamlEndpoint(facade, deployment, tokenStore); executeAuthenticator(request, response, facade, deployment, authenticator); return; } } try { getSessionStore(request, facade, deployment).isLoggedIn(); // sets request UserPrincipal if logged in. we do this so that the UserPrincipal is available on unsecured, unconstrainted URLs super.invoke(request, response); } finally { } } protected abstract GenericPrincipalFactory createPrincipalFactory(); protected abstract boolean forwardToErrorPageInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException; protected void forwardToLogoutPage(Request request, HttpServletResponse response,SamlDeployment deployment) { RequestDispatcher disp = request.getRequestDispatcher(deployment.getLogoutPage()); //make sure the login page is never cached response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); try { disp.forward(request.getRequest(), response); } catch (ServletException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } protected boolean authenticateInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException { log.fine("authenticateInternal"); CatalinaHttpFacade facade = new CatalinaHttpFacade(response, request); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { log.fine("deployment not configured"); return false; } SamlSessionStore tokenStore = getSessionStore(request, facade, deployment); SamlAuthenticator authenticator = new CatalinaSamlAuthenticator(facade, deployment, tokenStore); return executeAuthenticator(request, response, facade, deployment, authenticator); } protected boolean executeAuthenticator(Request request, HttpServletResponse response, CatalinaHttpFacade facade, SamlDeployment deployment, SamlAuthenticator authenticator) { AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { log.fine("AUTHENTICATED"); if (facade.isEnded()) { return false; } return true; } if (outcome == AuthOutcome.LOGGED_OUT) { logoutInternal(request); if (deployment.getLogoutPage() != null) { forwardToLogoutPage(request, response, deployment); } log.fine("Logging OUT"); return false; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { log.fine("challenge"); challenge.challenge(facade); } return false; } public void keycloakSaveRequest(Request request) throws IOException { saveRequest(request, request.getSessionInternal(true)); } public boolean keycloakRestoreRequest(Request request) { try { return restoreRequest(request, request.getSessionInternal()); } catch (IOException e) { throw new RuntimeException(e); } } protected SamlSessionStore getSessionStore(Request request, HttpFacade facade, SamlDeployment resolvedDeployment) { SamlSessionStore store = (SamlSessionStore)request.getNote(TOKEN_STORE_NOTE); if (store != null) { return store; } store = createSessionStore(request, facade, resolvedDeployment); request.setNote(TOKEN_STORE_NOTE, store); return store; } protected SamlSessionStore createSessionStore(Request request, HttpFacade facade, SamlDeployment resolvedDeployment) { SamlSessionStore store; store = new CatalinaSamlSessionStore(userSessionManagement, createPrincipalFactory(), mapper, request, this, facade, resolvedDeployment); return store; } }
package org.hisp.dhis.analytics.security; /* * Copyright (c) 2004-2017, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hisp.dhis.analytics.AnalyticsSecurityManager; import org.hisp.dhis.analytics.DataQueryParams; import org.hisp.dhis.analytics.event.EventQueryParams; import org.hisp.dhis.common.*; import org.hisp.dhis.dataapproval.DataApproval; import org.hisp.dhis.dataapproval.DataApprovalLevel; import org.hisp.dhis.dataapproval.DataApprovalLevelService; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.setting.SystemSettingManager; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Lars Helge Overland */ public class DefaultAnalyticsSecurityManager implements AnalyticsSecurityManager { private static final Log log = LogFactory.getLog( DefaultAnalyticsSecurityManager.class ); private static final String AUTH_VIEW_EVENT_ANALYTICS = "F_VIEW_EVENT_ANALYTICS"; @Autowired private DataApprovalLevelService approvalLevelService; @Autowired private SystemSettingManager systemSettingManager; @Autowired private DimensionService dimensionService; @Autowired private CurrentUserService currentUserService; // ------------------------------------------------------------------------- // AnalyticsSecurityManager implementation // ------------------------------------------------------------------------- @Override public void decideAccess( DataQueryParams params ) { // --------------------------------------------------------------------- // Check current user data view access to org units // --------------------------------------------------------------------- User user = currentUserService.getCurrentUser(); List<DimensionalItemObject> queryOrgUnits = params.getDimensionOrFilterItems( DimensionalObject.ORGUNIT_DIM_ID ); if ( queryOrgUnits.isEmpty() || user == null || !user.hasDataViewOrganisationUnit() ) { return; // Allow if no } Set<OrganisationUnit> viewOrgUnits = user.getDataViewOrganisationUnits(); for ( DimensionalItemObject object : queryOrgUnits ) { OrganisationUnit queryOrgUnit = (OrganisationUnit) object; if ( !queryOrgUnit.isDescendant( viewOrgUnits ) ) { throw new IllegalQueryException( String.format( "User: %s is not allowed to view org unit: %s", user.getUsername(), queryOrgUnit.getUid() ) ); } } } @Override public void decideAccessEventQuery( EventQueryParams params ) { User user = currentUserService.getCurrentUser(); decideAccess( params ); if ( user != null && !user.isAuthorized( AUTH_VIEW_EVENT_ANALYTICS ) ) { throw new IllegalQueryException( String.format( "User: %s is not allowed to view event analytics", user.getUsername() ) ); } } @Override public User getCurrentUser( DataQueryParams params ) { return params != null && params.hasCurrentUser() ? params.getCurrentUser() : currentUserService.getCurrentUser(); } @Override public DataQueryParams withDataApprovalConstraints( DataQueryParams params ) { DataQueryParams.Builder paramsBuilder = DataQueryParams.newBuilder( params ); User user = currentUserService.getCurrentUser(); boolean hideUnapprovedData = systemSettingManager.hideUnapprovedDataInAnalytics(); boolean canViewUnapprovedData = user != null ? user.getUserCredentials().isAuthorized( DataApproval.AUTH_VIEW_UNAPPROVED_DATA ) : true; if ( hideUnapprovedData && user != null ) { Map<OrganisationUnit, Integer> approvalLevels = null; if ( params.hasApprovalLevel() ) { // Set approval level from query DataApprovalLevel approvalLevel = approvalLevelService.getDataApprovalLevel( params.getApprovalLevel() ); if ( approvalLevel == null ) { throw new IllegalQueryException( String.format( "Approval level does not exist: %s", params.getApprovalLevel() ) ); } approvalLevels = approvalLevelService.getUserReadApprovalLevels( approvalLevel ); } else if ( !canViewUnapprovedData ) { // Set approval level from user level approvalLevels = approvalLevelService.getUserReadApprovalLevels(); } if ( approvalLevels != null && !approvalLevels.isEmpty() ) { paramsBuilder.withDataApprovalLevels( approvalLevels ); log.debug( String.format( "User: %s constrained by data approval levels: %s", user.getUsername(), approvalLevels.values() ) ); } } return paramsBuilder.build(); } @Override public DataQueryParams withDimensionConstraints( DataQueryParams params ) { DataQueryParams.Builder builder = DataQueryParams.newBuilder( params ); applyOrganisationUnitConstraint( builder, params ); applyUserConstraints( builder, params ); return builder.build(); } /** * Applies organisation unit security constraint. * * @param builder the data query parameters builder. * @param params the data query parameters. */ private void applyOrganisationUnitConstraint( DataQueryParams.Builder builder, DataQueryParams params ) { User user = currentUserService.getCurrentUser(); // --------------------------------------------------------------------- // Check if current user has data view organisation units // --------------------------------------------------------------------- if ( params == null || user == null || !user.hasDataViewOrganisationUnit() ) { return; } // --------------------------------------------------------------------- // Check if request already has organisation units specified // --------------------------------------------------------------------- if ( params.hasDimensionOrFilterWithItems( DimensionalObject.ORGUNIT_DIM_ID ) ) { return; } // ----------------------------------------------------------------- // Apply constraint as filter, and remove potential all-dimension // ----------------------------------------------------------------- builder.removeDimensionOrFilter( DimensionalObject.ORGUNIT_DIM_ID ); List<OrganisationUnit> orgUnits = new ArrayList<>( user.getDataViewOrganisationUnits() ); DimensionalObject constraint = new BaseDimensionalObject( DimensionalObject.ORGUNIT_DIM_ID, DimensionType.ORGANISATION_UNIT, orgUnits ); builder.addFilter( constraint ); log.debug( String.format( "User: %s constrained by data view organisation units", user.getUsername() ) ); } /** * Applies user security constraint. * * @param builder the data query parameters builder. * @param params the data query parameters. */ private void applyUserConstraints( DataQueryParams.Builder builder, DataQueryParams params ) { User user = currentUserService.getCurrentUser(); // --------------------------------------------------------------------- // Check if current user has dimension constraints // --------------------------------------------------------------------- if ( params == null || user == null || user.getUserCredentials() == null || !user.getUserCredentials().hasDimensionConstraints() ) { return; } Set<DimensionalObject> dimensionConstraints = user.getUserCredentials().getDimensionConstraints(); for ( DimensionalObject dimension : dimensionConstraints ) { // ----------------------------------------------------------------- // Check if constraint already is specified with items // ----------------------------------------------------------------- if ( params.hasDimensionOrFilterWithItems( dimension.getUid() ) ) { continue; } List<DimensionalItemObject> canReadItems = dimensionService.getCanReadDimensionItems( dimension.getDimension() ); // ----------------------------------------------------------------- // Check if current user has access to any items from constraint // ----------------------------------------------------------------- if ( canReadItems == null || canReadItems.isEmpty() ) { throw new IllegalQueryException( String.format( "Current user is constrained by a dimension but has access to no associated dimension items: %s", dimension.getDimension() ) ); } // ----------------------------------------------------------------- // Apply constraint as filter, and remove potential all-dimension // ----------------------------------------------------------------- builder.removeDimensionOrFilter( dimension.getDimension() ); DimensionalObject constraint = new BaseDimensionalObject( dimension.getDimension(), dimension.getDimensionType(), null, dimension.getDisplayName(), canReadItems ); builder.addFilter( constraint ); log.debug( String.format( "User: %s constrained by dimension: %s", user.getUsername(), constraint.getDimension() ) ); } } }
/* * (c) Copyright Christian P. Fries, Germany. Contact: [email protected]. * * Created on 28.11.2012 */ package net.finmath.marketdata.model; import java.io.Serializable; import java.time.LocalDate; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import net.finmath.marketdata.calibration.ParameterObject; import net.finmath.marketdata.model.curves.Curve; import net.finmath.marketdata.model.curves.DiscountCurve; import net.finmath.marketdata.model.curves.ForwardCurve; import net.finmath.marketdata.model.volatilities.VolatilitySurface; /** * Implements a collection of market data objects (e.g., discount curves, forward curve) * which provide interpolation of market data or other derived quantities * ("calibrated curves"). This can be seen as a model to be used in analytic pricing * formulas - hence this class is termed <code>AnalyticModelFromCurvesAndVols</code>. * * @author Christian Fries * @version 1.0 */ public class AnalyticModelFromCurvesAndVols implements AnalyticModel, Serializable, Cloneable { private static final long serialVersionUID = 6906386712907555046L; private final LocalDate referenceDate; private final Map<String, Curve> curvesMap = new HashMap<>(); private final Map<String, VolatilitySurface> volatilitySurfaceMap = new HashMap<>(); /** * Create an empty analytic model. */ public AnalyticModelFromCurvesAndVols() { referenceDate = null; } /** * Create an empty analytic model for a specified date. * * @param referenceDate The reference date that should be used for all curves and surfaces of this model. */ public AnalyticModelFromCurvesAndVols(final LocalDate referenceDate) { this.referenceDate = referenceDate; } /** * Create an analytic model with the given curves. * * @param curves The vector of curves. */ public AnalyticModelFromCurvesAndVols(final Curve[] curves) { for (final Curve curve : curves) { curvesMap.put(curve.getName(), curve); } referenceDate = null; } /** * Create an analytic model with the given curves. * * @param curves A collection of curves. */ public AnalyticModelFromCurvesAndVols(final Collection<Curve> curves) { for (final Curve curve : curves) { curvesMap.put(curve.getName(), curve); } referenceDate = null; } /** * Create an analytic model with the given curves for the specified reference date. * * @param referenceDate The reference date that should be used for all curves and surfaces of this model. * @param curves The vector of curves. */ public AnalyticModelFromCurvesAndVols(final LocalDate referenceDate, final Curve[] curves) { for (final Curve curve : curves) { curvesMap.put(curve.getName(), curve); final LocalDate curveDate = curve.getReferenceDate(); if(referenceDate != null && curveDate != null && ! referenceDate.equals(curveDate)) { throw new IllegalArgumentException("Reference date of curve "+curve.getName()+" does not match the reference date of the model."); } } this.referenceDate = referenceDate; } /** * Create an analytic model with the given curves for the specified reference date. * * @param referenceDate The reference date that should be used for all curves and surfaces of this model. * @param curves A collection of curves. */ public AnalyticModelFromCurvesAndVols(final LocalDate referenceDate, final Collection<Curve> curves) { for (final Curve curve : curves) { curvesMap.put(curve.getName(), curve); final LocalDate curveDate = curve.getReferenceDate(); if(referenceDate != null && curveDate != null && ! referenceDate.equals(curveDate)) { throw new IllegalArgumentException("Reference date of curve "+curve.getName()+" does not match the reference date of the model."); } } this.referenceDate = referenceDate; } /** * Create an analytic model for the specified reference date, together with curves and volatility surfaces, each with their specific name. * * @param referenceDate The reference date that should be used for all curves and surfaces of this model. * @param curvesMap A map containing all curves, together with their names they should have in the model. * @param volatilitySurfaceMap A map containing all volatility surfaces, together with their names they should have in the model. */ public AnalyticModelFromCurvesAndVols(final LocalDate referenceDate, final Map<String, Curve> curvesMap, final Map<String, VolatilitySurface> volatilitySurfaceMap) { this(referenceDate); this.curvesMap.putAll(curvesMap); this.volatilitySurfaceMap.putAll(volatilitySurfaceMap); } @Override public Curve getCurve(final String name) { return curvesMap.get(name); } @Override public Map<String, Curve> getCurves() { return Collections.unmodifiableMap(curvesMap); } @Override public AnalyticModel addCurve(final String name, final Curve curve) { final LocalDate curveDate = curve.getReferenceDate(); if(referenceDate != null && curveDate != null && ! referenceDate.equals(curveDate)) { throw new IllegalArgumentException("Reference date of curve does not match reference date of model."); } final AnalyticModelFromCurvesAndVols newModel = clone(); newModel.curvesMap.put(name, curve); return newModel; } public AnalyticModel addCurve(final Curve curve) { final LocalDate curveDate = curve.getReferenceDate(); if(referenceDate != null && curveDate != null && ! referenceDate.equals(curveDate)) { throw new IllegalArgumentException("Reference date of curve does not match reference date of model."); } final AnalyticModelFromCurvesAndVols newModel = clone(); newModel.curvesMap.put(curve.getName(), curve); return newModel; } @Override public AnalyticModel addCurves(final Curve... curves) { final Map<String, Curve> curvesMap = new HashMap<>(); for (final Curve curve : curves) { curvesMap.put(curve.getName(), curve); final LocalDate curveDate = curve.getReferenceDate(); if(referenceDate != null && curveDate != null && ! referenceDate.equals(curveDate) ) { throw new IllegalArgumentException("Reference date of curve "+curve.getName()+" does not match the reference date of the model."); } } final AnalyticModelFromCurvesAndVols newModel = clone(); newModel.curvesMap.putAll(curvesMap); return newModel; } @Override public AnalyticModel addCurves(final Set<Curve> curves) { final Map<String, Curve> curvesMap = new HashMap<>(); for (final Curve curve : curves) { curvesMap.put(curve.getName(), curve); final LocalDate curveDate = curve.getReferenceDate(); if(referenceDate != null && curveDate != null && ! referenceDate.equals(curveDate) ) { throw new IllegalArgumentException("Reference date of curve "+curve.getName()+" does not match the reference date of the model."); } } final AnalyticModelFromCurvesAndVols newModel = clone(); newModel.curvesMap.putAll(curvesMap); return newModel; } @Override public DiscountCurve getDiscountCurve(final String discountCurveName) { DiscountCurve discountCurve = null; final Curve curve = getCurve(discountCurveName); if(DiscountCurve.class.isInstance(curve)) { discountCurve = (DiscountCurve)curve; } return discountCurve; } @Override public ForwardCurve getForwardCurve(final String forwardCurveName) { ForwardCurve forwardCurve = null; final Curve curve = getCurve(forwardCurveName); if(ForwardCurve.class.isInstance(curve)) { forwardCurve = (ForwardCurve)curve; } return forwardCurve; } @Override public VolatilitySurface getVolatilitySurface(final String name) { return volatilitySurfaceMap.get(name); } @Override public Map<String, VolatilitySurface> getVolatilitySurfaces() { return Collections.unmodifiableMap(volatilitySurfaceMap); } public AnalyticModel addVolatilitySurface(final VolatilitySurface volatilitySurface) { final LocalDate surfaceDate = volatilitySurface.getReferenceDate(); if(referenceDate != null && surfaceDate != null && ! referenceDate.equals(surfaceDate)) { throw new IllegalArgumentException("Reference date of surface does not match reference date of model."); } final AnalyticModelFromCurvesAndVols newModel = clone(); newModel.volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface); return newModel; } @Override public AnalyticModel addVolatilitySurfaces(final VolatilitySurface... volatilitySurfaces) { final AnalyticModelFromCurvesAndVols newModel = clone(); for(final VolatilitySurface volatilitySurface : volatilitySurfaces) { newModel.volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface); final LocalDate surfaceDate = volatilitySurface.getReferenceDate(); if(referenceDate != null && surfaceDate != null && ! referenceDate.equals(surfaceDate) ) { throw new IllegalArgumentException("Reference date of surface "+volatilitySurface.getName()+" does not match the reference date of the model."); } } return newModel; } @Override public AnalyticModel addVolatilitySurfaces(final Set<VolatilitySurface> volatilitySurfaces) { final AnalyticModelFromCurvesAndVols newModel = clone(); for(final VolatilitySurface volatilitySurface : volatilitySurfaces) { newModel.volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface); final LocalDate surfaceDate = volatilitySurface.getReferenceDate(); if(referenceDate != null && surfaceDate != null && ! referenceDate.equals(surfaceDate) ) { throw new IllegalArgumentException("Reference date of surface "+volatilitySurface.getName()+" does not match the reference date of the model."); } } return newModel; } private void setCurve(final Curve curve) { curvesMap.put(curve.getName(), curve); } private void setVolatilitySurface(final VolatilitySurface volatilitySurface) { volatilitySurfaceMap.put(volatilitySurface.getName(), volatilitySurface); } private void set(final Object marketDataObject) { if(marketDataObject instanceof Curve) { setCurve((Curve)marketDataObject); } else if(marketDataObject instanceof VolatilitySurface) { setVolatilitySurface((VolatilitySurface)marketDataObject); } else { throw new IllegalArgumentException("Provided object is not of supported type."); } } @Override public AnalyticModelFromCurvesAndVols clone() { final AnalyticModelFromCurvesAndVols newModel = new AnalyticModelFromCurvesAndVols(referenceDate); newModel.curvesMap.putAll(curvesMap); newModel.volatilitySurfaceMap.putAll(volatilitySurfaceMap); return newModel; } @Override public AnalyticModel getCloneForParameter(final Map<ParameterObject, double[]> curveParameterPairs) throws CloneNotSupportedException { // Build the modified clone of this model final AnalyticModelFromCurvesAndVols modelClone = clone(); // Add modified clones of curves to model clone if(curveParameterPairs != null) { for(final Entry<ParameterObject,double[]> curveParameterPair : curveParameterPairs.entrySet()) { final ParameterObject newCurve = curveParameterPair.getKey().getCloneForParameter(curveParameterPair.getValue()); modelClone.set(newCurve); } } return modelClone; } @Override public String toString() { return "AnalyticModelFromCurvesAndVols: referenceDate=" + referenceDate + ", curves=" + curvesMap.keySet() + ", volatilitySurfaces=" + volatilitySurfaceMap.keySet(); } /** * Returns the reference date of the curves of this model. * * @return The reference date of the model. */ public LocalDate getReferenceDate() { return referenceDate; } }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES 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.openqa.selenium.chrome; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openqa.selenium.PageLoadStrategy; import org.openqa.selenium.UnexpectedAlertBehaviour; import org.openqa.selenium.remote.AcceptedW3CCapabilityKeys; import org.openqa.selenium.testing.TestUtilities; import org.openqa.selenium.testing.UnitTests; import java.io.File; import java.time.Duration; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.InstanceOfAssertFactories.LIST; import static org.assertj.core.api.InstanceOfAssertFactories.MAP; import static org.openqa.selenium.chrome.ChromeDriverLogLevel.OFF; import static org.openqa.selenium.chrome.ChromeDriverLogLevel.SEVERE; import static org.openqa.selenium.remote.CapabilityType.TIMEOUTS; @Category(UnitTests.class) public class ChromeOptionsTest { @Test public void optionsAsMapShouldBeImmutable() { Map<String, Object> options = new ChromeOptions().asMap(); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> options.put("browserType", "firefox")); Map<String, Object> googOptions = (Map<String, Object>) options.get(ChromeOptions.CAPABILITY); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> googOptions.put("binary", "")); List<String> extensions = (List<String>) googOptions.get("extensions"); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> extensions.add("x")); List<String> args = (List<String>) googOptions.get("args"); assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> args.add("-help")); } @Test public void canBuildLogLevelFromStringRepresentation() { assertThat(ChromeDriverLogLevel.fromString("off")).isEqualTo(OFF); assertThat(ChromeDriverLogLevel.fromString("SEVERE")).isEqualTo(SEVERE); } @Test public void canAddW3CCompliantOptions() { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.setBrowserVersion("99") .setPlatformName("9 3/4") .setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE) .setAcceptInsecureCerts(true) .setPageLoadStrategy(PageLoadStrategy.EAGER) .setStrictFileInteractability(true) .setImplicitWaitTimeout(Duration.ofSeconds(1)) .setPageLoadTimeout(Duration.ofSeconds(2)) .setScriptTimeout(Duration.ofSeconds(3)); Map<String, Object> mappedOptions = chromeOptions.asMap(); assertThat(mappedOptions.get("browserName")).isEqualTo("chrome"); assertThat(mappedOptions.get("browserVersion")).isEqualTo("99"); assertThat(mappedOptions.get("platformName")).isEqualTo("9 3/4"); assertThat(mappedOptions.get("unhandledPromptBehavior").toString()).isEqualTo("ignore"); assertThat(mappedOptions.get("acceptInsecureCerts")).isEqualTo(true); assertThat(mappedOptions.get("pageLoadStrategy").toString()).isEqualTo("eager"); assertThat(mappedOptions.get("strictFileInteractability")).isEqualTo(true); Map<String, Long> expectedTimeouts = new HashMap<>(); expectedTimeouts.put("implicit", 1000L); expectedTimeouts.put("pageLoad", 2000L); expectedTimeouts.put("script", 3000L); assertThat(expectedTimeouts).isEqualTo(mappedOptions.get("timeouts")); } @Test public void canAddSequentialTimeouts() { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.setImplicitWaitTimeout(Duration.ofSeconds(1)); Map<String, Object> mappedOptions = chromeOptions.asMap(); Map<String, Long> expectedTimeouts = new HashMap<>(); expectedTimeouts.put("implicit", 1000L); assertThat(expectedTimeouts).isEqualTo(mappedOptions.get("timeouts")); chromeOptions.setPageLoadTimeout(Duration.ofSeconds(2)); expectedTimeouts.put("pageLoad", 2000L); Map<String, Object> mappedOptions2 = chromeOptions.asMap(); assertThat(expectedTimeouts).isEqualTo(mappedOptions2.get("timeouts")); } @Test public void mixAddingTimeoutsCapsAndSetter() { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.setCapability(TIMEOUTS, Map.of("implicit", 1000)); chromeOptions.setPageLoadTimeout(Duration.ofSeconds(2)); Map<String, Number> expectedTimeouts = new HashMap<>(); expectedTimeouts.put("implicit", 1000); expectedTimeouts.put("pageLoad", 2000L); assertThat(chromeOptions.asMap().get("timeouts")).isEqualTo(expectedTimeouts); } @Test public void mergingOptionsMergesArguments() { ChromeOptions one = new ChromeOptions().addArguments("verbose"); ChromeOptions two = new ChromeOptions().addArguments("silent"); ChromeOptions merged = one.merge(two); assertThat(merged.asMap()).asInstanceOf(MAP) .extractingByKey(ChromeOptions.CAPABILITY).asInstanceOf(MAP) .extractingByKey("args").asInstanceOf(LIST) .containsExactly("verbose", "silent"); } @Test public void mergingOptionsMergesEncodedExtensions() { String ext1 = Base64.getEncoder().encodeToString("ext1".getBytes()); String ext2 = Base64.getEncoder().encodeToString("ext2".getBytes()); ChromeOptions one = new ChromeOptions().addEncodedExtensions(ext1); ChromeOptions two = new ChromeOptions().addEncodedExtensions(ext2); ChromeOptions merged = one.merge(two); assertThat(merged.asMap()).asInstanceOf(MAP) .extractingByKey(ChromeOptions.CAPABILITY).asInstanceOf(MAP) .extractingByKey("extensions").asInstanceOf(LIST) .containsExactly(ext1, ext2); } @Test public void mergingOptionsMergesExtensions() { File ext1 = TestUtilities.createTmpFile("ext1"); String ext1Encoded = Base64.getEncoder().encodeToString("ext1".getBytes()); File ext2 = TestUtilities.createTmpFile("ext2"); String ext2Encoded = Base64.getEncoder().encodeToString("ext2".getBytes()); ChromeOptions one = new ChromeOptions().addExtensions(ext1); ChromeOptions two = new ChromeOptions().addExtensions(ext2); ChromeOptions merged = one.merge(two); assertThat(merged.asMap()).asInstanceOf(MAP) .extractingByKey(ChromeOptions.CAPABILITY).asInstanceOf(MAP) .extractingByKey("extensions").asInstanceOf(LIST) .containsExactly(ext1Encoded, ext2Encoded); } @Test public void mergingOptionsMergesEncodedExtensionsAndFileExtensions() { File ext1 = TestUtilities.createTmpFile("ext1"); String ext1Encoded = Base64.getEncoder().encodeToString("ext1".getBytes()); String ext2 = Base64.getEncoder().encodeToString("ext2".getBytes()); ChromeOptions one = new ChromeOptions().addExtensions(ext1); ChromeOptions two = new ChromeOptions().addEncodedExtensions(ext2); ChromeOptions merged = one.merge(two); assertThat(merged.asMap()).asInstanceOf(MAP) .extractingByKey(ChromeOptions.CAPABILITY).asInstanceOf(MAP) .extractingByKey("extensions").asInstanceOf(LIST) .containsExactly(ext1Encoded, ext2); } @Test public void mergingOptionsMergesExperimentalOptions() { ChromeOptions one = new ChromeOptions() .setExperimentalOption("opt1", "val1") .setExperimentalOption("opt2", "val2"); ChromeOptions two = new ChromeOptions() .setExperimentalOption("opt2", "val4") .setExperimentalOption("opt3", "val3"); ChromeOptions merged = one.merge(two); assertThat(merged.asMap()).asInstanceOf(MAP) .extractingByKey(ChromeOptions.CAPABILITY).asInstanceOf(MAP) .containsEntry("opt1", "val1") .containsEntry("opt2", "val4") .containsEntry("opt3", "val3"); } @Test public void isW3CSafe() { Map<String, Object> converted = new ChromeOptions() .setBinary("some/path") .addArguments("--headless") .setLogLevel(ChromeDriverLogLevel.INFO) .asMap(); Predicate<String> badKeys = new AcceptedW3CCapabilityKeys().negate(); Set<String> seen = converted.keySet().stream() .filter(badKeys) .collect(toSet()); assertThat(seen).isEmpty(); } @Test public void shouldBeAbleToSetAnAndroidOption() { Map<String, Object> converted = new ChromeOptions() .setAndroidActivity("com.cheese.nom") .asMap(); assertThat(converted) .extractingByKey(ChromeOptions.CAPABILITY).asInstanceOf(MAP) .extractingByKey("androidActivity") .isEqualTo("com.cheese.nom"); } }
/* * Copyright 2014, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.transport; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import java.io.InputStream; import java.nio.ByteBuffer; import javax.annotation.Nullable; /** * Abstract base class for {@link Stream} implementations. */ public abstract class AbstractStream<IdT> implements Stream { /** * Indicates the phase of the GRPC stream in one direction. */ protected enum Phase { HEADERS, MESSAGE, STATUS } private volatile IdT id; private final MessageFramer framer; private final MessageDeframer deframer; /** * Inbound phase is exclusively written to by the transport thread. */ private Phase inboundPhase = Phase.HEADERS; /** * Outbound phase is exclusively written to by the application thread. */ private Phase outboundPhase = Phase.HEADERS; AbstractStream() { MessageDeframer.Listener inboundMessageHandler = new MessageDeframer.Listener() { @Override public void bytesRead(int numBytes) { returnProcessedBytes(numBytes); } @Override public void messageRead(InputStream input) { receiveMessage(input); } @Override public void deliveryStalled() { inboundDeliveryPaused(); } @Override public void endOfStream() { remoteEndClosed(); } }; MessageFramer.Sink<ByteBuffer> outboundFrameHandler = new MessageFramer.Sink<ByteBuffer>() { @Override public void deliverFrame(ByteBuffer frame, boolean endOfStream) { internalSendFrame(frame, endOfStream); } }; framer = new MessageFramer(outboundFrameHandler, 4096); this.deframer = new MessageDeframer(inboundMessageHandler); } /** * Returns the internal id for this stream. Note that Id can be {@code null} for client streams * as the transport may defer creating the stream to the remote side until is has payload or * metadata to send. */ @Nullable public IdT id() { return id; } /** * Set the internal id for this stream */ public void id(IdT id) { Preconditions.checkState(id != null, "Can only set id once"); this.id = id; } @Override public void writeMessage(InputStream message, int length, @Nullable Runnable accepted) { Preconditions.checkNotNull(message, "message"); Preconditions.checkArgument(length >= 0, "length must be >= 0"); outboundPhase(Phase.MESSAGE); if (!framer.isClosed()) { framer.writePayload(message, length); } // TODO(nmittler): add flow control. if (accepted != null) { accepted.run(); } } @Override public final void flush() { if (!framer.isClosed()) { framer.flush(); } } /** * Closes the underlying framer. * * <p>No-op if the framer has already been closed. */ final void closeFramer() { if (!framer.isClosed()) { framer.close(); } } /** * Free any resources associated with this stream. Subclass implementations must call this * version. * <p> * NOTE. Can be called by both the transport thread and the application thread. Transport * threads need to dispose when the remote side has terminated the stream. Application threads * will dispose when the application decides to close the stream as part of normal processing. * </p> */ public void dispose() { framer.dispose(); } /** * Sends an outbound frame to the remote end point. * * @param frame a buffer containing the chunk of data to be sent. * @param endOfStream if {@code true} indicates that no more data will be sent on the stream by * this endpoint. */ protected abstract void internalSendFrame(ByteBuffer frame, boolean endOfStream); /** A message was deframed. */ protected abstract void receiveMessage(InputStream is); /** Deframer has no pending deliveries. */ protected abstract void inboundDeliveryPaused(); /** Deframer reached end of stream. */ protected abstract void remoteEndClosed(); /** * Returns the given number of processed bytes back to inbound flow control to enable receipt of * more data. */ protected abstract void returnProcessedBytes(int processedBytes); /** * Called when a {@link #deframe(Buffer, boolean)} operation failed. */ protected abstract void deframeFailed(Throwable cause); /** * Closes this deframer and frees any resources. After this method is called, additional calls * will have no effect. */ protected final void closeDeframer() { deframer.close(); } /** * Called to parse a received frame and attempt delivery of any completed * messages. Must be called from the transport thread. */ protected final void deframe(Buffer frame, boolean endOfStream) { try { deframer.deframe(frame, endOfStream); } catch (Throwable t) { deframeFailed(t); } } /** * Indicates whether delivery is currently stalled, pending receipt of more data. */ protected final boolean isDeframerStalled() { return deframer.isStalled(); } /** * Called to request the given number of messages from the deframer. Must be called * from the transport thread. */ protected final void requestMessagesFromDeframer(int numMessages) { try { deframer.request(numMessages); } catch (Throwable t) { deframeFailed(t); } } final Phase inboundPhase() { return inboundPhase; } /** * Transitions the inbound phase to the given phase and returns the previous phase. * If the transition is disallowed, throws an {@link IllegalStateException}. */ final Phase inboundPhase(Phase nextPhase) { Phase tmp = inboundPhase; inboundPhase = verifyNextPhase(inboundPhase, nextPhase); return tmp; } final Phase outboundPhase() { return outboundPhase; } /** * Transitions the outbound phase to the given phase and returns the previous phase. * If the transition is disallowed, throws an {@link IllegalStateException}. */ final Phase outboundPhase(Phase nextPhase) { Phase tmp = outboundPhase; outboundPhase = verifyNextPhase(outboundPhase, nextPhase); return tmp; } private Phase verifyNextPhase(Phase currentPhase, Phase nextPhase) { if (nextPhase.ordinal() < currentPhase.ordinal()) { throw new IllegalStateException( String.format("Cannot transition phase from %s to %s", currentPhase, nextPhase)); } return nextPhase; } /** * Can the stream receive data from its remote peer. */ public boolean canReceive() { return inboundPhase() != Phase.STATUS; } /** * Can the stream send data to its remote peer. */ public boolean canSend() { return outboundPhase() != Phase.STATUS; } /** * Is the stream fully closed. Note that this method is not thread-safe as inboundPhase and * outboundPhase are mutated in different threads. Tests must account for thread coordination * when calling. */ @VisibleForTesting public boolean isClosed() { return inboundPhase() == Phase.STATUS && outboundPhase() == Phase.STATUS; } @Override public String toString() { return toStringHelper().toString(); } protected Objects.ToStringHelper toStringHelper() { return Objects.toStringHelper(this) .add("id", id()) .add("inboundPhase", inboundPhase().name()) .add("outboundPhase", outboundPhase().name()); } }
/******************************************************************************* * Copyright FUJITSU LIMITED 2017 *******************************************************************************/ package org.oscm.app.setup; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.oscm.app.domain.PlatformConfigurationKey; public class PropertyImportControllerTest { private final static String DRIVER_CLASS = "org.oscm.app.setup.PropertyImport"; private final static String DRIVER_CLASS_DUMMY = "class"; private final static String DRIVER_URL = "url"; private final static String USER_NAME = "user"; private final static String USER_PASSWORD = "password"; private final static String PROPERTY_FILE = "file"; private final static String CONTROLLER_ID = "controller"; private final static String CONTROLLER_ID_PROXY = "PROXY"; private final static boolean OVERWRITE_FLAG = true; private final static String TEST_PLATFORM_KEY = PlatformConfigurationKey.APP_BASE_URL .name(); private final static String TEST_CONTROLLER_KEY = "KEY"; private final static String TEST_VALUE = "value"; private final static String APP_BASE_URL = "http://www.fujitsu.com"; private static Connection mockConn; private static PreparedStatement mockStmt; private static ResultSet mockResult; private static PropertyImport propImportProxy; private static PropertyImport propImportController; @SuppressWarnings("unchecked") @BeforeClass public static void setup() throws SQLException, FileNotFoundException { mockConn = Mockito.mock(Connection.class); mockStmt = Mockito.mock(PreparedStatement.class); mockResult = Mockito.mock(ResultSet.class); doReturn(mockStmt).when(mockConn).prepareStatement(anyString()); doReturn(mockResult).when(mockStmt).executeQuery(); propImportProxy = spy(new PropertyImport(DRIVER_CLASS, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, "")); doReturn(mockConn).when(propImportProxy).getConnetion(); doReturn(null).when(propImportProxy).getInputStreamForProperties(); doNothing().when(propImportProxy).createEntries(any(Connection.class), anyMap()); doNothing().when(propImportProxy).updateEntries(any(Connection.class), anyMap()); doNothing().when(propImportProxy).deleteEntries(any(Connection.class), anyMap()); propImportController = spy(new PropertyImport(DRIVER_CLASS, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, CONTROLLER_ID)); doReturn(mockConn).when(propImportController).getConnetion(); doReturn(null).when(propImportController).getInputStreamForProperties(); doNothing().when(propImportController) .createEntries(any(Connection.class), anyMap()); doNothing().when(propImportController) .updateEntries(any(Connection.class), anyMap()); doNothing().when(propImportController) .deleteEntries(any(Connection.class), anyMap()); } enum ControllerId { EMPTY_VALUE, NOT_PRESENT, WITH_VALUE, RESERVED_APP_VALUE } @Test public void constructor() { // when PropertyImport propImport = new PropertyImport(DRIVER_CLASS, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, CONTROLLER_ID); // then assertEquals(DRIVER_URL, propImport.getDriverURL()); assertEquals(USER_NAME, propImport.getUserName()); assertEquals(USER_PASSWORD, propImport.getUserPwd()); assertEquals(PROPERTY_FILE, propImport.getPropertyFile()); assertEquals(CONTROLLER_ID, propImport.getControllerId()); assertEquals(Boolean.valueOf(OVERWRITE_FLAG), Boolean.valueOf(propImport.isOverwriteFlag())); } @Test public void constructor_classNotExist() { try { new PropertyImport(DRIVER_CLASS_DUMMY, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, CONTROLLER_ID); fail("Runtime exception expected."); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals( PropertyImport.ERR_DRIVER_CLASS_NOT_FOUND.replaceFirst( PropertyImport.ERR_PARAM_ESC, DRIVER_CLASS_DUMMY), e.getMessage()); } } @Test public void constructor_classNull() { try { new PropertyImport(null, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, CONTROLLER_ID); fail("Runtime exception expected"); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(PropertyImport.ERR_DRIVER_CLASS_NULL, e.getMessage()); } } @Test public void constructor_controleIdNull() { // when PropertyImport propImport = new PropertyImport(DRIVER_CLASS, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, null); // then assertEquals(CONTROLLER_ID_PROXY, propImport.getControllerId()); } @Test public void constructor_controleIdEmpty() { // when PropertyImport propImport = new PropertyImport(DRIVER_CLASS, DRIVER_URL, USER_NAME, USER_PASSWORD, PROPERTY_FILE, OVERWRITE_FLAG, ""); // then assertEquals(CONTROLLER_ID_PROXY, propImport.getControllerId()); } @Ignore @Test public void execute_ProxySettings() { // given Properties p = givenAppProperties(ControllerId.WITH_VALUE); doReturn(p).when(propImportProxy) .loadProperties(any(InputStream.class)); // when propImportProxy.execute(); // then assertEquals(CONTROLLER_ID_PROXY, propImportProxy.getControllerId()); } @Test public void execute_ControllerSettings() { // given Properties p = givenAppProperties(ControllerId.WITH_VALUE); doReturn(p).when(propImportController) .loadProperties(any(InputStream.class)); // when propImportController.execute(); // then assertEquals(CONTROLLER_ID, propImportController.getControllerId()); } @Test public void execute_ControllerSettings_EmptyControllerId() { // given Properties p = givenAppProperties(ControllerId.EMPTY_VALUE); doReturn(p).when(propImportController) .loadProperties(any(InputStream.class)); // when try { propImportController.execute(); fail("Runtime exception expected."); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(PropertyImport.ERR_CONTROLLER_ID_EMPTY, e.getMessage()); } } @Test public void execute_ControllerSettings_ReservedAppControllerId() { // given Properties p = givenAppProperties(ControllerId.RESERVED_APP_VALUE); doReturn(p).when(propImportController) .loadProperties(any(InputStream.class)); // when try { propImportController.execute(); fail("Runtime exception expected."); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(PropertyImport.ERR_CONTROLLER_ID_RESERVED, e.getMessage()); } } private Properties givenAppProperties(ControllerId controllerId) { Properties p = getProperties(); if (ControllerId.WITH_VALUE.equals(controllerId)) { p.setProperty("CONTROLLER_ID", CONTROLLER_ID); } else if (ControllerId.EMPTY_VALUE.equals(controllerId)) { p.setProperty("CONTROLLER_ID", ""); } else if (ControllerId.RESERVED_APP_VALUE.equals(controllerId)) { p.setProperty("CONTROLLER_ID", CONTROLLER_ID_PROXY); } p.setProperty(TEST_PLATFORM_KEY, APP_BASE_URL); p.setProperty(TEST_CONTROLLER_KEY, TEST_VALUE); return p; } private Properties getProperties() { Properties p = new Properties(); p.put(PlatformConfigurationKey.APP_BASE_URL.name(), APP_BASE_URL); p.put(PlatformConfigurationKey.APP_ADMIN_MAIL_ADDRESS.name(), "[email protected]"); p.put(PlatformConfigurationKey.APP_TIMER_INTERVAL.name(), "15000"); p.put(PlatformConfigurationKey.APP_TIMER_REFRESH_SUBSCRIPTIONS.name(), "86400000"); p.put(PlatformConfigurationKey.BSS_WEBSERVICE_URL.name(), "http://localhost:8680/{service}/BASIC?wsdl"); p.put(PlatformConfigurationKey.BSS_USER_KEY.name(), "1000"); p.put(PlatformConfigurationKey.BSS_USER_PWD.name(), "_crypt:admin123"); p.put(PlatformConfigurationKey.BSS_AUTH_MODE.name(), "INTERNAL"); return p; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner.iterative.rule; import com.facebook.presto.spi.function.OperatorType; import com.facebook.presto.spi.plan.PlanNodeIdAllocator; import com.facebook.presto.spi.plan.ValuesNode; import com.facebook.presto.spi.relation.DeterminismEvaluator; import com.facebook.presto.spi.relation.RowExpression; import com.facebook.presto.spi.relation.VariableReferenceExpression; import com.facebook.presto.sql.planner.iterative.rule.ReorderJoins.MultiJoinNode; import com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder; import com.facebook.presto.sql.planner.plan.JoinNode; import com.facebook.presto.sql.planner.plan.JoinNode.EquiJoinClause; import com.facebook.presto.sql.relational.FunctionResolution; import com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator; import com.facebook.presto.testing.LocalQueryRunner; import com.google.common.collect.ImmutableList; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.LinkedHashSet; import java.util.Optional; import static com.facebook.airlift.testing.Closeables.closeAllRuntimeException; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.expressions.LogicalRowExpressions.and; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.sql.planner.iterative.Lookup.noLookup; import static com.facebook.presto.sql.planner.iterative.rule.ReorderJoins.MultiJoinNode.toMultiJoinNode; import static com.facebook.presto.sql.planner.plan.JoinNode.Type.FULL; import static com.facebook.presto.sql.planner.plan.JoinNode.Type.INNER; import static com.facebook.presto.sql.planner.plan.JoinNode.Type.LEFT; import static com.facebook.presto.sql.relational.Expressions.call; import static com.facebook.presto.sql.relational.Expressions.constant; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static org.testng.Assert.assertEquals; public class TestJoinNodeFlattener { private static final int DEFAULT_JOIN_LIMIT = 10; private DeterminismEvaluator determinismEvaluator; private FunctionResolution functionResolution; private LocalQueryRunner queryRunner; @BeforeClass public void setUp() { queryRunner = new LocalQueryRunner(testSessionBuilder().build()); determinismEvaluator = new RowExpressionDeterminismEvaluator(queryRunner.getMetadata()); functionResolution = new FunctionResolution(queryRunner.getMetadata().getFunctionManager()); } @AfterClass(alwaysRun = true) public void tearDown() { closeAllRuntimeException(queryRunner); queryRunner = null; } @Test(expectedExceptions = IllegalStateException.class) public void testDoesNotAllowOuterJoin() { PlanBuilder p = planBuilder(); VariableReferenceExpression a1 = p.variable("A1"); VariableReferenceExpression b1 = p.variable("B1"); JoinNode outerJoin = p.join( FULL, p.values(a1), p.values(b1), ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()); toMultiJoinNode(outerJoin, noLookup(), DEFAULT_JOIN_LIMIT, functionResolution, determinismEvaluator); } @Test public void testDoesNotConvertNestedOuterJoins() { PlanBuilder p = planBuilder(); VariableReferenceExpression a1 = p.variable("A1"); VariableReferenceExpression b1 = p.variable("B1"); VariableReferenceExpression c1 = p.variable("C1"); JoinNode leftJoin = p.join( LEFT, p.values(a1), p.values(b1), ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()); ValuesNode valuesC = p.values(c1); JoinNode joinNode = p.join( INNER, leftJoin, valuesC, ImmutableList.of(equiJoinClause(a1, c1)), ImmutableList.of(a1, b1, c1), Optional.empty()); MultiJoinNode expected = MultiJoinNode.builder() .setSources(leftJoin, valuesC).setFilter(createEqualsExpression(a1, c1)) .setOutputVariables(a1, b1, c1) .build(); assertEquals(toMultiJoinNode(joinNode, noLookup(), DEFAULT_JOIN_LIMIT, functionResolution, determinismEvaluator), expected); } @Test public void testRetainsOutputSymbols() { PlanBuilder p = planBuilder(); VariableReferenceExpression a1 = p.variable("A1"); VariableReferenceExpression b1 = p.variable("B1"); VariableReferenceExpression b2 = p.variable("B2"); VariableReferenceExpression c1 = p.variable("C1"); VariableReferenceExpression c2 = p.variable("C2"); ValuesNode valuesA = p.values(a1); ValuesNode valuesB = p.values(b1, b2); ValuesNode valuesC = p.values(c1, c2); JoinNode joinNode = p.join( INNER, valuesA, p.join( INNER, valuesB, valuesC, ImmutableList.of(equiJoinClause(b1, c1)), ImmutableList.of(b1, b2, c1, c2), Optional.empty()), ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()); MultiJoinNode expected = MultiJoinNode.builder() .setSources(valuesA, valuesB, valuesC) .setFilter(and(createEqualsExpression(b1, c1), createEqualsExpression(a1, b1))) .setOutputVariables(a1, b1) .build(); assertEquals(toMultiJoinNode(joinNode, noLookup(), DEFAULT_JOIN_LIMIT, functionResolution, determinismEvaluator), expected); } @Test public void testCombinesCriteriaAndFilters() { PlanBuilder p = planBuilder(); VariableReferenceExpression a1 = p.variable("A1"); VariableReferenceExpression b1 = p.variable("B1"); VariableReferenceExpression b2 = p.variable("B2"); VariableReferenceExpression c1 = p.variable("C1"); VariableReferenceExpression c2 = p.variable("C2"); ValuesNode valuesA = p.values(a1); ValuesNode valuesB = p.values(b1, b2); ValuesNode valuesC = p.values(c1, c2); RowExpression bcFilter = and( call( OperatorType.GREATER_THAN.name(), functionResolution.comparisonFunction(OperatorType.GREATER_THAN, c2.getType(), BIGINT), BOOLEAN, ImmutableList.of(c2, constant(0L, BIGINT))), call( OperatorType.NOT_EQUAL.name(), functionResolution.comparisonFunction(OperatorType.NOT_EQUAL, c2.getType(), BIGINT), BOOLEAN, ImmutableList.of(c2, constant(7L, BIGINT))), call( OperatorType.GREATER_THAN.name(), functionResolution.comparisonFunction(OperatorType.GREATER_THAN, b2.getType(), c2.getType()), BOOLEAN, ImmutableList.of(b2, c2))); RowExpression add = call( OperatorType.ADD.name(), functionResolution.arithmeticFunction(OperatorType.ADD, a1.getType(), c1.getType()), a1.getType(), ImmutableList.of(a1, c1)); RowExpression abcFilter = call( OperatorType.LESS_THAN.name(), functionResolution.comparisonFunction(OperatorType.LESS_THAN, add.getType(), b1.getType()), BOOLEAN, ImmutableList.of(add, b1)); JoinNode joinNode = p.join( INNER, valuesA, p.join( INNER, valuesB, valuesC, ImmutableList.of(equiJoinClause(b1, c1)), ImmutableList.of(b1, b2, c1, c2), Optional.of(bcFilter)), ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1, b2, c1, c2), Optional.of(abcFilter)); MultiJoinNode expected = new MultiJoinNode( new LinkedHashSet<>(ImmutableList.of(valuesA, valuesB, valuesC)), and(createEqualsExpression(b1, c1), createEqualsExpression(a1, b1), bcFilter, abcFilter), ImmutableList.of(a1, b1, b2, c1, c2)); assertEquals(toMultiJoinNode(joinNode, noLookup(), DEFAULT_JOIN_LIMIT, functionResolution, determinismEvaluator), expected); } @Test public void testConvertsBushyTrees() { PlanBuilder p = planBuilder(); VariableReferenceExpression a1 = p.variable("A1"); VariableReferenceExpression b1 = p.variable("B1"); VariableReferenceExpression c1 = p.variable("C1"); VariableReferenceExpression d1 = p.variable("D1"); VariableReferenceExpression d2 = p.variable("D2"); VariableReferenceExpression e1 = p.variable("E1"); VariableReferenceExpression e2 = p.variable("E2"); ValuesNode valuesA = p.values(a1); ValuesNode valuesB = p.values(b1); ValuesNode valuesC = p.values(c1); ValuesNode valuesD = p.values(d1, d2); ValuesNode valuesE = p.values(e1, e2); JoinNode joinNode = p.join( INNER, p.join( INNER, p.join( INNER, valuesA, valuesB, ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()), valuesC, ImmutableList.of(equiJoinClause(a1, c1)), ImmutableList.of(a1, b1, c1), Optional.empty()), p.join( INNER, valuesD, valuesE, ImmutableList.of( equiJoinClause(d1, e1), equiJoinClause(d2, e2)), ImmutableList.of(d1, d2, e1, e2), Optional.empty()), ImmutableList.of(equiJoinClause(b1, e1)), ImmutableList.of(a1, b1, c1, d1, d2, e1, e2), Optional.empty()); MultiJoinNode expected = MultiJoinNode.builder() .setSources(valuesA, valuesB, valuesC, valuesD, valuesE) .setFilter(and(createEqualsExpression(a1, b1), createEqualsExpression(a1, c1), createEqualsExpression(d1, e1), createEqualsExpression(d2, e2), createEqualsExpression(b1, e1))) .setOutputVariables(a1, b1, c1, d1, d2, e1, e2) .build(); assertEquals(toMultiJoinNode(joinNode, noLookup(), 5, functionResolution, determinismEvaluator), expected); } @Test public void testMoreThanJoinLimit() { PlanBuilder p = planBuilder(); VariableReferenceExpression a1 = p.variable("A1"); VariableReferenceExpression b1 = p.variable("B1"); VariableReferenceExpression c1 = p.variable("C1"); VariableReferenceExpression d1 = p.variable("D1"); VariableReferenceExpression d2 = p.variable("D2"); VariableReferenceExpression e1 = p.variable("E1"); VariableReferenceExpression e2 = p.variable("E2"); ValuesNode valuesA = p.values(a1); ValuesNode valuesB = p.values(b1); ValuesNode valuesC = p.values(c1); ValuesNode valuesD = p.values(d1, d2); ValuesNode valuesE = p.values(e1, e2); JoinNode join1 = p.join( INNER, valuesA, valuesB, ImmutableList.of(equiJoinClause(a1, b1)), ImmutableList.of(a1, b1), Optional.empty()); JoinNode join2 = p.join( INNER, valuesD, valuesE, ImmutableList.of( equiJoinClause(d1, e1), equiJoinClause(d2, e2)), ImmutableList.of(d1, d2, e1, e2), Optional.empty()); JoinNode joinNode = p.join( INNER, p.join( INNER, join1, valuesC, ImmutableList.of(equiJoinClause(a1, c1)), ImmutableList.of(a1, b1, c1), Optional.empty()), join2, ImmutableList.of(equiJoinClause(b1, e1)), ImmutableList.of(a1, b1, c1, d1, d2, e1, e2), Optional.empty()); MultiJoinNode expected = MultiJoinNode.builder() .setSources(join1, join2, valuesC) .setFilter(and(createEqualsExpression(a1, c1), createEqualsExpression(b1, e1))) .setOutputVariables(a1, b1, c1, d1, d2, e1, e2) .build(); assertEquals(toMultiJoinNode(joinNode, noLookup(), 2, functionResolution, determinismEvaluator), expected); } private RowExpression createEqualsExpression(VariableReferenceExpression left, VariableReferenceExpression right) { return call( OperatorType.EQUAL.name(), functionResolution.comparisonFunction(OperatorType.EQUAL, left.getType(), right.getType()), BOOLEAN, ImmutableList.of(left, right)); } private EquiJoinClause equiJoinClause(VariableReferenceExpression variable1, VariableReferenceExpression variable2) { return new EquiJoinClause(variable1, variable2); } private PlanBuilder planBuilder() { return new PlanBuilder(TEST_SESSION, new PlanNodeIdAllocator(), queryRunner.getMetadata()); } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * DeleteVpcType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * DeleteVpcType bean class */ public class DeleteVpcType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = DeleteVpcType Namespace URI = http://ec2.amazonaws.com/doc/2010-11-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2010-11-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for VpcId */ protected java.lang.String localVpcId ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getVpcId(){ return localVpcId; } /** * Auto generated setter method * @param param VpcId */ public void setVpcId(java.lang.String param){ this.localVpcId=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { DeleteVpcType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2010-11-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":DeleteVpcType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "DeleteVpcType", xmlWriter); } } namespace = "http://ec2.amazonaws.com/doc/2010-11-15/"; if (! namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); xmlWriter.writeStartElement(prefix,"vpcId", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace,"vpcId"); } } else { xmlWriter.writeStartElement("vpcId"); } if (localVpcId==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("vpcId cannot be null!!"); }else{ xmlWriter.writeCharacters(localVpcId); } xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/", "vpcId")); if (localVpcId != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localVpcId)); } else { throw new org.apache.axis2.databinding.ADBException("vpcId cannot be null!!"); } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DeleteVpcType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DeleteVpcType object = new DeleteVpcType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"DeleteVpcType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (DeleteVpcType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","vpcId").equals(reader.getName())){ java.lang.String content = reader.getElementText(); object.setVpcId( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
/* * This file is part of the SMT project. * Copyright 2010 David R. Cok * Created August 2010 */ package org.smtlib; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** This class implements launching, writing to, and reading responses from a * launched process (in particular, solver processes). * @author David Cok */ public class SolverProcess { final static protected String eol = System.getProperty("line.separator"); /** Wraps an exception thrown because of a failure in the prover */ public static class ProverException extends RuntimeException { private static final long serialVersionUID = 1L; public ProverException(String s) { super(s); } } /** The command-line arguments that launch a new process */ protected String[] app; /** The text that marks the end of the text returned from the process */ protected String endMarker; /** The Java process object (initialized by start() )*/ protected Process process; /** The Writer object that writes to the spawned process (initialized by start() )*/ protected Writer toProcess; /** The Reader process that reads from the standard output of the spawned process (initialized by start() )*/ protected Reader fromProcess; /** The Reader process that reads from the standard error stream of the spawned process (initialized by start() )*/ protected Reader errors; /** A place (e.g., log file), if non-null, to write all outbound communications for diagnostic purposes */ public /*@Nullable*/Writer log; /** Constructs a SolverProcess object, without actually starting the process as yet. * @param cmd the command-line that will launch the desired process * @param endMarker text that marks the end of text returned from the process, e.g. the end of the * prompt for new input * @param logfile if not null, the name of a file to log communications to, for diagnostic purposes */ public SolverProcess(String[] cmd, String endMarker, /*@Nullable*/String logfile) { this.endMarker = endMarker; try { if (logfile != null) { log = new FileWriter(logfile); } } catch (IOException e) { System.out.println("Failed to create solver log file " + logfile + ": " + e); // FIXME - wwrite to somewhere better } setCmd(cmd); } /** Enables changing the command-line; must be called prior to start() */ public void setCmd(String[] cmd) { this.app = cmd; try { if (log != null && cmd != null) { // TODO: Might be nicer to escape any backslashes and enclose strings in quotes, in case arguments contain spaces or special characters log.write(";; "); for (String s: cmd) { log.write(s); log.write(" "); } log.write(eol); } } catch (IOException e) { System.out.println("Failed to write to solver log file : " + e); // FIXME - wwrite to somewhere better } } /** Starts the process; if the argument is true, then also listens to its output until a prompt is read. */ public void start(boolean listen) throws ProverException { try { process = Runtime.getRuntime().exec(app); toProcess = new OutputStreamWriter(process.getOutputStream()); fromProcess = new BufferedReader(new InputStreamReader(process.getInputStream())); errors = new InputStreamReader(process.getErrorStream()); if (listen) listen(); } catch (IOException e) { throw new ProverException(e.getMessage()); } catch (RuntimeException e) { throw new ProverException(e.getMessage()); } } /** Listens to the process's standard output until the designated endMarker is read * and to the error output. If there is error output, it is returned; * otherwise the standard output is returned. */ public String listen() throws IOException { // FIXME - need to put the two reads in parallel, otherwise one might block on a full buffer, preventing the other from completing String err = listenThru(errors,null); String out = listenThru(fromProcess,endMarker); err = err + listenThru(errors,null); if (log != null) { if (!out.isEmpty()) { log.write(";OUT: "); log.write(out); log.write(eol); } // input usually ends with a prompt and no line terminator if (!err.isEmpty()) { log.write(";ERR: "); log.write(err); } // input usually ends with a line terminator, we think } // System.out.println("OUT: " + out.replace('\r', '@').replace('\n', '@')); // System.out.println("ERR: " + err.replace('\r', '@').replace('\n', '@')); // In some cases (yices2) the prompt is on the error stream. Our heuristic is that then there is no line-termination if (err.endsWith("\n") || out.isEmpty()) { return err.isEmpty() || err.charAt(0) == ';' ? out : err; // Note: the guard against comments (starting with ;) is for Z3 } else { return out; } } /** Returns true if the process is still running; this relies on exceptions * for control flow and may be a bit expensive. */ public boolean isRunning(boolean expectStopped) { try { process.exitValue(); if (!expectStopped) { if (log != null) { try { log.write("Solver has unexpectedly terminated"); log.write(eol); log.flush(); } catch (IOException e) { // ignore } } } return false; } catch (IllegalThreadStateException e) { return true; } } /** Aborts the process */ public void exit() { process.destroy(); process = null; toProcess = null; if (log != null) { try { log.write(";;Exiting solver"); log.write(eol); log.flush(); log.close(); } catch (IOException e) { // Ignore } } } /** Sends all the given text arguments, then (if listen is true) listens for the designated end marker text */ public /*@Nullable*/ String send(boolean listen, String ... args) throws IOException { if (toProcess == null) throw new ProverException("The solver has not been started"); for (String arg: args) { // System.out.print(arg); if (log != null) log.write(arg); toProcess.write(arg); } // System.out.println(); if (log != null) log.flush(); toProcess.flush(); if (listen) return listen(); return null; } /** Sends all the given text arguments, then listens for the designated end marker text */ public /*@Nullable*/ String sendAndListen(String ... args) throws IOException { return send(true,args); } /** Sends all the given text arguments, but does not wait for a response */ public void sendNoListen(String ... args) throws IOException { send(false,args); } // TODO - combine listen and noListen versions of send? /** A pool of buffers used by listenThru. The listenThru method needs a buffer, which may need to be big. * However, the method is called often and we do not want to be continually allocating big buffers that * have to wait around to be garbage collected. Especially since, unless there are multiple SMT processes * working simultaneously, we will never need more than one of these. But in order to be thread-safe we * cannot simply declare a static buffer. */ static private List<char[]> bufferCollection = Collections.synchronizedList(new LinkedList<char[]>()); /** Gets a buffer out of the shared free-list of buffers * @return a free buffer available to be used */ synchronized private static char[] getBuffer() { char[] buf; if (bufferCollection.isEmpty()) { // There is nothing magic about the size of the buffers - just meant to be generally enough to // hold the output of a read, but not so large as to unnecessarily use memory. // If it is not large enough, it will be expanded. buf = new char[10000]; } else { buf = bufferCollection.remove(0); } return buf; } /** Puts a buffer back into the shared free-list. * @param buf the buffer being released */ synchronized private static void putBuffer(char[] buf) { bufferCollection.add(buf); } /** Reads the given Reader until the given String is read (or end of input is reached); * may block until input is available; the stopping string must occur at the end of the * input. This is typically used to read through a prompt on standard output; when the stopping * string (the prompt) is read, one knows that the output from the program is complete and not * to wait for any more. * * @param r the Reader to read characters from * @param end a stopping String * @return the String read * @throws IOException if an IO failure occurs */ static public /*@NonNull*/String listenThru(/*@NonNull*/Reader r, /*@Nullable*/ String end) throws IOException { char[] buf = getBuffer(); try { int len = end != null ? end.length() : 0; int p = 0; // Number of characters read int parens = 0; while (end != null || r.ready()) { //System.out.println("ABOUT TO READ " + p); int i = r.read(buf,p,buf.length-p); if (i == -1) break; // End of Input for (int ii=0; ii<i; ++ii) { if (buf[p+ii] == '(') ++parens; else if (buf[p+ii] == ')') --parens; } p += i; //System.out.println("HEARD: " + new String(buf,0,p)); if (end != null && p >= len) { // Need to compare a String to a part of a char array - we iterate by // hand to avoid creating a new String or CharBuffer object boolean match = true; int k = p-len; for (int j=0; j<len; j++) { if (end.charAt(j) != buf[k++]) { match = false; break; } } if (match && (!"\n".equals(end) || parens == 0)) break; // stopping string matched } if (p == buf.length) { // expand the buffer char[] nbuf = new char[2*buf.length]; System.arraycopy(buf,0,nbuf,0,p); buf = nbuf; } } return new String(buf,0,p); } finally { putBuffer(buf); } } }
package com.atulgpt.www.timetrix.fragments; import android.annotation.TargetApi; import android.app.Dialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Toast; import com.atulgpt.www.timetrix.R; import com.atulgpt.www.timetrix.adapters.CustomAdapter; import com.atulgpt.www.timetrix.adapters.DatabaseAdapter; import com.atulgpt.www.timetrix.adapters.RecyclerViewAdapter; import com.atulgpt.www.timetrix.utils.GlobalData; import com.atulgpt.www.timetrix.utils.NoteUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link FragmentAllNotes.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link FragmentAllNotes#newInstance} factory method to * create an instance of this fragment. */ public class FragmentAllNotes extends android.support.v4.app.Fragment implements View.OnClickListener, DialogInterface.OnClickListener, CustomAdapter.OnListAdapterInteractionListener, RecyclerViewAdapter.OnListAdapterInteractionListener, DatabaseAdapter.DatabaseAdapterListener { private static final String TAG = FragmentAllNotes.class.getSimpleName (); private static final boolean DEBUG = true; private static final String ARG_NOTE_INDEX = "param1"; private static final String ARG_PARAM2 = "param2"; private static final int DIALOG_BUTTON_CLICKED = 1; private static final int DIALOG_BUTTON_NOT_CLICKED = 0; // TODOo: Rename and change types of parameters private String mSectionIndex; private int mDialogStatus; private OnFragmentInteractionListener mOnFragmentInteractionListener; //private static CustomAdapter.OnListAdapterInteractionListener mOnListAdapterInteractionListener; private RecyclerViewAdapter mCustomRecyclerViewAdapterAllNotes; private ArrayList<String> mArrayListAllNotes; private RecyclerView mRecyclerViewAllNotes; public static final String tempString = "subject_fragment_all"; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SubjectTabFragment. */ public static FragmentAllNotes newInstance(String param1, String param2) { FragmentAllNotes fragment = new FragmentAllNotes (); Bundle args = new Bundle (); args.putString (ARG_NOTE_INDEX, param1); args.putString (ARG_PARAM2, param2); fragment.setArguments (args); return fragment; } public void setSectionIndex(String param1) { this.mSectionIndex = param1; } public FragmentAllNotes() { // Required empty public constructor } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState (outState); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); if (getArguments () != null) { mSectionIndex = getArguments ().getString (ARG_NOTE_INDEX); } } @Override public void onStart() { super.onStart (); } @Override public void onResume() { super.onResume (); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate (R.layout.fragment_all_notes, container, false); } @Override public void setArguments(Bundle args) { super.setArguments (args); if (DEBUG) Log.d (TAG, "setArgument " + args); } // TODOo: Rename method, update argument and hook method into UI event public void listDataSetChanged() { if (mOnFragmentInteractionListener != null) { mOnFragmentInteractionListener.onFragmentInteraction (this.getClass ().getName (), null); } else Toast.makeText (getActivity (), "Couldn't update the list!", Toast.LENGTH_LONG).show (); } @Override public void onAttach(Context activity) { super.onAttach (activity); //Toast.makeText(getActivity(), "onAttach in fragmentAll", Toast.LENGTH_SHORT).show(); try { mOnFragmentInteractionListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException (activity.toString () + " must implement OnFragmentInteractionListener"); } // ((StartupPage)activity).updateTitleOnSectionAttached (Integer.parseInt (mSectionIndex)); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated (savedInstanceState); mSectionIndex = String.valueOf (mOnFragmentInteractionListener.getSectionIndex ()); populateListView (); } /** * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} * has returned, but before any saved state has been restored in to the view. * This gives subclasses a chance to initialize themselves once * they know their view hierarchy has been completely created. The fragment's * view hierarchy is not however attached to its parent at this point. * * @param view The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}. * @param savedInstanceState If non-null, this fragment is being re-constructed */ @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated (view, savedInstanceState); FloatingActionButton btnAddNotes = (FloatingActionButton) view.findViewById (R.id.buttonAddNotes); btnAddNotes.setOnClickListener (this); // mListViewAll = (ListView) getActivity ().findViewById (R.id.listNotesAll); mRecyclerViewAllNotes = (RecyclerView) view.findViewById (R.id.recyclerNotesAll); mArrayListAllNotes = new ArrayList<> (); // mCustomAdapterAllNotes = new CustomAdapter (mArrayListAllNotes, getActivity (), tempString, mHandlerAll); mRecyclerViewAllNotes.setHasFixedSize (true); mCustomRecyclerViewAdapterAllNotes = new RecyclerViewAdapter (mArrayListAllNotes, getActivity (), this, tempString); mRecyclerViewAllNotes.setAdapter (mCustomRecyclerViewAdapterAllNotes); LinearLayoutManager llm = new LinearLayoutManager (getActivity ()); llm.setOrientation (LinearLayoutManager.VERTICAL); mRecyclerViewAllNotes.setLayoutManager (llm); } @Override public void onDetach() { super.onDetach (); mOnFragmentInteractionListener = null; } @TargetApi(Build.VERSION_CODES.KITKAT) @Override public void onClick(View v) { if (v.getId () == R.id.buttonAddNotes) { //AlertDialog alertDialog = new AlertDialog(getActivity()); if (mDialogStatus == DIALOG_BUTTON_NOT_CLICKED) { android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder (getActivity ()); builder.setTitle (R.string.add_notes_str); builder.setCancelable (true); // for transition // String transitionName = getString (R.string.transition_string); // ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation (getActivity (),dialogView,transitionName); // // DialogAddNewNote dialogAddNewNote = DialogAddNewNote.newInstance(5); // ChangeBounds changeBoundsTransition = TransitionInflater.from(getActivity ()).inflateTransition(R.transition.change_bounds); // dialogAddNewNote.setSharedElementEnterTransition (changeBoundsTransition); builder.setView (R.layout.dialog_add_notes); builder.setNegativeButton (R.string.cancel_str, new DialogInterface.OnClickListener () { public void onClick(DialogInterface dialog, int id) { } }); builder.setPositiveButton (R.string.done_str, this); android.support.v7.app.AlertDialog alertDialog = builder.create (); alertDialog.setOnDismissListener (new DialogInterface.OnDismissListener () { @Override public void onDismiss(DialogInterface dialog) { mDialogStatus = DIALOG_BUTTON_NOT_CLICKED; } }); alertDialog.show (); mDialogStatus = DIALOG_BUTTON_CLICKED; } } } @Override public void onClick(DialogInterface dialog, int which) { Dialog d = (Dialog) dialog; EditText editText = (EditText) d.findViewById (R.id.editTextNotes); EditText editTextAddTitle = (EditText) d.findViewById (R.id.editTextNotesTitle); String note = editText.getText ().toString (); String title = editTextAddTitle.getText ().toString (); if (note.trim ().isEmpty ()) return; JSONObject jsonObject = new JSONObject (); DatabaseAdapter databaseAdapter = new DatabaseAdapter (getActivity (), this); String allNote = databaseAdapter.getNotesForSection (Integer.parseInt (mSectionIndex) + 1); JSONArray js = new JSONArray (); if (DEBUG) Log.d (TAG, "onClick allNote = " + allNote + " SubjectId -1 = " + mSectionIndex + " empty json = " + js + " empty 2nd =" + js.toString ()); JSONArray jsonArray = new JSONArray (); try { if (allNote != null) { jsonArray = new JSONArray (allNote); } } catch (JSONException e) { e.printStackTrace (); Toast.makeText (getActivity (), R.string.JSONArray_parse_fail_err_str, Toast.LENGTH_SHORT).show (); if (DEBUG) Log.d (TAG, "onClick " + getString (R.string.JSONArray_parse_fail_err_str) + " allNote = " + allNote); } try { int length; length = jsonArray.length (); jsonObject.put (GlobalData.NOTE_INDEX, length); jsonObject.put (GlobalData.NOTE_TITLE, title); jsonObject.put (GlobalData.NOTE_BODY, note); jsonObject.put (GlobalData.NOTE_IS_STAR, false); SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm", Locale.US); long timeInMillis = System.currentTimeMillis (); String date = simpleDateFormat.format (new Date ()); jsonObject.put (GlobalData.NOTE_DATE_STAMP, date); jsonObject.put (GlobalData.NOTE_TIME_MILLIS, timeInMillis); jsonArray.put (length, jsonObject); } catch (JSONException e) { e.printStackTrace (); Toast.makeText (getActivity (), R.string.file_could_not_update_str, Toast.LENGTH_LONG).show (); if (DEBUG) Log.d (TAG, "onClick 1." + getString (R.string.file_could_not_update_str)); } Boolean bool; bool = databaseAdapter.setNote (Integer.parseInt (mSectionIndex) + 1, jsonArray.toString ()); if (DEBUG) Log.d (TAG, "onClick checking JSONArray" + jsonArray.toString ()); if (bool) { populateListView (); } else { Toast.makeText (getActivity (), R.string.file_could_not_update_str, Toast.LENGTH_LONG).show (); if (DEBUG) Log.d (TAG, "onClick 2." + getString (R.string.file_could_not_update_str)); } } @Override public void onListAdapterInteractionListener(final String eventName, final String data2, final String data3) { if (eventName.equals ("populate") && !eventName.equals ("delete")) { listDataSetChanged (); } if (eventName.equals ("delete")) { listDataSetChanged (); CoordinatorLayout coordinatorLayout = (CoordinatorLayout) getActivity ().findViewById (R.id.coordinatorLayout); View.OnClickListener mOnClickListener = new View.OnClickListener () { @Override public void onClick(View v) { NoteUtil noteUtil = new NoteUtil (getActivity ()); try { JSONObject jsonObjectNote = new JSONObject (data3); Boolean bool = noteUtil.addNoteAtPosition (Long.valueOf (data2), jsonObjectNote, Integer.valueOf (mSectionIndex) + 1); if (DEBUG) Toast.makeText (getActivity (), "Note Added " + bool, Toast.LENGTH_SHORT).show (); populateListView (); } catch (JSONException e) { e.printStackTrace (); Toast.makeText (getActivity (), R.string.undo_failed_err_str, Toast.LENGTH_SHORT).show (); } } }; Snackbar snackbar = Snackbar .make (coordinatorLayout, R.string.oops_made_a_mistake_str, Snackbar.LENGTH_LONG) .setAction (R.string.undo_str, mOnClickListener); snackbar.setActionTextColor (Color.RED); View snackView = snackbar.getView (); snackView.setBackgroundColor (Color.DKGRAY); snackbar.show (); } } @Override public void itemClicked(int sectionIndex, int noteIndex) { } @Override public void onListAdapterInteractionListener(String data1, String data2) { } @Override public void populateListViewData(String data, String query) { } public interface OnFragmentInteractionListener { // TODOo: Update argument type and name void onFragmentInteraction(String data1, String data2); int getSectionIndex(); } public void populateListView() { populateListView (""); } /** * @param query search string from the parent activity to display in the recyclerView */ public void populateListView(String query) { if (getActivity () == null) { return; } DatabaseAdapter databaseAdapter = new DatabaseAdapter (getActivity (), this); String allNote = databaseAdapter.getNotesForSection (Integer.parseInt (mSectionIndex) + 1); JSONArray jsonArray = new JSONArray (); try { if (allNote != null) jsonArray = new JSONArray (allNote); } catch (JSONException e) { e.printStackTrace (); Toast.makeText (getActivity (), R.string.all_note_is_corrupted_err_str, Toast.LENGTH_LONG).show (); } mArrayListAllNotes.clear (); for (int count = 0; count < jsonArray.length (); count++) { try { JSONObject jsonObject = jsonArray.getJSONObject (count); String temp = jsonObject.toString (); String noteTitle = jsonObject.getString (GlobalData.NOTE_TITLE); String noteBody = jsonObject.getString (GlobalData.NOTE_BODY); if ((noteBody.toLowerCase ()).contains (query.toLowerCase ()) || (noteTitle.toLowerCase ()).contains (query.toLowerCase ()) || query.equals ("")) { mArrayListAllNotes.add (temp); } } catch (JSONException e) { e.printStackTrace (); Toast.makeText (getActivity (), R.string.updating_list_failed_err_str, Toast.LENGTH_LONG).show (); } } mCustomRecyclerViewAdapterAllNotes.setNoteIndex (mSectionIndex); mRecyclerViewAllNotes.setAdapter (mCustomRecyclerViewAdapterAllNotes); mCustomRecyclerViewAdapterAllNotes.notifyDataSetChanged (); } }
/* * The MIT License * * Copyright 2016 Ahseya. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.horrorho.inflatabledonkey.cloudkitty; import com.github.horrorho.inflatabledonkey.exception.UncheckedInterruptedException; import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.RequestOperation; import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.ResponseOperation; import com.github.horrorho.inflatabledonkey.protobuf.util.ProtobufAssistant; import com.github.horrorho.inflatabledonkey.requests.ProtoBufsRequestFactory; import com.github.horrorho.inflatabledonkey.responsehandler.DelimitedProtobufHandler; import com.github.horrorho.inflatabledonkey.util.ListUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import java.util.stream.IntStream; import javax.annotation.concurrent.ThreadSafe; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpUriRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Super basic concurrent CloudKit client. Requests over our limit (default: 400) are concurrently processed. * * @author Ahseya */ @ThreadSafe public final class CloudKitty { private static final Logger logger = LoggerFactory.getLogger(CloudKitty.class); private static final ResponseHandler<List<ResponseOperation>> RESPONSE_HANDLER = new DelimitedProtobufHandler<>(ResponseOperation::parseFrom); private static final int LIMIT = 400; // TODO inject private final ResponseHandler<List<ResponseOperation>> responseHandler; private final Function<String, RequestOperation.Header> requestOperationHeaders; private final ProtoBufsRequestFactory requestFactory; private final ForkJoinPool forkJoinPool; private final int limit; CloudKitty( ResponseHandler<List<ResponseOperation>> responseHandler, Function<String, RequestOperation.Header> requestOperationHeaders, ProtoBufsRequestFactory requestFactory, ForkJoinPool forkJoinPool, int limit) { this.responseHandler = Objects.requireNonNull(responseHandler); this.requestOperationHeaders = Objects.requireNonNull(requestOperationHeaders); this.requestFactory = Objects.requireNonNull(requestFactory); this.forkJoinPool = Objects.requireNonNull(forkJoinPool); this.limit = limit; } CloudKitty( Function<String, RequestOperation.Header> requestOperationHeaders, ProtoBufsRequestFactory requestFactory, ForkJoinPool forkJoinPool, int limit) { this(RESPONSE_HANDLER, requestOperationHeaders, requestFactory, forkJoinPool, limit); } CloudKitty( Function<String, RequestOperation.Header> requestOperationHeaders, ProtoBufsRequestFactory requestFactory, ForkJoinPool forkJoinPool) { this(requestOperationHeaders, requestFactory, forkJoinPool, LIMIT); } public List<ResponseOperation> get(HttpClient httpClient, String api, String operation, List<RequestOperation> requests) throws IOException { return get(httpClient, api, operation, requests, Function.identity()); } public <T> List<T> get(HttpClient httpClient, String api, String key, List<RequestOperation> requests, Function<ResponseOperation, T> field) throws IOException { return execute(httpClient, api, requestOperationHeaders.apply(key), requests, field); } <T> List<T> execute(HttpClient httpClient, String api, RequestOperation.Header header, List<RequestOperation> requests, Function<ResponseOperation, T> field) throws IOException { try { logger.debug("-- execute() - requests: {}", requests.size()); logger.trace("-- execute() - requests: {}", requests); // Split and concurrently pipeline requests over our limit. List<List<RequestOperation>> split = ListUtils.split(requests, limit); logger.debug("-- execute() - split: {}", split.size()); List<SimpleImmutableEntry<Integer, List<RequestOperation>>> list = IntStream.range(0, split.size()) .mapToObj(i -> new SimpleImmutableEntry<>(i, split.get(i))) .collect(toList()); List<SimpleImmutableEntry<Integer, List<ResponseOperation>>> get = forkJoinPool.submit(() -> list.parallelStream() .map(u -> new SimpleImmutableEntry<>(u.getKey(), request(httpClient, api, header, u.getValue()))) .collect(toList())) .get(); // Order responses to match requests. List<T> reordered = get.stream() .sorted(Comparator.comparing(Map.Entry::getKey)) .map(Map.Entry::getValue) .flatMap(Collection::stream) .map(field) .collect(Collectors.toList()); if (reordered.size() != requests.size()) { logger.warn("-- execute() - requests: {} reordered: {}", requests.size(), reordered.size()); throw new IOException("CloudKitty execute, bad response"); } return reordered; } catch (InterruptedException ex) { throw new UncheckedInterruptedException(ex); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof UncheckedIOException) { throw ((UncheckedIOException) cause).getCause(); } throw new RuntimeException(cause); } } List<ResponseOperation> request(HttpClient httpClient, String api, RequestOperation.Header header, List<RequestOperation> requests) throws UncheckedIOException { logger.trace("<< request() - httpClient: {} header: {} requests: {}", httpClient, header, requests); logger.debug("-- request() - requests: {}", requests.size()); assert (!requests.isEmpty()); byte[] data = encode(header, requests.iterator()); List<ResponseOperation> responses = client(httpClient, api, data); logger.trace(">> request() - responses: {}", responses); return responses; } byte[] encode(RequestOperation.Header header, Iterator<RequestOperation> it) throws UncheckedIOException { try { assert (it.hasNext()); ByteArrayOutputStream os = new ByteArrayOutputStream(); CKProto.requestOperationWithHeader(it.next(), header).writeDelimitedTo(os); for (int i = 1; it.hasNext() && i < limit; i++) { it.next().writeDelimitedTo(os); } return os.toByteArray(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } List<ResponseOperation> client(HttpClient httpClient, String api, byte[] data) { try { HttpUriRequest uriRequest = requestFactory.apply(api, UUID.randomUUID(), data); List<ResponseOperation> responses = httpClient.execute(uriRequest, responseHandler); responses.forEach(ProtobufAssistant::logDebugUnknownFields); return responses; } catch (IOException ex) { throw new UncheckedIOException(ex); } } public String cloudKitUserId() { return requestFactory.cloudKitUserId(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.ignite.testsuites; import org.apache.ignite.internal.processors.cache.AtomicCacheAffinityConfigurationTest; import org.apache.ignite.internal.processors.cache.consistency.AtomicReadRepairTest; import org.apache.ignite.internal.processors.cache.consistency.ExplicitTransactionalReadRepairTest; import org.apache.ignite.internal.processors.cache.consistency.ImplicitTransactionalReadRepairTest; import org.apache.ignite.internal.processors.cache.consistency.ReplicatedExplicitTransactionalReadRepairTest; import org.apache.ignite.internal.processors.cache.consistency.ReplicatedImplicitTransactionalReadRepairTest; import org.apache.ignite.internal.processors.cache.consistency.SingleBackupExplicitTransactionalReadRepairTest; import org.apache.ignite.internal.processors.cache.consistency.SingleBackupImplicitTransactionalReadRepairTest; import org.apache.ignite.internal.processors.cache.datastructures.GridCacheQueueCleanupSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.GridCacheQueueClientDisconnectTest; import org.apache.ignite.internal.processors.cache.datastructures.GridCacheQueueMultiNodeConsistencySelfTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteAtomicLongClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteAtomicReferenceClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteAtomicSequenceClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteAtomicStampedClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteClientDataStructuresTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteClientDiscoveryDataStructuresTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteCountDownLatchClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteDataStructureUniqueNameTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteDataStructureWithJobTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteDataStructuresCreateDeniedInClusterReadOnlyMode; import org.apache.ignite.internal.processors.cache.datastructures.IgniteDataStructuresNoClassOnServerTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteQueueClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteSequenceInternalCleanupTest; import org.apache.ignite.internal.processors.cache.datastructures.IgniteSetClusterReadOnlyTest; import org.apache.ignite.internal.processors.cache.datastructures.OutOfMemoryVolatileRegionTest; import org.apache.ignite.internal.processors.cache.datastructures.SemaphoreFailoverNoWaitingAcquirerTest; import org.apache.ignite.internal.processors.cache.datastructures.SemaphoreFailoverSafeReleasePermitsTest; import org.apache.ignite.internal.processors.cache.datastructures.local.GridCacheLocalAtomicQueueApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.GridCacheLocalAtomicSetSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.GridCacheLocalQueueApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.GridCacheLocalSequenceApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.GridCacheLocalSetSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.IgniteLocalAtomicLongApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.IgniteLocalCountDownLatchSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.IgniteLocalLockSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.local.IgniteLocalSemaphoreSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicQueueApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicQueueCreateMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicQueueFailoverDataConsistencySelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicQueueMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicQueueRotativeMultiNodeTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicReferenceApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicReferenceMultiNodeTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicSequenceMultiThreadedTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicSequenceTxSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicSetFailoverSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicSetSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedAtomicStampedApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedDataStructuresFailoverSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedNodeRestartTxSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueCreateMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueEntryMoveSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueFailoverDataConsistencySelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueJoinedNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedQueueRotativeMultiNodeTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedSequenceApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedSequenceMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedSetFailoverSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedSetSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedSetWithClientSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.GridCachePartitionedSetWithNodeFilterSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.IgnitePartitionedAtomicLongApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.IgnitePartitionedCountDownLatchSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.IgnitePartitionedLockSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.IgnitePartitionedQueueNoBackupsTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.IgnitePartitionedSemaphoreSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.partitioned.IgnitePartitionedSetNoBackupsSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedAtomicReferenceApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedAtomicReferenceMultiNodeTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedAtomicStampedApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedDataStructuresFailoverSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedQueueApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedQueueMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedQueueRotativeMultiNodeTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedSequenceApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedSequenceMultiNodeSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedSetSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedSetWithClientSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.GridCacheReplicatedSetWithNodeFilterSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.IgniteReplicatedAtomicLongApiSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.IgniteReplicatedCountDownLatchSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.IgniteReplicatedLockSelfTest; import org.apache.ignite.internal.processors.cache.datastructures.replicated.IgniteReplicatedSemaphoreSelfTest; import org.apache.ignite.internal.processors.cache.distributed.replicated.IgniteCacheAtomicReplicatedNodeRestartSelfTest; import org.apache.ignite.internal.processors.datastructures.GridCacheReplicatedQueueRemoveSelfTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * Test suite for cache data structures. */ @RunWith(Suite.class) @Suite.SuiteClasses({ GridCachePartitionedQueueFailoverDataConsistencySelfTest.class, GridCachePartitionedAtomicQueueFailoverDataConsistencySelfTest.class, GridCacheLocalSequenceApiSelfTest.class, GridCacheLocalSetSelfTest.class, GridCacheLocalAtomicSetSelfTest.class, GridCacheLocalQueueApiSelfTest.class, GridCacheLocalAtomicQueueApiSelfTest.class, IgniteLocalCountDownLatchSelfTest.class, IgniteLocalSemaphoreSelfTest.class, IgniteLocalLockSelfTest.class, GridCacheReplicatedSequenceApiSelfTest.class, GridCacheReplicatedSequenceMultiNodeSelfTest.class, GridCacheReplicatedQueueApiSelfTest.class, GridCacheReplicatedQueueMultiNodeSelfTest.class, GridCacheReplicatedQueueRotativeMultiNodeTest.class, GridCacheReplicatedSetSelfTest.class, GridCacheReplicatedSetWithClientSelfTest.class, GridCacheReplicatedSetWithNodeFilterSelfTest.class, GridCacheReplicatedDataStructuresFailoverSelfTest.class, IgniteReplicatedCountDownLatchSelfTest.class, IgniteReplicatedSemaphoreSelfTest.class, IgniteReplicatedLockSelfTest.class, IgniteCacheAtomicReplicatedNodeRestartSelfTest.class, GridCacheReplicatedQueueRemoveSelfTest.class, OutOfMemoryVolatileRegionTest.class, GridCachePartitionedSequenceApiSelfTest.class, GridCachePartitionedSequenceMultiNodeSelfTest.class, GridCachePartitionedQueueApiSelfTest.class, GridCachePartitionedAtomicQueueApiSelfTest.class, GridCachePartitionedQueueMultiNodeSelfTest.class, GridCachePartitionedAtomicQueueMultiNodeSelfTest.class, GridCacheQueueClientDisconnectTest.class, GridCachePartitionedQueueCreateMultiNodeSelfTest.class, GridCachePartitionedAtomicQueueCreateMultiNodeSelfTest.class, GridCachePartitionedSetSelfTest.class, GridCachePartitionedSetWithClientSelfTest.class, GridCachePartitionedSetWithNodeFilterSelfTest.class, IgnitePartitionedSetNoBackupsSelfTest.class, GridCachePartitionedAtomicSetSelfTest.class, IgnitePartitionedCountDownLatchSelfTest.class, IgniteDataStructureWithJobTest.class, IgnitePartitionedSemaphoreSelfTest.class, SemaphoreFailoverSafeReleasePermitsTest.class, SemaphoreFailoverNoWaitingAcquirerTest.class, IgnitePartitionedLockSelfTest.class, GridCachePartitionedSetFailoverSelfTest.class, GridCachePartitionedAtomicSetFailoverSelfTest.class, GridCachePartitionedQueueRotativeMultiNodeTest.class, GridCachePartitionedAtomicQueueRotativeMultiNodeTest.class, GridCacheQueueCleanupSelfTest.class, GridCachePartitionedQueueEntryMoveSelfTest.class, GridCachePartitionedDataStructuresFailoverSelfTest.class, GridCacheQueueMultiNodeConsistencySelfTest.class, IgniteLocalAtomicLongApiSelfTest.class, IgnitePartitionedAtomicLongApiSelfTest.class, IgniteReplicatedAtomicLongApiSelfTest.class, GridCachePartitionedAtomicSequenceMultiThreadedTest.class, GridCachePartitionedAtomicSequenceTxSelfTest.class, GridCachePartitionedAtomicStampedApiSelfTest.class, GridCacheReplicatedAtomicStampedApiSelfTest.class, GridCachePartitionedAtomicReferenceApiSelfTest.class, GridCacheReplicatedAtomicReferenceApiSelfTest.class, GridCachePartitionedAtomicReferenceMultiNodeTest.class, GridCacheReplicatedAtomicReferenceMultiNodeTest.class, GridCachePartitionedNodeRestartTxSelfTest.class, GridCachePartitionedQueueJoinedNodeSelfTest.class, IgniteDataStructureUniqueNameTest.class, IgniteDataStructuresNoClassOnServerTest.class, IgniteClientDataStructuresTest.class, IgniteClientDiscoveryDataStructuresTest.class, IgnitePartitionedQueueNoBackupsTest.class, IgniteSequenceInternalCleanupTest.class, AtomicCacheAffinityConfigurationTest.class, IgniteCacheDataStructuresBinarySelfTestSuite.class, ImplicitTransactionalReadRepairTest.class, SingleBackupImplicitTransactionalReadRepairTest.class, ReplicatedImplicitTransactionalReadRepairTest.class, AtomicReadRepairTest.class, ExplicitTransactionalReadRepairTest.class, SingleBackupExplicitTransactionalReadRepairTest.class, ReplicatedExplicitTransactionalReadRepairTest.class, IgniteAtomicLongClusterReadOnlyTest.class, IgniteAtomicReferenceClusterReadOnlyTest.class, IgniteAtomicSequenceClusterReadOnlyTest.class, IgniteAtomicStampedClusterReadOnlyTest.class, IgniteCountDownLatchClusterReadOnlyTest.class, IgniteDataStructuresCreateDeniedInClusterReadOnlyMode.class, IgniteQueueClusterReadOnlyTest.class, IgniteSetClusterReadOnlyTest.class }) public class IgniteCacheDataStructuresSelfTestSuite { }
/* JNativeHook: Global keyboard and mouse hooking for Java. * Copyright (C) 2006-2013 Alexander Barker. All Rights Received. * http://code.google.com/p/jnativehook/ * * JNativeHook is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JNativeHook is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jnativehook; //Imports import java.io.File; import java.io.UnsupportedEncodingException; import java.util.EventListener; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.swing.event.EventListenerList; import org.jnativehook.keyboard.NativeKeyEvent; import org.jnativehook.keyboard.NativeKeyListener; import org.jnativehook.mouse.NativeMouseEvent; import org.jnativehook.mouse.NativeMouseListener; import org.jnativehook.mouse.NativeMouseMotionListener; import org.jnativehook.mouse.NativeMouseWheelEvent; import org.jnativehook.mouse.NativeMouseWheelListener; import bg.abv.king_hell.util.Util; /** * GlobalScreen is used to represent the native screen area that Java does not * usually have access to. This class can be thought of as the source component * for native input events. * <p /> * This class also handles the loading, unpacking and communication with the * native library. That includes registering and unregistering the native hook * with the underlying operating system and adding global keyboard and mouse * listeners. * * @author Alexander Barker (<a href="mailto:[email protected]">[email protected]</a>) * @editor Nikola "King_Hual" Yanakiev */ public class GlobalScreen { /** The GlobalScreen singleton. */ private static GlobalScreen instance; /** The list of event listeners to notify. */ private EventListenerList eventListeners; /** The service to dispatch events. */ private ExecutorService eventExecutor; public static void initialize() { instance = new GlobalScreen(); } /** * Private constructor to prevent multiple instances of the global screen. * The {@link #registerNativeHook} method will be called on construction to * unpack and load the native library. */ private GlobalScreen() { //Setup instance variables. eventListeners = new EventListenerList(); //Unpack and Load the native library. GlobalScreen.loadNativeLibrary(); } /** * A destructor that will perform native cleanup by calling the * {@link #unregisterNativeHook} method. This method will not run until the * class is garbage collected. * * @throws Throwable a <code>NativeHookException</code> raised by calling * {@link #unloadNativeLibrary()} * @see Object#finalize */ @Override protected void finalize() throws Throwable { if (GlobalScreen.isNativeHookRegistered()) { GlobalScreen.unloadNativeLibrary(); } super.finalize(); } /** * Returns the singleton instance of <code>GlobalScreen</code>. * * @return singleton instance of <code>GlobalScreen</code> */ public static GlobalScreen getInstance() { return GlobalScreen.instance; } /** * Adds the specified native key listener to receive key events from the * native system. If listener is null, no exception is thrown and no action * is performed. * * @param listener a native key listener object */ public void addNativeKeyListener(NativeKeyListener listener) { if (listener != null) { eventListeners.add(NativeKeyListener.class, listener); } } /** * Removes the specified native key listener so that it no longer receives * key events from the native system. This method performs no function if * the listener specified by the argument was not previously added. If * listener is null, no exception is thrown and no action is performed. * * @param listener a native key listener object */ public void removeNativeKeyListener(NativeKeyListener listener) { if (listener != null) { eventListeners.remove(NativeKeyListener.class, listener); } } /** * Adds the specified native mouse listener to receive mouse events from the * native system. If listener is null, no exception is thrown and no action * is performed. * * @param listener a native mouse listener object */ public void addNativeMouseListener(NativeMouseListener listener) { if (listener != null) { eventListeners.add(NativeMouseListener.class, listener); } } /** * Removes the specified native mouse listener so that it no longer receives * mouse events from the native system. This method performs no function if * the listener specified by the argument was not previously added. If * listener is null, no exception is thrown and no action is performed. * * @param listener a native mouse listener object */ public void removeNativeMouseListener(NativeMouseListener listener) { if (listener != null) { eventListeners.remove(NativeMouseListener.class, listener); } } /** * Adds the specified native mouse motion listener to receive mouse motion * events from the native system. If listener is null, no exception is * thrown and no action is performed. * * @param listener a native mouse motion listener object */ public void addNativeMouseMotionListener(NativeMouseMotionListener listener) { if (listener != null) { eventListeners.add(NativeMouseMotionListener.class, listener); } } /** * Removes the specified native mouse motion listener so that it no longer * receives mouse motion events from the native system. This method performs * no function if the listener specified by the argument was not previously * added. If listener is null, no exception is thrown and no action is * performed. * * @param listener a native mouse motion listener object */ public void removeNativeMouseMotionListener(NativeMouseMotionListener listener) { if (listener != null) { eventListeners.remove(NativeMouseMotionListener.class, listener); } } /** * Adds the specified native mouse wheel listener to receive mouse wheel * events from the native system. If listener is null, no exception is * thrown and no action is performed. * * @param listener a native mouse wheel listener object * * @since 1.1 */ public void addNativeMouseWheelListener(NativeMouseWheelListener listener) { if (listener != null) { eventListeners.add(NativeMouseWheelListener.class, listener); } } /** * Removes the specified native mouse wheel listener so that it no longer * receives mouse wheel events from the native system. This method performs * no function if the listener specified by the argument was not previously * added. If listener is null, no exception is thrown and no action is * performed. * * @param listener a native mouse wheel listener object * * @since 1.1 */ public void removeNativeMouseWheelListener(NativeMouseWheelListener listener) { if (listener != null) { eventListeners.remove(NativeMouseWheelListener.class, listener); } } /** * Enable the native hook if it is not currently running. If it is running * the function has no effect. * <p /> * <b>Note: </b> This method will throw a <code>NativeHookException</code> * if specific operating system features are unavailable or disabled. * For example: Access for assistive devices is unchecked in the Universal * Access section of the System Preferences on Apple's OS X platform or * <code>Load "record"</code> is missing for the xorg.conf file on * Unix/Linux/Solaris platforms. * * @throws NativeHookException problem registering the native hook with * the underlying operating system. * * @since 1.1 */ public static native void registerNativeHook() throws NativeHookException; /** * Disable the native hook if it is currently registered. If the native * hook it is not registered the function has no effect. * * @since 1.1 */ public static native void unregisterNativeHook(); /** * Returns <code>true</code> if the native hook is currently registered. * * @return true if the native hook is currently registered. * @throws NativeHookException the native hook exception * * @since 1.1 */ public static native boolean isNativeHookRegistered(); /** * Dispatches an event to the appropriate processor. This method is * generally called by the native library but maybe used to synthesize * native events from Java. * * @param e the <code>NativeInputEvent</code> to dispatch. */ public final void dispatchEvent(final NativeInputEvent e) { eventExecutor.execute(new Runnable() { public void run() { if (e instanceof NativeKeyEvent) { processKeyEvent((NativeKeyEvent) e); } else if (e instanceof NativeMouseWheelEvent) { processMouseWheelEvent((NativeMouseWheelEvent) e); } else if (e instanceof NativeMouseEvent) { processMouseEvent((NativeMouseEvent) e); } } }); } /** * Processes native key events by dispatching them to all registered * <code>NativeKeyListener</code> objects. * * @param e the <code>NativeKeyEvent</code> to dispatch. * @see NativeKeyEvent * @see NativeKeyListener * @see #addNativeKeyListener(NativeKeyListener) */ protected void processKeyEvent(NativeKeyEvent e) { int id = e.getID(); EventListener[] listeners = eventListeners.getListeners(NativeKeyListener.class); for (int i = 0; i < listeners.length; i++) { switch (id) { case NativeKeyEvent.NATIVE_KEY_PRESSED: ((NativeKeyListener) listeners[i]).nativeKeyPressed(e); break; case NativeKeyEvent.NATIVE_KEY_TYPED: ((NativeKeyListener) listeners[i]).nativeKeyTyped(e); break; case NativeKeyEvent.NATIVE_KEY_RELEASED: ((NativeKeyListener) listeners[i]).nativeKeyReleased(e); break; } } } /** * Processes native mouse events by dispatching them to all registered * <code>NativeMouseListener</code> objects. * * @param e the <code>NativeMouseEvent</code> to dispatch. * @see NativeMouseEvent * @see NativeMouseListener * @see #addNativeMouseListener(NativeMouseListener) */ protected void processMouseEvent(NativeMouseEvent e) { int id = e.getID(); EventListener[] listeners; if (id == NativeMouseEvent.NATIVE_MOUSE_MOVED || id == NativeMouseEvent.NATIVE_MOUSE_DRAGGED) { listeners = eventListeners.getListeners(NativeMouseMotionListener.class); } else { listeners = eventListeners.getListeners(NativeMouseListener.class); } for (int i = 0; i < listeners.length; i++) { switch (id) { case NativeMouseEvent.NATIVE_MOUSE_CLICKED: ((NativeMouseListener) listeners[i]).nativeMouseClicked(e); break; case NativeMouseEvent.NATIVE_MOUSE_PRESSED: ((NativeMouseListener) listeners[i]).nativeMousePressed(e); break; case NativeMouseEvent.NATIVE_MOUSE_RELEASED: ((NativeMouseListener) listeners[i]).nativeMouseReleased(e); break; case NativeMouseEvent.NATIVE_MOUSE_MOVED: ((NativeMouseMotionListener) listeners[i]).nativeMouseMoved(e); break; case NativeMouseEvent.NATIVE_MOUSE_DRAGGED: ((NativeMouseMotionListener) listeners[i]).nativeMouseDragged(e); break; } } } /** * Processes native mouse wheel events by dispatching them to all registered * <code>NativeMouseWheelListener</code> objects. * * @param e The <code>NativeMouseWheelEvent</code> to dispatch. * @see NativeMouseWheelEvent * @see NativeMouseWheelListener * @see #addNativeMouseWheelListener(NativeMouseWheelListener) * * @since 1.1 */ protected void processMouseWheelEvent(NativeMouseWheelEvent e) { EventListener[] listeners = eventListeners.getListeners(NativeMouseWheelListener.class); for (int i = 0; i < listeners.length; i++) { ((NativeMouseWheelListener) listeners[i]).nativeMouseWheelMoved(e); } } /** * Initialize a local executor service for event delivery. This method * should only be called by the native library during the hook registration * process. * * @since 1.1 */ protected void startEventDispatcher() { // Create a new single thread executor. eventExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("JNativeHook Native Dispatch"); return t; } }); } /** * Shutdown the local executor service for event delivery. Any events * events pending delivery will be discarded. This method should only be * called by the native library during the hook deregistration process. * * @since 1.1 */ protected void stopEventDispatcher() { if (eventExecutor != null) { // Shutdown the current Event executor. eventExecutor.shutdownNow(); eventExecutor = null; } } public static String getLibraryName() { return ("hooklib"+System.mapLibraryName("").substring(System.mapLibraryName("").lastIndexOf('.'))).replaceAll("\\.jnilib$", "\\.dylib"); } public static String getLibraryPath() throws UnsupportedEncodingException { return Util.getDataFolder()+getLibraryName(); } public static boolean libraryExists() { try { return new File(getLibraryPath()).exists(); } catch(Exception e) { return false; } } /** * Perform procedures to interface with the native library. These procedures * include unpacking and loading the library into the Java Virtual Machine. */ protected static void loadNativeLibrary() { try { System.load(getLibraryPath()); } catch(Exception e){ } } /** * Perform procedures to cleanup the native library. This method is called * on garbage collection to ensure proper native cleanup. */ protected static void unloadNativeLibrary() throws NativeHookException { //Make sure the native thread has stopped. unregisterNativeHook(); } }
package kornell.gui.client.util.forms.formfield; import static kornell.core.util.StringUtils.isNone; import java.util.List; import com.github.gwtbootstrap.client.ui.Icon; import com.github.gwtbootstrap.client.ui.ListBox; import com.github.gwtbootstrap.client.ui.TextBox; import com.github.gwtbootstrap.client.ui.Tooltip; import com.github.gwtbootstrap.client.ui.constants.Placement; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.HasChangeHandlers; import com.google.gwt.event.dom.client.HasKeyUpHandlers; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.EventBus; import com.google.web.bindery.event.shared.SimpleEventBus; import kornell.api.client.Callback; import kornell.gui.client.util.validation.ValidationChangedEvent; import kornell.gui.client.util.validation.ValidationChangedHandler; import kornell.gui.client.util.validation.Validator; public class KornellFormFieldWrapper extends Composite { EventBus fieldBus = new SimpleEventBus(); interface MyUiBinder extends UiBinder<Widget, KornellFormFieldWrapper> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField FlowPanel fieldPanelWrapper; @UiField FlowPanel labelPanel; @UiField Label fieldLabel; @UiField FlowPanel fieldPanel; TextBox fieldTextBox; ListBox fieldListBox; SimpleDatePicker fieldSimpleDatePicker; Label fieldError; Label fieldTxt; boolean isEditMode; KornellFormField<?> formField; private Validator validator; private Timer updateTimer; public KornellFormFieldWrapper(String label, KornellFormField<?> formField) { this(label, formField, true, null); } public KornellFormFieldWrapper(String label, KornellFormField<?> formField, boolean isEditMode) { this(label, formField, isEditMode, null); } public KornellFormFieldWrapper(String label, KornellFormField<?> formField, boolean isEditMode, Validator validator) { this(label, formField, isEditMode, validator, null); } public KornellFormFieldWrapper(String label, KornellFormField<?> formField, boolean isEditMode, Validator validator, String tooltipText) { initWidget(uiBinder.createAndBindUi(this)); fieldLabel.setText(label); if (tooltipText != null && isEditMode) { Icon icon = new Icon(); icon.addStyleName("fa fa-question-circle"); Tooltip tooltip = new Tooltip(tooltipText); tooltip.setPlacement(Placement.TOP); tooltip.add(icon); labelPanel.add(tooltip); } this.formField = formField; this.isEditMode = isEditMode; this.validator = validator; initData(formField); updateTimer = new Timer() { @Override public void run() { validate(); } }; } public void initData(KornellFormField<?> formField) { fieldPanel.clear(); this.formField = formField; if (!isEditMode) { fieldTxt = new Label(); fieldTxt.addStyleName("lblValue"); fieldTxt.setText(formField.getDisplayText()); fieldPanel.add(fieldTxt); } else { final Widget fieldWidget = formField.getFieldWidget(); fieldPanel.add(fieldWidget); if (fieldWidget instanceof HasKeyUpHandlers) { HasKeyUpHandlers ku = (HasKeyUpHandlers) fieldWidget; if (validator != null) { ku.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { scheduleValidation(); } }); } } if (fieldWidget instanceof HasChangeHandlers) { HasChangeHandlers ku = (HasChangeHandlers) fieldWidget; if (validator != null) { ku.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { scheduleValidation(); } }); } } fieldError = new Label(); fieldError.addStyleName("error"); fieldPanel.add(fieldError); } } private void validate() { validator.getErrors(formField.getFieldWidget(), new Callback<List<String>>() { @Override public void ok(List<String> errors) { if (errors.isEmpty()) { setError(""); } else { showErrors(errors); } fieldBus.fireEvent(new ValidationChangedEvent()); } }); } public void scheduleValidation() { updateTimer.cancel(); updateTimer.schedule(500); } private void showErrors(List<String> errorKeys) { StringBuilder buf = new StringBuilder(); for (String e : errorKeys) { buf.append(e); } setError(buf.toString()); } public KornellFormField<?> getFormField() { return formField; } public void setFieldLabelText(String text) { fieldLabel.setText(text); } public Widget getFieldWidget() { return formField.getFieldWidget(); } public String getFieldDisplayText() { return formField.getDisplayText(); } public String getFieldPersistText() { return formField.getPersistText(); } public void setError(String text) { if (fieldError != null) fieldError.setText(text); } public String getError() { return fieldError != null ? fieldError.getText() : ""; } public void clearError() { if (fieldError != null) { fieldError.setText(""); } } public void addStyleName(String styleName) { fieldPanelWrapper.addStyleName(styleName); } public boolean isValid() { return fieldError == null || isNone(fieldError.getText()); } public void addValidationListener(ValidationChangedHandler handler) { fieldBus.addHandler(ValidationChangedEvent.TYPE, handler); } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * DescribeBundleTasksItemType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.6 Built on : Aug 30, 2011 (10:01:01 CEST) */ package com.amazon.ec2; /** * DescribeBundleTasksItemType bean class */ public class DescribeBundleTasksItemType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = DescribeBundleTasksItemType Namespace URI = http://ec2.amazonaws.com/doc/2012-08-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for BundleId */ protected java.lang.String localBundleId ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getBundleId(){ return localBundleId; } /** * Auto generated setter method * @param param BundleId */ public void setBundleId(java.lang.String param){ this.localBundleId=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { DescribeBundleTasksItemType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2012-08-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":DescribeBundleTasksItemType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "DescribeBundleTasksItemType", xmlWriter); } } namespace = "http://ec2.amazonaws.com/doc/2012-08-15/"; if (! namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); xmlWriter.writeStartElement(prefix,"bundleId", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace,"bundleId"); } } else { xmlWriter.writeStartElement("bundleId"); } if (localBundleId==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("bundleId cannot be null!!"); }else{ xmlWriter.writeCharacters(localBundleId); } xmlWriter.writeEndElement(); xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/", "bundleId")); if (localBundleId != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localBundleId)); } else { throw new org.apache.axis2.databinding.ADBException("bundleId cannot be null!!"); } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DescribeBundleTasksItemType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DescribeBundleTasksItemType object = new DescribeBundleTasksItemType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"DescribeBundleTasksItemType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (DescribeBundleTasksItemType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","bundleId").equals(reader.getName())){ java.lang.String content = reader.getElementText(); object.setBundleId( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
/** * The MIT License (MIT) * * Copyright (c) 2016 developers-payu-latam * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.utils; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.payu.sdk.PayU; import com.payu.sdk.constants.Constants; import com.payu.sdk.enums.SubscriptionCreationSource; import com.payu.sdk.exceptions.InvalidParametersException; import com.payu.sdk.exceptions.PayUException; import com.payu.sdk.model.AdditionalValue; import com.payu.sdk.model.Address; import com.payu.sdk.model.Currency; import com.payu.sdk.model.PaymentMethodType; import com.payu.sdk.model.request.Request; import com.payu.sdk.paymentplan.model.BankAccount; import com.payu.sdk.paymentplan.model.Customer; import com.payu.sdk.paymentplan.model.PaymentPlanCreditCard; import com.payu.sdk.paymentplan.model.RecurringBill; import com.payu.sdk.paymentplan.model.RecurringBillItem; import com.payu.sdk.paymentplan.model.RecurringBillPaymentRetry; import com.payu.sdk.paymentplan.model.Subscription; import com.payu.sdk.paymentplan.model.SubscriptionPlan; import com.payu.sdk.payments.model.BankAccountListRequest; import com.payu.sdk.payments.model.CustomerListRequest; import com.payu.sdk.payments.model.PaymentPlanCreditCardListRequest; import com.payu.sdk.payments.model.RecurringBillItemListRequest; import com.payu.sdk.payments.model.RecurringBillListRequest; import com.payu.sdk.payments.model.SubscriptionPlanListRequest; import com.payu.sdk.payments.model.SubscriptionsListRequest; /** * Utility for payment plan requests in the PayU SDK. * * @author PayU Latam * @since 1.0.0 * @version 1.0.0, 11/09/2013 */ public final class PaymentPlanRequestUtil extends CommonRequestUtil { /** * Private Constructor */ private PaymentPlanRequestUtil() { } // valid keys for CreditCard public static final String[] CREDIT_CARD_VALID_PARAMS = new String[] { PayU.PARAMETERS.TOKEN_ID, PayU.PARAMETERS.CREDIT_CARD_NUMBER, PayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE, PayU.PARAMETERS.PAYMENT_METHOD, PayU.PARAMETERS.PAYER_NAME, PayU.PARAMETERS.PAYER_STREET, PayU.PARAMETERS.PAYER_STREET_2, PayU.PARAMETERS.PAYER_STREET_3, PayU.PARAMETERS.PAYER_CITY, PayU.PARAMETERS.PAYER_STATE, PayU.PARAMETERS.PAYER_COUNTRY, PayU.PARAMETERS.PAYER_POSTAL_CODE, PayU.PARAMETERS.PAYER_PHONE }; // valid keys for BankAccount public static final String[] BANK_ACCOUNT_VALID_PARAMS = new String[] { PayU.PARAMETERS.BANK_ACCOUNT_ID, PayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER, PayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER_TYPE, PayU.PARAMETERS.BANK_ACCOUNT_CUSTOMER_NAME, PayU.PARAMETERS.BANK_ACCOUNT_AGENCY_NUMBER, PayU.PARAMETERS.BANK_ACCOUNT_AGENCY_DIGIT, PayU.PARAMETERS.BANK_ACCOUNT_ACCOUNT_DIGIT, PayU.PARAMETERS.BANK_ACCOUNT_NUMBER, PayU.PARAMETERS.BANK_ACCOUNT_BANK_NAME, PayU.PARAMETERS.BANK_ACCOUNT_TYPE, PayU.PARAMETERS.BANK_ACCOUNT_STATE }; public final static String EMPTY = ""; /* Build Methods */ /* PRIVATE METHODS */ /** * Build the plan additional values (currency and value) * * @param txCurrency * The currency of the plan * @param txValue * The value of the plan * @param txTax * The tax of the plan * @param txTaxReturnBase * The tax return base of the plan * @param txAdditionalValue * The additional value of the plan * @return The created list of additional values */ private static List<AdditionalValue> buildPlanAdditionalValues( Currency txCurrency, BigDecimal txValue, BigDecimal txTax, BigDecimal txTaxReturnBase, BigDecimal txAdditionalValue) { if (txCurrency == null || txValue == null) { return null; } List<AdditionalValue> values = new ArrayList<AdditionalValue>(); addAdditionalValue(txCurrency, Constants.PLAN_VALUE, txValue, values); addAdditionalValue(txCurrency, Constants.PLAN_TAX, txTax, values); addAdditionalValue(txCurrency, Constants.PLAN_TAX_RETURN_BASE, txTaxReturnBase, values); addAdditionalValue(txCurrency, Constants.PLAN_ADDITIONAL_VALUE, txAdditionalValue, values); return values; } /** * Build the item additional values (currency and value) * * @param txCurrency * The currency of the plan * @param txValue * The value of the plan * @param txTax * The tax of the plan * @param txTaxReturnBase * The tax return base of the plan * @return The created list of additional values */ private static List<AdditionalValue> buildItemAdditionalValues( Currency txCurrency, BigDecimal txValue, BigDecimal txTax, BigDecimal txTaxReturnBase) { if (txCurrency == null || txValue == null) { return null; } List<AdditionalValue> values = new ArrayList<AdditionalValue>(); addAdditionalValue(txCurrency, Constants.ITEM_VALUE, txValue, values); addAdditionalValue(txCurrency, Constants.ITEM_TAX, txTax, values); addAdditionalValue(txCurrency, Constants.ITEM_TAX_RETURN_BASE, txTaxReturnBase, values); return values; } /** * Creates or updates an additional value * * @param txCurrency * The transaction currency * @param name * The additional value name * @param value * The additional value value * @param additionalValues * The additional values list */ private static void addAdditionalValue(Currency txCurrency, String name, BigDecimal value, List<AdditionalValue> additionalValues) { if (value != null) { AdditionalValue additionalValue = new AdditionalValue(); additionalValue.setName(name); additionalValue.setCurrency(txCurrency); additionalValue.setValue(value); additionalValues.add(additionalValue); } } /* PUBLIC METHODS */ /** * Builds a costumer request * * @param parameters * The parameters to be sent to the server * @return The complete remove credit card token request */ public static Customer buildCustomerRequest(Map<String, String> parameters) { String customerName = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_NAME); String customerEmail = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_EMAIL); String customerId = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_ID); Customer request = new Customer(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setFullName(customerName); request.setEmail(customerEmail); request.setId(customerId); return request; } /** * Builds a costumer request * * @param parameters * The parameters to be sent to the server * @return The request by customerRequestList * @throws PayUException */ public static CustomerListRequest buildCustomerListRequest(Map<String, String> parameters) throws PayUException { Map<String, String> parametersFilter=new HashMap<String, String>(); parametersFilter.put(PayU.PARAMETERS.PLAN_ID, parameters.get(PayU.PARAMETERS.PLAN_ID)); parametersFilter.put(PayU.PARAMETERS.PLAN_CODE, parameters.get(PayU.PARAMETERS.PLAN_CODE)); parametersFilter.put(PayU.PARAMETERS.LIMIT, parameters.get(PayU.PARAMETERS.LIMIT)); parametersFilter.put(PayU.PARAMETERS.OFFSET, parameters.get(PayU.PARAMETERS.OFFSET)); CustomerListRequest request = new CustomerListRequest(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setMap(parametersFilter); return request; } /** * Builds a credit card request * * @param parameters * The parameters to be sent to the server * @return The complete credit card request * @throws InvalidParametersException */ public static PaymentPlanCreditCard buildCreditCardRequest( Map<String, String> parameters) throws InvalidParametersException { String tokenId = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID); String customerId = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_ID); String creditCardNumber = getParameter(parameters, PayU.PARAMETERS.CREDIT_CARD_NUMBER); String creditCardName = getParameter(parameters, PayU.PARAMETERS.PAYER_NAME); String type = getParameter(parameters, PayU.PARAMETERS.PAYMENT_METHOD); String line1 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET); String line2 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_2); String line3 = getParameter(parameters, PayU.PARAMETERS.PAYER_STREET_3); String city = getParameter(parameters, PayU.PARAMETERS.PAYER_CITY); String state = getParameter(parameters, PayU.PARAMETERS.PAYER_STATE); String country = getParameter(parameters, PayU.PARAMETERS.PAYER_COUNTRY); String postalCode = getParameter(parameters, PayU.PARAMETERS.PAYER_POSTAL_CODE); String phone = getParameter(parameters, PayU.PARAMETERS.PAYER_PHONE); String expDate = getParameter(parameters, PayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE); String document = getParameter(parameters, PayU.PARAMETERS.CREDIT_CARD_DOCUMENT); Address address = new Address(); address.setLine1(line1 != null ? line1 : EMPTY); address.setLine2(line2 != null ? line2 : EMPTY); address.setLine3(line3 != null ? line3 : EMPTY); address.setCity(city != null ? city : EMPTY); address.setState(state); address.setCountry(country); address.setPostalCode(postalCode != null ? postalCode : EMPTY); address.setPhone(phone); PaymentPlanCreditCard request = new PaymentPlanCreditCard(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setToken(tokenId); request.setCustomerId(customerId); request.setNumber(creditCardNumber); request.setName(creditCardName); request.setType(type); request.setAddress(address); request.setDocument(document != null ? document : EMPTY); validateDateParameter(expDate, PayU.PARAMETERS.CREDIT_CARD_EXPIRATION_DATE, Constants.SECUNDARY_DATE_FORMAT); if (expDate != null) { String[] date = expDate.split("/"); request.setExpMonth(Integer.parseInt(date[1])); request.setExpYear(Integer.parseInt(date[0])); } return request; } /** * Builds a credit card request * * @param parameters * The parameters to be sent to the server * @return The complete credit card request * @throws InvalidParametersException */ public static PaymentPlanCreditCardListRequest buildCreditCardListRequest( Map<String, String> parameters) throws InvalidParametersException { PaymentPlanCreditCardListRequest request = new PaymentPlanCreditCardListRequest(); String customerId = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_ID); request.setCustomerId(customerId); return request; } /** * Builds a bank account request * * @param parameters The parameters to be sent to the server * @return The complete bank account request * @throws InvalidParametersException */ public static BankAccount buildBankAccountRequest(Map<String, String> parameters) throws InvalidParametersException { String bankAccountId = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_ID); String customerId = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_ID); String accountId = getParameter(parameters, PayU.PARAMETERS.ACCOUNT_ID); String customerName = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_CUSTOMER_NAME); String documentNumber = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER); String documentNumberType = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_DOCUMENT_NUMBER_TYPE); String bankName = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_BANK_NAME); String bankType = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_TYPE); String accountNumber = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_NUMBER); String state = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_STATE); String country = getParameter(parameters, PayU.PARAMETERS.COUNTRY); String accountDigit = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_ACCOUNT_DIGIT); String agencyDigit = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_AGENCY_DIGIT); String agencyNumber = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_AGENCY_NUMBER); BankAccount request = new BankAccount(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setId(bankAccountId); request.setAccountId(accountId); request.setCustomerId(customerId); request.setName(customerName); request.setDocumentNumber(documentNumber); request.setDocumentNumberType(documentNumberType); request.setBank(bankName); request.setType(bankType); request.setAccountNumber(accountNumber); request.setState(state); request.setCountry(country); request.setAgencyDigit(agencyDigit); request.setAgencyNumber(agencyNumber); request.setAccountDigit(accountDigit); return request; } /** * Builds a bank account list request * * @param parameters The parameters to be sent to the server * @return The complete bank account request * @throws InvalidParametersException */ public static BankAccountListRequest buildBankAccountListRequest(Map<String, String> parameters) throws InvalidParametersException { String customerId = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_ID); BankAccountListRequest request = new BankAccountListRequest(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setCustomerId(customerId); return request; } /** * Builds a subscription plan request * * @param parameters * The parameters to be sent to the server * @return The complete SubscriptionPlan request * @throws InvalidParametersException */ public static SubscriptionPlan buildSubscriptionPlanRequest( Map<String, String> parameters) throws InvalidParametersException { String planCode = getParameter(parameters, PayU.PARAMETERS.PLAN_CODE); Integer accountId = getIntegerParameter(parameters, PayU.PARAMETERS.ACCOUNT_ID); String planDescription = getParameter(parameters, PayU.PARAMETERS.PLAN_DESCRIPTION); String planInterval = getParameter(parameters, PayU.PARAMETERS.PLAN_INTERVAL); Integer planIntervalCount = getIntegerParameter(parameters, PayU.PARAMETERS.PLAN_INTERVAL_COUNT); Integer planTrialPeriodDays = getIntegerParameter(parameters, PayU.PARAMETERS.PLAN_TRIAL_PERIOD_DAYS); Currency planCurrency = getEnumValueParameter(Currency.class, parameters, PayU.PARAMETERS.PLAN_CURRENCY); BigDecimal planValue = getBigDecimalParameter(parameters, PayU.PARAMETERS.PLAN_VALUE); BigDecimal planTax = getBigDecimalParameter(parameters, PayU.PARAMETERS.PLAN_TAX); BigDecimal planTaxReturnBase = getBigDecimalParameter(parameters, PayU.PARAMETERS.PLAN_TAX_RETURN_BASE); Integer maxPaymentsAllowed = getIntegerParameter(parameters, PayU.PARAMETERS.PLAN_MAX_PAYMENTS); Integer planPaymentAttemptsDelay = getIntegerParameter(parameters, PayU.PARAMETERS.PLAN_ATTEMPTS_DELAY); Integer planPaymentMaxPendingPayments = getIntegerParameter(parameters, PayU.PARAMETERS.PLAN_MAX_PENDING_PAYMENTS); Integer planPaymentMaxPaymentAttemps = getIntegerParameter(parameters, PayU.PARAMETERS.PLAN_MAX_PAYMENT_ATTEMPTS); BigDecimal planAdditionalValue = getBigDecimalParameter(parameters, PayU.PARAMETERS.PLAN_ADDITIONAL_VALUE); SubscriptionPlan request = new SubscriptionPlan(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setAccountId(accountId); request.setPlanCode(planCode); request.setDescription(planDescription); request.setInterval(planInterval); request.setIntervalCount(planIntervalCount); request.setTrialDays(planTrialPeriodDays); request.setMaxPaymentsAllowed(maxPaymentsAllowed); request.setAdditionalValues(buildPlanAdditionalValues(planCurrency, planValue, planTax, planTaxReturnBase, planAdditionalValue)); request.setPaymentAttemptsDelay(planPaymentAttemptsDelay); request.setMaxPaymentAttempts(planPaymentMaxPaymentAttemps); request.setMaxPendingPayments(planPaymentMaxPendingPayments); return request; } /** * Builds a subscription plan list request * * @param parameters * The parameters to be sent to the server * @return The complete SubscriptionPlan request * @throws InvalidParametersException * @throws PayUException */ public static SubscriptionPlanListRequest buildSubscriptionPlanListRequest(Map<String, String> parameters) throws InvalidParametersException, PayUException { SubscriptionPlanListRequest request = new SubscriptionPlanListRequest(); request.setMap(parameters); RequestUtil.setAuthenticationCredentials(parameters, request); return request; } /** * Builds a Customer with a CreditCard request * * @param parameters * The parameters to be sent to the server * @return The complete Customer with a CreditCard request * @throws InvalidParametersException */ public static Customer buildCustomerWithCreditCardRequest( Map<String, String> parameters) throws InvalidParametersException { PaymentPlanCreditCard creditCard = buildCreditCardRequest(parameters); Customer request = buildCustomerRequest(parameters); RequestUtil.setAuthenticationCredentials(parameters, request); request.addCreditCard(creditCard); return request; } /** * Builds a Customer with a BankAccount request * * @param parameters * The parameters to be sent to the server * @return The complete Customer with a CreditCard request * @throws InvalidParametersException */ public static Customer buildCustomerWithBankAccountRequest( Map<String, String> parameters) throws InvalidParametersException { BankAccount bankAccount = buildBankAccountRequest(parameters); Customer request = buildCustomerRequest(parameters); RequestUtil.setAuthenticationCredentials(parameters, request); request.addBankAccount(bankAccount); return request; } /** * Builds a subscription request * * @param parameters * The parameters to be sent to the server * @return The complete subscription request * @throws InvalidParametersException */ public static Request buildSubscriptionRequest( Map<String, String> parameters) throws InvalidParametersException { // Subscription basic parameters Integer trialDays = getIntegerParameter(parameters, PayU.PARAMETERS.TRIAL_DAYS); Boolean immediatePayment = getBooleanParameter(parameters, PayU.PARAMETERS.IMMEDIATE_PAYMENT); Integer quantity = getIntegerParameter(parameters, PayU.PARAMETERS.QUANTITY); Integer installments = getIntegerParameter(parameters, PayU.PARAMETERS.INSTALLMENTS_NUMBER); String subscriptionId = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_ID); Boolean termsAndConditionsAcepted=getBooleanParameter(parameters, PayU.PARAMETERS.TERMS_AND_CONDITIONS_ACEPTED); List<RecurringBillItem> recurringBillItems = buildRecurringBillItemList(parameters); // Plan parameter SubscriptionPlan plan = buildSubscriptionPlanRequest(parameters); String planId = getParameter(parameters, PayU.PARAMETERS.PLAN_ID); plan.setId(planId); if(planId!=null){ plan.setAccountId(null); } // Customer parameter Customer customer = buildCustomerRequest(parameters); // CreditCard parameter if (CollectionsUtil.interceptMaps(parameters.keySet(), CREDIT_CARD_VALID_PARAMS)) { PaymentPlanCreditCard cc = buildCreditCardRequest(parameters); if (parameters.containsKey(PayU.PARAMETERS.TOKEN_ID)) { cc.setAddress(null); } cc.setCustomerId(null); customer.addCreditCard(cc); } // BankAccount parameter if (CollectionsUtil.interceptMaps(parameters.keySet(), BANK_ACCOUNT_VALID_PARAMS)) { BankAccount bankAccount=buildBankAccountRequest(parameters); bankAccount.setCustomerId(null); if(bankAccount.getId()!=null){ bankAccount.setAccountId(null); } customer.addBankAccount(bankAccount); } // Delivery address parameters Address deliveryAddress = new Address(); deliveryAddress.setLine1(getParameter(parameters, PayU.PARAMETERS.DELIVERY_ADDRESS_1)); deliveryAddress.setLine2(getParameter(parameters, PayU.PARAMETERS.DELIVERY_ADDRESS_2)); deliveryAddress.setLine3(getParameter(parameters, PayU.PARAMETERS.DELIVERY_ADDRESS_3)); deliveryAddress.setCity(getParameter(parameters, PayU.PARAMETERS.DELIVERY_CITY)); deliveryAddress.setState(getParameter(parameters, PayU.PARAMETERS.DELIVERY_STATE)); deliveryAddress.setCountry(getParameter(parameters, PayU.PARAMETERS.DELIVERY_COUNTRY)); deliveryAddress.setPostalCode(getParameter(parameters, PayU.PARAMETERS.DELIVERY_POSTAL_CODE)); deliveryAddress.setPhone(getParameter(parameters, PayU.PARAMETERS.DELIVERY_PHONE)); // Subscription notifyUrl, sourceReference, extra1 and extra 2 parameters String notifyUrl = getParameter(parameters, PayU.PARAMETERS.NOTIFY_URL); String sourceReference = getParameter(parameters, PayU.PARAMETERS.SOURCE_REFERENCE); String extra1 = getParameter(parameters, PayU.PARAMETERS.EXTRA1); String extra2 = getParameter(parameters, PayU.PARAMETERS.EXTRA2); // Subscription sourceId and description Long sourceId = getLongParameter(parameters, PayU.PARAMETERS.SOURCE_ID); String description = getParameter(parameters, PayU.PARAMETERS.DESCRIPTION); SubscriptionCreationSource creationSource = getEnumValueParameter(SubscriptionCreationSource.class, parameters, PayU.PARAMETERS.CREATION_SOURCE); // Migrated subscriptions parameters String sourceBuyerIP = getParameter(parameters, PayU.PARAMETERS.SOURCE_BUYER_IP); Integer sourceNumberOfPayments = getIntegerParameter(parameters, PayU.PARAMETERS.SOURCE_NUMBER_OF_PAYMENTS); Integer sourceNextPaymentNumber = getIntegerParameter(parameters, PayU.PARAMETERS.SOURCE_NEXT_PAYMENT_NUMBER); // Subscription basic parameters Subscription request = new Subscription(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setTrialDays(trialDays); request.setImmediatePayment(immediatePayment); request.setQuantity(quantity); request.setInstallments(installments); request.setTermsAndConditionsAcepted(termsAndConditionsAcepted); request.setDeliveryAddress(deliveryAddress); request.setRecurringBillItems(recurringBillItems); request.setNotifyUrl(notifyUrl); request.setSourceReference(sourceReference); request.setExtra1(extra1); request.setExtra2(extra2); request.setSourceId(sourceId); request.setDescription(description); request.setSourceBuyerIp(sourceBuyerIP); request.setSourceNumberOfPayments(sourceNumberOfPayments); request.setSourceNextPaymentNumber(sourceNextPaymentNumber); if (creationSource != null) { request.setCreationSource(creationSource.name()); } // Subscription complex parameters (customer and plan) request.setPlan(plan); request.setCustomer(customer); request.setId(subscriptionId); return request; } /** * Builds a recurring billing item request without authentication * * @param parameters * The parameters to be sent to the server * @return List<RecurringBillItem> The RecurringBillItems list * @throws InvalidParametersException */ private static List<RecurringBillItem> buildRecurringBillItemList(Map<String, String> parameters) throws InvalidParametersException { if (parameters.containsKey(PayU.PARAMETERS.SUBSCRIPTION_EXTRA_CHARGES_DESCRIPTION)) { String description = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_EXTRA_CHARGES_DESCRIPTION); BigDecimal value = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_VALUE); BigDecimal taxValue = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_TAX); BigDecimal taxReturnBase = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_TAX_RETURN_BASE); Currency currency = getEnumValueParameter(Currency.class, parameters, PayU.PARAMETERS.CURRENCY); RecurringBillItem recurringBillItem = new RecurringBillItem(); recurringBillItem.setDescription(description); List<AdditionalValue> additionalValues = buildItemAdditionalValues(currency, value, taxValue, taxReturnBase); recurringBillItem.setAdditionalValues(additionalValues); return Arrays.asList(recurringBillItem); } return Collections.emptyList(); } /** * Builds an update subscription request * * @param parameters * The parameters to be sent to the server * @return The complete subscription request * @throws InvalidParametersException */ public static Request buildSubscriptionUpdateRequest( Map<String, String> parameters) throws InvalidParametersException { String newCreditCardToken = getParameter(parameters, PayU.PARAMETERS.TOKEN_ID); String newBankAccountId = getParameter(parameters, PayU.PARAMETERS.BANK_ACCOUNT_ID); String subscriptionId = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_ID); Subscription request = new Subscription(); // Set the delivery address fields Address deliveryAddress = new Address(); deliveryAddress.setLine1(getParameter(parameters,PayU.PARAMETERS.DELIVERY_ADDRESS_1)); deliveryAddress.setLine2(getParameter(parameters,PayU.PARAMETERS.DELIVERY_ADDRESS_2)); deliveryAddress.setLine3(getParameter(parameters,PayU.PARAMETERS.DELIVERY_ADDRESS_3)); deliveryAddress.setCity(getParameter(parameters,PayU.PARAMETERS.DELIVERY_CITY)); deliveryAddress.setState(getParameter(parameters,PayU.PARAMETERS.DELIVERY_STATE)); deliveryAddress.setCountry(getParameter(parameters,PayU.PARAMETERS.DELIVERY_COUNTRY)); deliveryAddress.setPostalCode(getParameter(parameters,PayU.PARAMETERS.DELIVERY_POSTAL_CODE)); deliveryAddress.setPhone(getParameter(parameters,PayU.PARAMETERS.DELIVERY_PHONE)); RequestUtil.setAuthenticationCredentials(parameters, request); request.setUrlId(subscriptionId); request.setCreditCardToken(newCreditCardToken); request.setBankAccountId(newBankAccountId); request.setDeliveryAddress(deliveryAddress); return request; } /** * Builds a recurring bill item request * * @param parameters * The parameters to be sent to the server * @return The complete recurring bill item request * @throws InvalidParametersException */ public static Request buildRecurringBillItemRequest( Map<String, String> parameters) throws InvalidParametersException { // Recurring bill item basic parameters BigDecimal value = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_VALUE); Currency currency = getEnumValueParameter(Currency.class, parameters, PayU.PARAMETERS.CURRENCY); String description = getParameter(parameters, PayU.PARAMETERS.DESCRIPTION); BigDecimal taxValue = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_TAX); BigDecimal taxReturnBase = getBigDecimalParameter(parameters, PayU.PARAMETERS.ITEM_TAX_RETURN_BASE); String recurringBillItemId = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_ITEM_ID); String recurringItemId = getParameter(parameters, PayU.PARAMETERS.RECURRING_ITEM_ID); String subscriptionId = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_ID); // Subscription basic parameters RecurringBillItem request = new RecurringBillItem(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setId(recurringBillItemId); request.setDescription(description); request.setSubscriptionId(subscriptionId); request.setRecurringBillId(recurringItemId); List<AdditionalValue> additionalValues = buildItemAdditionalValues( currency, value, taxValue, taxReturnBase); request.setAdditionalValues(additionalValues); return request; } /** * Builds a recurring bill item request * * @param parameters * The parameters to be sent to the server * @return The complete recurring bill item request * @throws InvalidParametersException * @throws PayUException */ public static Request buildRecurringBillItemListRequest( Map<String, String> parameters) throws InvalidParametersException, PayUException { String description = getParameter(parameters, PayU.PARAMETERS.DESCRIPTION); String subscriptionId = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_ID); Map<String, String> parametersRequest=new HashMap<String, String>(); parametersRequest.put(PayU.PARAMETERS.SUBSCRIPTION_ID, subscriptionId); parametersRequest.put(PayU.PARAMETERS.DESCRIPTION, description); RecurringBillItemListRequest request = new RecurringBillItemListRequest(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setMap(parametersRequest); return request; } /** * Builds a recurring bill request * * @param parameters The parameters to be sent to the server * @return The complete recurring bill request * @throws InvalidParametersException */ public static Request buildRecurringBillRequest( Map<String, String> parameters) throws InvalidParametersException { // Recurring bill basic parameters String recurringBillId = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_ID); RecurringBill request = new RecurringBill(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setId(recurringBillId); return request; } /** * Builds a recurring bill list request * * @param parameters The parameters to be sent to the server * @return The complete recurring bill list request * @throws InvalidParametersException * @throws PayUException */ public static Request buildRecurringBillListRequest( Map<String, String> parameters) throws InvalidParametersException, PayUException { String startDate = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_DATE_BEGIN); String endDate = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_DATE_FINAL); // Validates the PaymentMethodType value, if any. getEnumValueParameter( PaymentMethodType.class, parameters, PayU.PARAMETERS.RECURRING_BILL_PAYMENT_METHOD_TYPE); validateDateParameter( startDate, PayU.PARAMETERS.RECURRING_BILL_DATE_BEGIN, Constants.DEFAULT_DATE_WITHOUT_HOUR_FORMAT); validateDateParameter( endDate, PayU.PARAMETERS.RECURRING_BILL_DATE_FINAL, Constants.DEFAULT_DATE_WITHOUT_HOUR_FORMAT); RecurringBillListRequest request = new RecurringBillListRequest(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setMap(parameters); return request; } /** * Builds a subscription request * * @param parameters * The parameters to be sent to the server * @return The complete subscription request * @throws InvalidParametersException * @throws PayUException */ public static Request buildSubscriptionListRequest( Map<String, String> parameters) throws InvalidParametersException, PayUException { // Subscription parameters String customerId = getParameter(parameters, PayU.PARAMETERS.CUSTOMER_ID); String planCode = getParameter(parameters, PayU.PARAMETERS.PLAN_CODE); String planId = getParameter(parameters, PayU.PARAMETERS.PLAN_ID); String state = getParameter(parameters, PayU.PARAMETERS.STATE); String subscriptionId = getParameter(parameters, PayU.PARAMETERS.SUBSCRIPTION_ID); String accountId=getParameter(parameters, PayU.PARAMETERS.ACCOUNT_ID); String limit=getParameter(parameters, PayU.PARAMETERS.LIMIT); String offset=getParameter(parameters, PayU.PARAMETERS.OFFSET); String sourceId = getParameter(parameters, PayU.PARAMETERS.SOURCE_ID); Map<String, String> paramsFilter=new HashMap<String, String>(); paramsFilter.put(PayU.PARAMETERS.CUSTOMER_ID, customerId); paramsFilter.put(PayU.PARAMETERS.PLAN_CODE, planCode); paramsFilter.put(PayU.PARAMETERS.PLAN_ID, planId); paramsFilter.put(PayU.PARAMETERS.STATE, state); paramsFilter.put(PayU.PARAMETERS.SUBSCRIPTION_ID,subscriptionId); paramsFilter.put(PayU.PARAMETERS.ACCOUNT_ID, accountId); paramsFilter.put(PayU.PARAMETERS.LIMIT, limit); paramsFilter.put(PayU.PARAMETERS.OFFSET, offset); paramsFilter.put(PayU.PARAMETERS.SOURCE_ID, sourceId); SubscriptionsListRequest request = new SubscriptionsListRequest(); request.setMap(paramsFilter); RequestUtil.setAuthenticationCredentials(parameters, request); return request; } /** * Builds a recurring bill payment retry request * * @param parameters The parameters to be sent to the server * @return The complete recurring bill payment retry request * @throws InvalidParametersException * @throws PayUException */ public static Request buildRecurringBillPaymentRetryRequest( Map<String, String> parameters) throws InvalidParametersException, PayUException { String recurringBillId = getParameter(parameters, PayU.PARAMETERS.RECURRING_BILL_ID); RecurringBillPaymentRetry request = new RecurringBillPaymentRetry(); RequestUtil.setAuthenticationCredentials(parameters, request); request.setRecurringBillId(recurringBillId); return request; } }
package cz.metacentrum.perun.ldapc.model.impl; import static org.springframework.ldap.query.LdapQueryBuilder.query; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.Name; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.support.LdapNameBuilder; import cz.metacentrum.perun.core.api.Facility; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.Vo; import cz.metacentrum.perun.core.api.VosManager; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.ldapc.model.PerunAttribute; import cz.metacentrum.perun.ldapc.model.PerunFacility; import cz.metacentrum.perun.ldapc.model.PerunGroup; import cz.metacentrum.perun.ldapc.model.PerunUser; import cz.metacentrum.perun.ldapc.model.PerunVO; public class PerunGroupImpl extends AbstractPerunEntry<Group> implements PerunGroup { private final static Logger log = LoggerFactory.getLogger(PerunGroupImpl.class); @Autowired private PerunVO vo; @Autowired @Lazy private PerunUser user; @Autowired private PerunVO perunVO; @Autowired private PerunFacility perunFacility; @Override protected List<String> getDefaultUpdatableAttributes() { return Arrays.asList( PerunAttribute.PerunAttributeNames.ldapAttrCommonName, PerunAttribute.PerunAttributeNames.ldapAttrPerunUniqueGroupName, PerunAttribute.PerunAttributeNames.ldapAttrDescription); } @Override protected List<PerunAttribute<Group>> getDefaultAttributeDescriptions() { return Arrays.asList( new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrCommonName, PerunAttribute.REQUIRED, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> group.getName() ), new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrPerunGroupId, PerunAttribute.REQUIRED, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> String.valueOf(group.getId()) ), new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrPerunUniqueGroupName, PerunAttributeDesc.REQUIRED, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> vo.getVoShortName(group.getVoId()) + ":" + group.getName() ), new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrPerunVoId, PerunAttributeDesc.REQUIRED, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> String.valueOf(group.getVoId()) ), new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrDescription, PerunAttributeDesc.OPTIONAL, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> group.getDescription() ), new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrPerunParentGroup, PerunAttributeDesc.OPTIONAL, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> group.getParentGroupId() == null ? null : this.addBaseDN(this.getEntryDN(String.valueOf(group.getVoId()), String.valueOf(group.getParentGroupId()))).toString() // PerunAttributeNames.ldapAttrPerunGroupId + "=" + group.getParentGroupId().toString() + "," + PerunAttributeNames.ldapAttrPerunVoId + "=" + group.getVoId() + "," + ldapProperties.getLdapBase() ), new PerunAttributeDesc<>( PerunAttribute.PerunAttributeNames.ldapAttrPerunParentGroupId, PerunAttributeDesc.OPTIONAL, (PerunAttribute.SingleValueExtractor<Group>)(group, attrs) -> group.getParentGroupId() == null ? null : group.getParentGroupId().toString() ) ); } public void addGroup(Group group) throws InternalErrorException { addEntry(group); } public void addGroupAsSubGroup(Group group, Group parentGroup) throws InternalErrorException { //This method has the same implementation like 'addGroup' addGroup(group); } public void removeGroup(Group group) throws InternalErrorException { Name groupDN = buildDN(group); Name fullGroupDN = this.addBaseDN(groupDN); DirContextOperations groupEntry = findByDN(groupDN); String[] uniqueMembers = groupEntry.getStringAttributes(PerunAttribute.PerunAttributeNames.ldapAttrUniqueMember); if(uniqueMembers != null) for(String memberDN: uniqueMembers) { DirContextOperations memberEntry = user.findByDN(LdapNameBuilder.newInstance(memberDN).build()); memberEntry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrMemberOf, fullGroupDN.toString()); ldapTemplate.modifyAttributes(memberEntry); } deleteEntry(group); } @Override public void updateGroup(Group group) throws InternalErrorException { modifyEntry(group); } public void addMemberToGroup(Member member, Group group) throws InternalErrorException { //Add member to group Name groupDN = buildDN(group); DirContextOperations groupEntry = findByDN(groupDN); Name memberDN = user.getEntryDN(String.valueOf(member.getUserId())); Name fullMemberDN = addBaseDN(memberDN); if(isMember(groupEntry, fullMemberDN)) return; groupEntry.addAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrUniqueMember, fullMemberDN.toString()); ldapTemplate.modifyAttributes(groupEntry); //Add member to vo if this group is membersGroup if(group.getName().equals(VosManager.MEMBERS_GROUP) && group.getParentGroupId() == null) { //Add info to vo vo.addMemberToVO(group.getVoId(), member); } //Add group info to member // user->add('memberOf' => groupDN) DirContextOperations userEntry = findByDN(memberDN); userEntry.addAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrMemberOf, addBaseDN(groupDN).toString()); ldapTemplate.modifyAttributes(userEntry); } public void removeMemberFromGroup(Member member, Group group) throws InternalErrorException { //Remove member from group Name groupDN = buildDN(group); DirContextOperations groupEntry = findByDN(groupDN); Name memberDN = user.getEntryDN(String.valueOf(member.getUserId())); Name fullMemberDN = addBaseDN(memberDN); if(!isMember(groupEntry, fullMemberDN)) return; groupEntry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrUniqueMember, fullMemberDN.toString()); ldapTemplate.modifyAttributes(groupEntry); //Remove member from vo if this group is membersGroup if(group.getName().equals(VosManager.MEMBERS_GROUP) && group.getParentGroupId() == null) { //Remove info from vo vo.removeMemberFromVO(group.getVoId(), member); } //Remove group info from member DirContextOperations userEntry = findByDN(memberDN); userEntry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrMemberOf, addBaseDN(groupDN).toString()); ldapTemplate.modifyAttributes(userEntry); } @Override public void addAsVoAdmin(Group group, Vo vo) { DirContextOperations entry = findByDN(buildDN(group)); Name voDN = addBaseDN(perunVO.getEntryDN(String.valueOf(vo.getId()))); entry.addAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfVo, voDN.toString()); ldapTemplate.modifyAttributes(entry); } @Override public void removeFromVoAdmins(Group group, Vo vo) { DirContextOperations entry = findByDN(buildDN(group)); Name voDN = addBaseDN(perunVO.getEntryDN(String.valueOf(vo.getId()))); entry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfVo, voDN.toString()); ldapTemplate.modifyAttributes(entry); } @Override public void addAsGroupAdmin(Group group, Group group2) { DirContextOperations entry = findByDN(buildDN(group)); Name groupDN = addBaseDN(getEntryDN(String.valueOf(group2.getVoId()), String.valueOf(group2.getId()))); entry.addAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfGroup, groupDN.toString()); ldapTemplate.modifyAttributes(entry); } @Override public void removeFromGroupAdmins(Group group, Group group2) { DirContextOperations entry = findByDN(buildDN(group)); Name groupDN = addBaseDN(getEntryDN(String.valueOf(group2.getVoId()), String.valueOf(group2.getId()))); entry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfGroup, groupDN.toString()); ldapTemplate.modifyAttributes(entry); } @Override public void addAsFacilityAdmin(Group group, Facility facility) { DirContextOperations entry = findByDN(buildDN(group)); Name facilityDN = addBaseDN(perunFacility.getEntryDN(String.valueOf(facility.getId()))); entry.addAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfFacility, facilityDN.toString()); ldapTemplate.modifyAttributes(entry); } @Override public void removeFromFacilityAdmins(Group group, Facility facility) { DirContextOperations entry = findByDN(buildDN(group)); Name facilityDN = addBaseDN(perunFacility.getEntryDN(String.valueOf(facility.getId()))); entry.removeAttributeValue(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfFacility, facilityDN.toString()); ldapTemplate.modifyAttributes(entry); } protected void doSynchronizeMembers(DirContextOperations groupEntry, List<Member> members) { List<Name> memberList = new ArrayList<Name>(members.size()); for (Member member: members) { memberList.add(addBaseDN(user.getEntryDN(String.valueOf(member.getUserId())))); } groupEntry.setAttributeValues(PerunAttribute.PerunAttributeNames.ldapAttrUniqueMember, memberList.stream().map( name -> name.toString() ).toArray(String[]::new)); } protected void doSynchronizeResources(DirContextOperations groupEntry, List<Resource> resources) { groupEntry.setAttributeValues(PerunAttribute.PerunAttributeNames.ldapAttrAssignedToResourceId, resources.stream().map( resource -> String.valueOf(resource.getId())).toArray(String[]::new)); } private void doSynchronizeAdminRoles(DirContextOperations entry, List<Group> admin_groups, List<Vo> admin_vos, List<Facility> admin_facilities) { entry.setAttributeValues(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfGroup, admin_groups.stream() .map(group -> addBaseDN(getEntryDN(String.valueOf(group.getVoId()), String.valueOf(group.getId())))) .toArray(Name[]::new) ); entry.setAttributeValues(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfVo, admin_vos.stream() .map(vo -> addBaseDN(perunVO.getEntryDN(String.valueOf(vo.getId())))) .toArray(Name[]::new) ); entry.setAttributeValues(PerunAttribute.PerunAttributeNames.ldapAttrAdminOfFacility, admin_facilities.stream() .map(facility -> addBaseDN(perunFacility.getEntryDN(String.valueOf(facility.getId())))) .toArray(Name[]::new) ); } @Override public void synchronizeGroup(Group group, List<Member> members, List<Resource> resources, List<Group> admin_groups, List<Vo> admin_vos, List<Facility> admin_facilities) throws InternalErrorException { SyncOperation syncOp = beginSynchronizeEntry(group); doSynchronizeMembers(syncOp.getEntry(), members); doSynchronizeResources(syncOp.getEntry(), resources); doSynchronizeAdminRoles(syncOp.getEntry(), admin_groups, admin_vos, admin_facilities); commitSyncOperation(syncOp); } @Override public void synchronizeMembers(Group group, List<Member> members) { DirContextOperations groupEntry = findByDN(buildDN(group)); doSynchronizeMembers(groupEntry, members); ldapTemplate.modifyAttributes(groupEntry); // user attributes are set when synchronizing users } @Override public void synchronizeResources(Group group, List<Resource> resources) { DirContextOperations groupEntry = findByDN(buildDN(group)); doSynchronizeResources(groupEntry, resources); ldapTemplate.modifyAttributes(groupEntry); } @Override public void synchronizeAdminRoles(Group group, List<Group> admin_groups, List<Vo> admin_vos, List<Facility> admin_facilities) { DirContextOperations groupEntry = findByDN(buildDN(group)); doSynchronizeAdminRoles(groupEntry, admin_groups, admin_vos, admin_facilities); ldapTemplate.modifyAttributes(groupEntry); } public boolean isMember(Member member, Group group) { DirContextOperations groupEntry = findByDN(buildDN(group)); Name userDN = addBaseDN(user.getEntryDN(String.valueOf(member.getUserId()))); return isMember(groupEntry, userDN); } @Deprecated public List<String> getAllUniqueMembersInGroup(int groupId, int voId) { Pattern userIdPattern = Pattern.compile("[0-9]+"); List<String> uniqueMembers = new ArrayList<String>(); DirContextOperations groupEntry = findById(String.valueOf(groupId), String.valueOf(voId)); String[] uniqueGroupInformation = groupEntry.getStringAttributes(PerunAttribute.PerunAttributeNames.ldapAttrUniqueMember); if(uniqueGroupInformation != null) { for(String s: uniqueGroupInformation) { Matcher userIdMatcher = userIdPattern.matcher(s); if(userIdMatcher.find()) uniqueMembers.add(s.substring(userIdMatcher.start(), userIdMatcher.end())); } } return uniqueMembers; } @Override protected void mapToContext(Group group, DirContextOperations context) throws InternalErrorException { context.setAttributeValue("objectclass", PerunAttribute.PerunAttributeNames.objectClassPerunGroup); mapToContext(group, context, getAttributeDescriptions()); } @Override protected Name buildDN(Group group) { return getEntryDN(String.valueOf(group.getVoId()), String.valueOf(group.getId())); } /** * Get Group DN using VoId and GroupId. * * @param voId vo id * @param groupId group id * @return DN in String */ @Override public Name getEntryDN(String ...id) { return LdapNameBuilder.newInstance() .add(PerunAttribute.PerunAttributeNames.ldapAttrPerunVoId, id[0]) .add(PerunAttribute.PerunAttributeNames.ldapAttrPerunGroupId, id[1]) .build(); } private boolean isMember(DirContextOperations groupEntry, Name userDN) { String[] memberOfInformation = groupEntry.getStringAttributes(PerunAttribute.PerunAttributeNames.ldapAttrUniqueMember); if(memberOfInformation != null) { for(String s: memberOfInformation) { Name memberDN = LdapNameBuilder.newInstance(s).build(); if(memberDN.compareTo(userDN) == 0) // TODO should probably cross-check the user.memberOf attribute return true; } } return false; } @Override public List<Name> listEntries() throws InternalErrorException { return ldapTemplate.search(query(). where("objectclass").is(PerunAttribute.PerunAttributeNames.objectClassPerunGroup), getNameMapper()); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.repo.endpoints; import org.json.simple.JSONObject; import org.pentaho.di.core.exception.KettleAuthException; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.ui.repo.controller.RepositoryConnectController; import org.pentaho.di.ui.repo.model.ErrorModel; import org.pentaho.di.ui.repo.model.LoginModel; import org.pentaho.di.ui.repo.model.RepositoryModel; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; /** * Created by bmorrise on 10/20/16. */ public class RepositoryEndpoint { private static Class<?> PKG = RepositoryEndpoint.class; public static final String ERROR_401 = "401"; private RepositoryConnectController controller; public RepositoryEndpoint( RepositoryConnectController controller ) { this.controller = controller; } @GET @Path( "/help" ) public Response help() { return Response.ok( controller.help() ).build(); } @GET @Path( "/user" ) public Response user() { return Response.ok( controller.getCurrentUser() ).build(); } @GET @Path( "/connection/create" ) public Response createConnection() { return Response.ok( controller.createConnection() ).build(); } @POST @Path( "/connection/edit" ) public Response editConnection( String database ) { return Response.ok( controller.editDatabaseConnection( database ) ).build(); } @POST @Path( "/connection/delete" ) public Response deleteConnection( String database ) { return Response.ok( controller.deleteDatabaseConnection( database ) ).build(); } @POST @Path( "/login" ) @Consumes( { APPLICATION_JSON } ) public Response login( LoginModel loginModel ) { try { if ( controller.isRelogin() ) { controller .reconnectToRepository( loginModel.getRepositoryName(), loginModel.getUsername(), loginModel.getPassword() ); } else { controller .connectToRepository( loginModel.getRepositoryName(), loginModel.getUsername(), loginModel.getPassword() ); } return Response.ok().build(); } catch ( Exception e ) { if ( e.getMessage().contains( ERROR_401 ) || e instanceof KettleAuthException ) { return Response.serverError() .entity( new ErrorModel( BaseMessages.getString( PKG, "RepositoryConnection.Error.InvalidCredentials" ) ) ) .build(); } else { return Response.serverError() .entity( new ErrorModel( BaseMessages.getString( PKG, "RepositoryConnection.Error.InvalidServer" ) ) ) .build(); } } } @POST @Path( "/add" ) @Consumes( { APPLICATION_JSON } ) public Response add( RepositoryModel model ) { if ( controller.createRepository( model.getId(), controller.modelToMap( model ) ) ) { return Response.ok().build(); } else { return Response.serverError() .entity( new ErrorModel( BaseMessages.getString( PKG, "RepositoryConnection.Error.InvalidServer" ) ) ) .build(); } } @POST @Path( "/update" ) @Consumes( { APPLICATION_JSON } ) public Response update( RepositoryModel model ) { if ( controller.updateRepository( model.getId(), controller.modelToMap( model ) ) ) { return Response.ok().build(); } else { return Response.serverError() .entity( new ErrorModel( BaseMessages.getString( PKG, "RepositoryConnection.Error.InvalidServer" ) ) ) .build(); } } @GET @Path( "/list" ) @Produces( { APPLICATION_JSON } ) public Response repositories() { return Response.ok( controller.getRepositories() ).build(); } @GET @Path( "/find/{repo : .+}" ) @Produces( { APPLICATION_JSON } ) public Response repository( @PathParam( "repo" ) String repo ) { return Response.ok( controller.getRepository( repo ) ).build(); } @POST @Path( "/default/set" ) @Consumes( { APPLICATION_JSON } ) public Response setDefault( RepositoryModel model ) { return Response.ok( controller.setDefaultRepository( model.getDisplayName() ) ).build(); } @POST @Path( "/default/clear" ) @Consumes( { APPLICATION_JSON } ) public Response setDefault() { return Response.ok( controller.clearDefaultRepository() ).build(); } @POST @Path( "/duplicate" ) @Consumes( { APPLICATION_JSON } ) public Response duplicate( RepositoryModel model ) { return Response.ok( controller.checkDuplicate( model.getDisplayName() ) ).build(); } @POST @Path( "/remove" ) @Consumes( { APPLICATION_JSON } ) public Response delete( RepositoryModel model ) { return Response.ok( controller.deleteRepository( model.getDisplayName() ) ).build(); } @GET @Path( "/types" ) @Consumes( { APPLICATION_JSON } ) public Response types() { return Response.ok( controller.getPlugins() ).build(); } @GET @Path( "/databases" ) @Produces( { APPLICATION_JSON } ) public Response databases() { return Response.ok( controller.getDatabases() ).build(); } @GET @Path( "/browse" ) @Produces( { APPLICATION_JSON } ) public Response browse() { String path = "/"; try { path = controller.browse(); } catch ( Exception e ) { // Do nothing } JSONObject jsonObject = new JSONObject(); jsonObject.put( "path", path ); return Response.ok( jsonObject.toJSONString() ).build(); } }
package pl.allegro.tech.build.axion.release.domain.logging; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; public class DefaultReleaseLoggerFactory implements ReleaseLoggerFactory { @Override public ReleaseLogger logger(Class<?> clazz) { return new Slf4jReleaseLogger(LoggerFactory.getLogger(clazz)); } @Override public ReleaseLogger logger(String name) { return new Slf4jReleaseLogger(LoggerFactory.getLogger(name)); } private static class Slf4jReleaseLogger implements ReleaseLogger, Logger { private final Logger logger; public Slf4jReleaseLogger(Logger logger) { this.logger = logger; } @Override public void quiet(String message) { logger.info(message); } @Override public String getName() { return logger.getName(); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public void trace(String s) { logger.trace(s); } @Override public void trace(String s, Object o) { logger.trace(s, o); } @Override public void trace(String s, Object o, Object o1) { logger.trace(s, o, o1); } @Override public void trace(String s, Object... objects) { logger.trace(s, objects); } @Override public void trace(String s, Throwable throwable) { logger.trace(s, throwable); } @Override public boolean isTraceEnabled(Marker marker) { return logger.isTraceEnabled(marker); } @Override public void trace(Marker marker, String s) { logger.trace(marker, s); } @Override public void trace(Marker marker, String s, Object o) { logger.trace(marker, s, o); } @Override public void trace(Marker marker, String s, Object o, Object o1) { logger.trace(marker, s, o, o1); } @Override public void trace(Marker marker, String s, Object... objects) { logger.trace(marker, s, objects); } @Override public void trace(Marker marker, String s, Throwable throwable) { logger.trace(marker, s, throwable); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public void debug(String s) { logger.debug(s); } @Override public void debug(String s, Object o) { logger.debug(s, o); } @Override public void debug(String s, Object o, Object o1) { logger.debug(s, o, o1); } @Override public void debug(String s, Object... objects) { logger.debug(s, objects); } @Override public void debug(String s, Throwable throwable) { logger.debug(s, throwable); } @Override public boolean isDebugEnabled(Marker marker) { return logger.isDebugEnabled(marker); } @Override public void debug(Marker marker, String s) { logger.debug(marker, s); } @Override public void debug(Marker marker, String s, Object o) { logger.debug(marker, s, o); } @Override public void debug(Marker marker, String s, Object o, Object o1) { logger.debug(marker, s, o, o1); } @Override public void debug(Marker marker, String s, Object... objects) { logger.debug(marker, s, objects); } @Override public void debug(Marker marker, String s, Throwable throwable) { logger.debug(marker, s, throwable); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public void info(String s) { logger.info(s); } @Override public void info(String s, Object o) { logger.info(s, o); } @Override public void info(String s, Object o, Object o1) { logger.info(s, o, o1); } @Override public void info(String s, Object... objects) { logger.info(s, objects); } @Override public void info(String s, Throwable throwable) { logger.info(s, throwable); } @Override public boolean isInfoEnabled(Marker marker) { return logger.isInfoEnabled(marker); } @Override public void info(Marker marker, String s) { logger.info(marker, s); } @Override public void info(Marker marker, String s, Object o) { logger.info(marker, s, o); } @Override public void info(Marker marker, String s, Object o, Object o1) { logger.info(marker, s, o, o1); } @Override public void info(Marker marker, String s, Object... objects) { logger.info(marker, s, objects); } @Override public void info(Marker marker, String s, Throwable throwable) { logger.info(marker, s, throwable); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public void warn(String s) { logger.warn(s); } @Override public void warn(String s, Object o) { logger.warn(s, o); } @Override public void warn(String s, Object... objects) { logger.warn(s, objects); } @Override public void warn(String s, Object o, Object o1) { logger.warn(s, o, o1); } @Override public void warn(String s, Throwable throwable) { logger.warn(s, throwable); } @Override public boolean isWarnEnabled(Marker marker) { return logger.isWarnEnabled(marker); } @Override public void warn(Marker marker, String s) { logger.warn(marker, s); } @Override public void warn(Marker marker, String s, Object o) { logger.warn(marker, s, o); } @Override public void warn(Marker marker, String s, Object o, Object o1) { logger.warn(marker, s, o, o1); } @Override public void warn(Marker marker, String s, Object... objects) { logger.warn(marker, s, objects); } @Override public void warn(Marker marker, String s, Throwable throwable) { logger.warn(marker, s, throwable); } @Override public boolean isErrorEnabled() { return logger.isErrorEnabled(); } @Override public void error(String s) { logger.error(s); } @Override public void error(String s, Object o) { logger.error(s, o); } @Override public void error(String s, Object o, Object o1) { logger.error(s, o, o1); } @Override public void error(String s, Object... objects) { logger.error(s, objects); } @Override public void error(String s, Throwable throwable) { logger.error(s, throwable); } @Override public boolean isErrorEnabled(Marker marker) { return logger.isErrorEnabled(marker); } @Override public void error(Marker marker, String s) { logger.error(marker, s); } @Override public void error(Marker marker, String s, Object o) { logger.error(marker, s, o); } @Override public void error(Marker marker, String s, Object o, Object o1) { logger.error(marker, s, o, o1); } @Override public void error(Marker marker, String s, Object... objects) { logger.error(marker, s, objects); } @Override public void error(Marker marker, String s, Throwable throwable) { logger.error(marker, s, throwable); } } }
/* * Copyright (c) 2016 Henry Addo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.addhen.android.raiburari.processor; import com.addhen.android.raiburari.annotations.Transform; import com.addhen.android.raiburari.annotations.TransformEntity; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.MirroredTypeException; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * @author Henry Addo */ public class TransformEntityAnnotatedClass { private TypeElement mTypeElement; private String mCanonicalClassName; private boolean mIsInjectable; private Map<String, TransformAnnotatedField> transformAnnotatedElementsMap = new HashMap<>(); public TransformEntityAnnotatedClass(TypeElement typeElement) throws ProcessingException { mTypeElement = typeElement; // Visibility if (typeElement.getModifiers().contains(Modifier.PRIVATE)) { throw new ProcessingException(typeElement, "Private classes can not contain @%s annotated fields", TransformEntity.class.getSimpleName()); } // No abstract if (typeElement.getModifiers().contains(Modifier.ABSTRACT)) { throw new ProcessingException(typeElement, "The class %s is abstract. You can't annotate abstract classes with @%", typeElement.getQualifiedName().toString(), TransformEntity.class.getSimpleName()); } // Constructor check boolean isConstructorFound = false; for (Element element : typeElement.getEnclosedElements()) { if (element.getKind() == ElementKind.CONSTRUCTOR) { ExecutableElement constructor = (ExecutableElement) element; for (Modifier modifier : constructor.getModifiers()) { if (constructor.getParameters().size() == 0 && constructor.getModifiers() .contains(Modifier.PUBLIC)) { isConstructorFound = true; break; } } } } if (!isConstructorFound) { throw new ProcessingException(typeElement, "Class %s has %s annotated fields (incl. super class) and therefore" + " must provide a public empty constructor (zero parameters)", typeElement.getQualifiedName().toString(), TransformEntity.class.getSimpleName()); } TransformEntity annotation = typeElement.getAnnotation(TransformEntity.class); // Get the full QualifiedTypeName try { Class<?> clazz = annotation.to(); mCanonicalClassName = clazz.getCanonicalName(); } catch (MirroredTypeException e) { DeclaredType classTypeMirror = (DeclaredType) e.getTypeMirror(); TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement(); mCanonicalClassName = classTypeElement.getQualifiedName().toString(); } // Get inject value mIsInjectable = annotation.isInjectable(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransformEntityAnnotatedClass that = (TransformEntityAnnotatedClass) o; return mTypeElement.equals(that.mTypeElement); } @Override public int hashCode() { return mTypeElement.hashCode(); } /** * Scans the class for annotated fields. Also scans inheritance hierarchy. */ public void scanForAnnotatedFields(Types typeUtils, Elements elementUtils) throws ProcessingException { // Scan inheritance hierarchy recursively to find all annotated fields TypeElement currentClass = mTypeElement; TypeMirror superClassType; Transform annotation = null; PackageElement originPackage = elementUtils.getPackageOf(mTypeElement); PackageElement superClassPackage; Set<VariableElement> annotatedFields = new LinkedHashSet<>(); Map<String, ExecutableElement> possibleSetterFields = new HashMap<>(); do { // Scan fields for (Element e : currentClass.getEnclosedElements()) { annotation = e.getAnnotation(Transform.class); if (e.getKind() == ElementKind.FIELD && annotation != null) { annotatedFields.add((VariableElement) e); } else if (annotation != null) { throw new ProcessingException(e, "%s is of type %s and annotated with @%s, but only Fields or setter " + "Methods can be annotated with @%s", e.getSimpleName(), e.getKind().toString(), Transform.class.getSimpleName(), Transform.class.getSimpleName()); } } superClassType = currentClass.getSuperclass(); currentClass = (TypeElement) typeUtils.asElement(superClassType); } while (superClassType.getKind() != TypeKind.NONE); // Check fields for (VariableElement e : annotatedFields) { annotation = e.getAnnotation(Transform.class); currentClass = (TypeElement) e.getEnclosingElement(); TransformAnnotatedField field = new TransformAnnotatedField(e, annotation); // Check field visibility of super class field if (currentClass != mTypeElement && !field.getField() .getModifiers() .contains(Modifier.PUBLIC)) { superClassPackage = elementUtils.getPackageOf(currentClass); if ((superClassPackage != null && originPackage == null) || (superClassPackage == null && originPackage != null) || (superClassPackage != null && !superClassPackage.equals( originPackage)) || (originPackage != null && !originPackage.equals( superClassPackage))) { throw new ProcessingException(e, "The field %s in class %s can not be accessed from it transform class because of " + "visibility issue. Either move class %s into the same package " + "as %s or make the field %s public", field.getFieldName(), field.getQualifiedSurroundingClassName(), mTypeElement.getQualifiedName().toString(), field.getQualifiedSurroundingClassName(), field.getFieldName(), Transform.class.getSimpleName()); } } TransformAnnotatedField existingTransformAnnotatedField = transformAnnotatedElementsMap.get(field.getFieldName()); if (existingTransformAnnotatedField != null) { throw new ProcessingException(e, "The field %s in class %s is annotated with @%s with transform name = \"%s\" " + "but this transform name is already used by %s in class %s", field.getFieldName(), field.getQualifiedSurroundingClassName(), Transform.class.getSimpleName(), field.getFieldName(), existingTransformAnnotatedField.getElementName(), existingTransformAnnotatedField.getQualifiedSurroundingClassName()); } transformAnnotatedElementsMap.put(field.getFieldName(), field); } } /** * Gets the TypeElement representing this class * * @return the TypeElement */ public TypeElement getElement() { return mTypeElement; } /** * Gets the full qualified class name of this annotated class * * @return full qualified class name */ public String getCanonicalName() { return mCanonicalClassName; } /** * Gets the injectable state of this annotated class * * @return whether to be injected by dagger. True for inject intentions. */ public boolean isInjectable() { return mIsInjectable; } /** * Get the Elements annotated with {@link Transform} * * @return annotated elements */ public Collection<TransformAnnotatedField> getTransformAnnotatedElements() { return transformAnnotatedElementsMap.values(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.sling.discovery.impl; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Dictionary; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.ReferencePolicy; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.commons.scheduler.Scheduler; import org.apache.sling.discovery.ClusterView; import org.apache.sling.discovery.DiscoveryService; import org.apache.sling.discovery.InstanceDescription; import org.apache.sling.discovery.PropertyProvider; import org.apache.sling.discovery.TopologyEvent; import org.apache.sling.discovery.TopologyEvent.Type; import org.apache.sling.discovery.TopologyEventListener; import org.apache.sling.discovery.TopologyView; import org.apache.sling.discovery.impl.cluster.ClusterViewService; import org.apache.sling.discovery.impl.cluster.UndefinedClusterViewException; import org.apache.sling.discovery.impl.cluster.UndefinedClusterViewException.Reason; import org.apache.sling.discovery.impl.common.DefaultClusterViewImpl; import org.apache.sling.discovery.impl.common.DefaultInstanceDescriptionImpl; import org.apache.sling.discovery.impl.common.heartbeat.HeartbeatHandler; import org.apache.sling.discovery.impl.common.resource.ResourceHelper; import org.apache.sling.discovery.impl.topology.TopologyViewImpl; import org.apache.sling.discovery.impl.topology.announcement.AnnouncementRegistry; import org.apache.sling.discovery.impl.topology.connector.ConnectorRegistry; import org.apache.sling.settings.SlingSettingsService; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This implementation of the cross-cluster service uses the view manager * implementation for detecting changes in a cluster and only supports one * cluster (of which this instance is part of). */ @Component(immediate = true) @Service(value = { DiscoveryService.class, DiscoveryServiceImpl.class }) public class DiscoveryServiceImpl implements DiscoveryService { private final static Logger logger = LoggerFactory.getLogger(DiscoveryServiceImpl.class); /** SLING-4755 : encapsulates an event that yet has to be sent (asynchronously) for a particular listener **/ private final static class AsyncEvent { private final TopologyEventListener listener; private final TopologyEvent event; AsyncEvent(TopologyEventListener listener, TopologyEvent event) { if (listener==null) { throw new IllegalArgumentException("listener must not be null"); } if (event==null) { throw new IllegalArgumentException("event must not be null"); } this.listener = listener; this.event = event; } @Override public String toString() { return "an AsyncEvent[event="+event+", listener="+listener+"]"; } } /** * SLING-4755 : background runnable that takes care of asynchronously sending events. * <p> * API is: enqueue() puts a listener-event tuple onto the internal Q, which * is processed in a loop in run that does so (uninterruptably, even catching * Throwables to be 'very safe', but sleeps 5sec if an Error happens) until * flushThenStop() is called - which puts the sender in a state where any pending * events are still sent (flush) but then stops automatically. The argument of * using flush before stop is that the event was originally meant to be sent * before the bundle was stopped - thus just because the bundle is stopped * doesn't undo the event and it still has to be sent. That obviously can * mean that listeners can receive a topology event after deactivate. But I * guess that was already the case before the change to become asynchronous. */ private final static class AsyncEventSender implements Runnable { /** stopped is always false until flushThenStop is called **/ private boolean stopped = false; /** eventQ contains all AsyncEvent objects that have yet to be sent - in order to be sent **/ private final List<AsyncEvent> eventQ = new LinkedList<AsyncEvent>(); /** Enqueues a particular event for asynchronous sending to a particular listener **/ void enqueue(TopologyEventListener listener, TopologyEvent event) { final AsyncEvent asyncEvent = new AsyncEvent(listener, event); synchronized(eventQ) { eventQ.add(asyncEvent); if (logger.isDebugEnabled()) { logger.debug("enqueue: enqueued event {} for async sending (Q size: {})", asyncEvent, eventQ.size()); } eventQ.notifyAll(); } } /** * Stops the AsyncEventSender as soon as the queue is empty */ void flushThenStop() { synchronized(eventQ) { logger.info("AsyncEventSender.flushThenStop: flushing (size: {}) & stopping...", eventQ.size()); stopped = true; eventQ.notifyAll(); } } /** Main worker loop that dequeues from the eventQ and calls sendTopologyEvent with each **/ public void run() { logger.info("AsyncEventSender.run: started."); try{ while(true) { try{ final AsyncEvent asyncEvent; synchronized(eventQ) { while(!stopped && eventQ.isEmpty()) { try { eventQ.wait(); } catch (InterruptedException e) { // issue a log debug but otherwise continue logger.debug("AsyncEventSender.run: interrupted while waiting for async events"); } } if (stopped) { if (eventQ.isEmpty()) { // then we have flushed, so we can now finally stop logger.info("AsyncEventSender.run: flush finished. stopped."); return; } else { // otherwise the eventQ is not yet empty, so we are still in flush mode logger.info("AsyncEventSender.run: flushing another event. (pending {})", eventQ.size()); } } asyncEvent = eventQ.remove(0); if (logger.isDebugEnabled()) { logger.debug("AsyncEventSender.run: dequeued event {}, remaining: {}", asyncEvent, eventQ.size()); } } if (asyncEvent!=null) { sendTopologyEvent(asyncEvent); } } catch(Throwable th) { // Even though we should never catch Error or RuntimeException // here's the thinking about doing it anyway: // * in case of a RuntimeException that would be less dramatic // and catching it is less of an issue - we rather want // the background thread to be able to continue than // having it finished just because of a RuntimeException // * catching an Error is of course not so nice. // however, should we really give up this thread even in // case of an Error? It could be an OOM or some other // nasty one, for sure. But even if. Chances are that // other parts of the system would also get that Error // if it is very dramatic. If not, then catching it // sounds feasible. // My two cents.. // the goal is to avoid quitting the AsyncEventSender thread logger.error("AsyncEventSender.run: Throwable occurred. Sleeping 5sec. Throwable: "+th, th); try { Thread.sleep(5000); } catch (InterruptedException e) { logger.warn("AsyncEventSender.run: interrupted while sleeping"); } } } } finally { logger.info("AsyncEventSender.run: quits (finally)."); } } /** Actual sending of the asynchronous event - catches RuntimeExceptions a listener can send. (Error is caught outside) **/ private void sendTopologyEvent(AsyncEvent asyncEvent) { final TopologyEventListener listener = asyncEvent.listener; final TopologyEvent event = asyncEvent.event; logger.debug("sendTopologyEvent: start: listener: {}, event: {}", listener, event); try{ listener.handleTopologyEvent(event); } catch(final Exception e) { logger.warn("sendTopologyEvent: handler threw exception. handler: "+listener+", exception: "+e, e); } logger.debug("sendTopologyEvent: start: listener: {}, event: {}", listener, event); } } @Reference private SlingSettingsService settingsService; @Reference(cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC, referenceInterface = TopologyEventListener.class) private TopologyEventListener[] eventListeners = new TopologyEventListener[0]; /** SLING-5030 : this map contains the event last sent to each listener to prevent duplicate CHANGING events when scheduler is broken**/ private Map<TopologyEventListener,TopologyEvent.Type> lastEventMap = new HashMap<TopologyEventListener, TopologyEvent.Type>(); /** * All property providers. */ @Reference(cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC, referenceInterface = PropertyProvider.class, updated = "updatedPropertyProvider") private List<ProviderInfo> providerInfos = new ArrayList<ProviderInfo>(); /** lock object used for synching bind/unbind and topology event sending **/ private final Object lock = new Object(); /** * whether or not this service is activated - necessary to avoid sending * events to discovery awares before activate is done **/ private boolean activated = false; /** SLING-3750 : set when activate() could not send INIT events due to being in isolated mode **/ private boolean initEventDelayed = false; @Reference private ResourceResolverFactory resourceResolverFactory; @Reference private Scheduler scheduler; @Reference private HeartbeatHandler heartbeatHandler; @Reference private AnnouncementRegistry announcementRegistry; @Reference private ConnectorRegistry connectorRegistry; @Reference private ClusterViewService clusterViewService; @Reference private Config config; /** the slingId of the local instance **/ private String slingId; /** the old view previously valid and sent to the TopologyEventListeners **/ private TopologyViewImpl oldView; /** * whether or not there is a delayed event sending pending. * Marked volatile to allow getTopology() to read this without need for * synchronized(lock) (which would be deadlock-prone). (introduced with SLING-4638). **/ private volatile boolean delayedEventPending = false; /** used to continue functioning when scheduler is broken **/ private volatile boolean delayedEventPendingFailed = false; private ServiceRegistration mbeanRegistration; /** SLING-4755 : reference to the background AsyncEventSender. Started/stopped in activate/deactivate **/ private AsyncEventSender asyncEventSender; protected void registerMBean(BundleContext bundleContext) { if (this.mbeanRegistration!=null) { try{ if ( this.mbeanRegistration != null ) { this.mbeanRegistration.unregister(); this.mbeanRegistration = null; } } catch(Exception e) { logger.error("registerMBean: Error on unregister: "+e, e); } } try { final Dictionary<String, String> mbeanProps = new Hashtable<String, String>(); mbeanProps.put("jmx.objectname", "org.apache.sling:type=discovery,name=DiscoveryServiceImpl"); final DiscoveryServiceMBeanImpl mbean = new DiscoveryServiceMBeanImpl(heartbeatHandler); this.mbeanRegistration = bundleContext.registerService(DiscoveryServiceMBeanImpl.class.getName(), mbean, mbeanProps); } catch (Throwable t) { logger.warn("registerMBean: Unable to register DiscoveryServiceImpl MBean", t); } } private void setOldView(TopologyViewImpl view) { if (view==null) { throw new IllegalArgumentException("view must not be null"); } oldView = view; } /** * Activate this service */ @Activate protected void activate(final BundleContext bundleContext) { logger.debug("DiscoveryServiceImpl activating..."); if (settingsService == null) { throw new IllegalStateException("settingsService not found"); } if (heartbeatHandler == null) { throw new IllegalStateException("heartbeatHandler not found"); } slingId = settingsService.getSlingId(); final String isolatedClusterId = UUID.randomUUID().toString(); { // create a pre-voting/isolated topologyView which would be used // until the first voting has finished. // this way for the single-instance case the clusterId can // remain the same between a getTopology() that is invoked before // the first TOPOLOGY_INIT and afterwards DefaultClusterViewImpl isolatedCluster = new DefaultClusterViewImpl(isolatedClusterId); Map<String, String> emptyProperties = new HashMap<String, String>(); DefaultInstanceDescriptionImpl isolatedInstance = new DefaultInstanceDescriptionImpl(isolatedCluster, true, true, slingId, emptyProperties); Collection<InstanceDescription> col = new ArrayList<InstanceDescription>(); col.add(isolatedInstance); final TopologyViewImpl topology = new TopologyViewImpl(); topology.addInstances(col); topology.markOld(); setOldView(topology); } setOldView((TopologyViewImpl) getTopology()); oldView.markOld(); // make sure the first heartbeat is issued as soon as possible - which // is right after this service starts. since the two (discoveryservice // and heartbeatHandler need to know each other, the discoveryservice // is passed on to the heartbeatHandler in this initialize call). heartbeatHandler.initialize(this, isolatedClusterId); final TopologyEventListener[] registeredServices; synchronized (lock) { // SLING-4755 : start the asyncEventSender in the background // will be stopped in deactivate (at which point // all pending events will still be sent but no // new events can be enqueued) asyncEventSender = new AsyncEventSender(); Thread th = new Thread(asyncEventSender); th.setName("Discovery-AsyncEventSender"); th.setDaemon(true); th.start(); registeredServices = this.eventListeners; doUpdateProperties(); TopologyViewImpl newView = (TopologyViewImpl) getTopology(); if (!newView.isCurrent()) { // SLING-3750: just issue a log.info about the delaying logger.info("activate: this instance is in isolated mode and must yet finish voting before it can send out TOPOLOGY_INIT."); initEventDelayed = true; } else { final TopologyEvent event = new TopologyEvent(Type.TOPOLOGY_INIT, null, newView); for (final TopologyEventListener da : registeredServices) { enqueueAsyncTopologyEvent(da, event); } } activated = true; setOldView(newView); } URL[] topologyConnectorURLs = config.getTopologyConnectorURLs(); if (topologyConnectorURLs != null) { for (int i = 0; i < topologyConnectorURLs.length; i++) { final URL aURL = topologyConnectorURLs[i]; if (aURL!=null) { try{ logger.info("activate: registering outgoing topology connector to "+aURL); connectorRegistry.registerOutgoingConnector(clusterViewService, aURL); } catch (final Exception e) { logger.info("activate: could not register url: "+aURL+" due to: "+e, e); } } } } registerMBean(bundleContext); logger.debug("DiscoveryServiceImpl activated."); } private void enqueueAsyncTopologyEvent(final TopologyEventListener da, final TopologyEvent event) { if (logger.isDebugEnabled()) { logger.debug("enqueueAsyncTopologyEvent: sending topologyEvent {}, to {}", event, da); } if (asyncEventSender==null) { // this should never happen - sendTopologyEvent should only be called // when activated logger.warn("enqueueAsyncTopologyEvent: asyncEventSender is null, cannot send event ({}, {})!", da, event); return; } if (lastEventMap.get(da)==event.getType() && event.getType()==Type.TOPOLOGY_CHANGING) { // don't sent TOPOLOGY_CHANGING twice logger.debug("enqueueAsyncTopologyEvent: listener already got TOPOLOGY_CHANGING: {}", da); return; } asyncEventSender.enqueue(da, event); lastEventMap.put(da, event.getType()); if (logger.isDebugEnabled()) { logger.debug("enqueueAsyncTopologyEvent: sending topologyEvent {}, to {}", event, da); } } /** * Deactivate this service */ @Deactivate protected void deactivate() { logger.debug("DiscoveryServiceImpl deactivated."); synchronized (lock) { activated = false; if (asyncEventSender!=null) { // it should always be not-null though asyncEventSender.flushThenStop(); asyncEventSender = null; } } try{ if ( this.mbeanRegistration != null ) { this.mbeanRegistration.unregister(); this.mbeanRegistration = null; } } catch(Exception e) { logger.error("deactivate: Error on unregister: "+e, e); } } /** * bind a topology event listener */ protected void bindTopologyEventListener(final TopologyEventListener eventListener) { logger.debug("bindTopologyEventListener: Binding TopologyEventListener {}", eventListener); synchronized (lock) { final List<TopologyEventListener> currentList = new ArrayList<TopologyEventListener>( Arrays.asList(eventListeners)); currentList.add(eventListener); this.eventListeners = currentList .toArray(new TopologyEventListener[currentList.size()]); if (activated && !initEventDelayed) { final TopologyViewImpl topology = (TopologyViewImpl) getTopology(); if (delayedEventPending) { // that means that for other TopologyEventListeners that were already bound // and in general: the topology is currently CHANGING // so we must reflect this with the isCurrent() flag (SLING-4638) topology.markOld(); } enqueueAsyncTopologyEvent(eventListener, new TopologyEvent( Type.TOPOLOGY_INIT, null, topology)); } } } /** * Unbind a topology event listener */ protected void unbindTopologyEventListener(final TopologyEventListener eventListener) { logger.debug("unbindTopologyEventListener: Releasing TopologyEventListener {}", eventListener); synchronized (lock) { final List<TopologyEventListener> currentList = new ArrayList<TopologyEventListener>( Arrays.asList(eventListeners)); currentList.remove(eventListener); this.eventListeners = currentList .toArray(new TopologyEventListener[currentList.size()]); } } /** * Bind a new property provider. */ protected void bindPropertyProvider(final PropertyProvider propertyProvider, final Map<String, Object> props) { logger.debug("bindPropertyProvider: Binding PropertyProvider {}", propertyProvider); synchronized (lock) { this.bindPropertyProviderInteral(propertyProvider, props); } } /** * Bind a new property provider. */ private void bindPropertyProviderInteral(final PropertyProvider propertyProvider, final Map<String, Object> props) { final ProviderInfo info = new ProviderInfo(propertyProvider, props); this.providerInfos.add(info); Collections.sort(this.providerInfos); this.doUpdateProperties(); handlePotentialTopologyChange(); } /** * Update a property provider. */ protected void updatedPropertyProvider(final PropertyProvider propertyProvider, final Map<String, Object> props) { logger.debug("bindPropertyProvider: Updating PropertyProvider {}", propertyProvider); synchronized (lock) { this.unbindPropertyProviderInternal(propertyProvider, props, false); this.bindPropertyProviderInteral(propertyProvider, props); } } /** * Unbind a property provider */ protected void unbindPropertyProvider(final PropertyProvider propertyProvider, final Map<String, Object> props) { logger.debug("unbindPropertyProvider: Releasing PropertyProvider {}", propertyProvider); synchronized (lock) { this.unbindPropertyProviderInternal(propertyProvider, props, true); } } /** * Unbind a property provider */ private void unbindPropertyProviderInternal( final PropertyProvider propertyProvider, final Map<String, Object> props, final boolean update) { final ProviderInfo info = new ProviderInfo(propertyProvider, props); if ( this.providerInfos.remove(info) && update ) { this.doUpdateProperties(); this.handlePotentialTopologyChange(); } } /** * Update the properties by inquiring the PropertyProvider's current values. * <p> * This method is invoked regularly by the heartbeatHandler. * The properties are stored in the repository under Config.getClusterInstancesPath() * and announced in the topology. * <p> * @see Config#getClusterInstancesPath() */ private void doUpdateProperties() { if (resourceResolverFactory == null) { // cannot update the properties then.. logger.debug("doUpdateProperties: too early to update the properties. resourceResolverFactory not yet set."); return; } else { logger.debug("doUpdateProperties: updating properties now.."); } final Map<String, String> newProps = new HashMap<String, String>(); for (final ProviderInfo info : this.providerInfos) { info.refreshProperties(); newProps.putAll(info.properties); } ResourceResolver resourceResolver = null; try { resourceResolver = resourceResolverFactory .getAdministrativeResourceResolver(null); Resource myInstance = ResourceHelper .getOrCreateResource( resourceResolver, config.getClusterInstancesPath() + "/" + slingId + "/properties"); // SLING-2879 - revert/refresh resourceResolver here to work // around a potential issue with jackrabbit in a clustered environment resourceResolver.revert(); resourceResolver.refresh(); final ModifiableValueMap myInstanceMap = myInstance.adaptTo(ModifiableValueMap.class); final Set<String> keys = new HashSet<String>(myInstanceMap.keySet()); for(final String key : keys) { if (newProps.containsKey(key)) { // perfect continue; } else if (key.indexOf(":")!=-1) { // ignore continue; } else { // remove myInstanceMap.remove(key); } } boolean anyChanges = false; for(final Entry<String, String> entry : newProps.entrySet()) { Object existingValue = myInstanceMap.get(entry.getKey()); if (entry.getValue().equals(existingValue)) { // SLING-3389: dont rewrite the properties if nothing changed! if (logger.isDebugEnabled()) { logger.debug("doUpdateProperties: unchanged: {}={}", entry.getKey(), entry.getValue()); } continue; } if (logger.isDebugEnabled()) { logger.debug("doUpdateProperties: changed: {}={}", entry.getKey(), entry.getValue()); } anyChanges = true; myInstanceMap.put(entry.getKey(), entry.getValue()); } if (anyChanges) { resourceResolver.commit(); } } catch (LoginException e) { logger.error( "handleEvent: could not log in administratively: " + e, e); throw new RuntimeException("Could not log in to repository (" + e + ")", e); } catch (PersistenceException e) { logger.error("handleEvent: got a PersistenceException: " + e, e); throw new RuntimeException( "Exception while talking to repository (" + e + ")", e); } finally { if (resourceResolver != null) { resourceResolver.close(); } } logger.debug("doUpdateProperties: updating properties done."); } /** * @see DiscoveryService#getTopology() */ public TopologyView getTopology() { if (clusterViewService == null) { throw new IllegalStateException( "DiscoveryService not yet initialized with IClusterViewService"); } // create a new topology view final TopologyViewImpl topology = new TopologyViewImpl(); ClusterView localClusterView = null; try { localClusterView = clusterViewService.getClusterView(); } catch (UndefinedClusterViewException e) { // SLING-5030 : when we're cut off from the local cluster we also // treat it as being cut off from the entire topology, ie we don't // update the announcements but just return // the previous oldView marked as !current logger.info("getTopology: undefined cluster view: "+e.getReason()+"] "+e); oldView.markOld(); if (e.getReason()==Reason.ISOLATED_FROM_TOPOLOGY) { if (heartbeatHandler!=null) { // SLING-5030 part 2: when we detect being isolated we should // step at the end of the leader-election queue and // that can be achieved by resetting the leaderElectionId // (which will in turn take effect on the next round of // voting, or also double-checked when the local instance votes) // //TODO: // Note that when the local instance doesn't notice // an 'ISOLATED_FROM_TOPOLOGY' case, then the leaderElectionId // will not be reset. Which means that it then could potentially // regain leadership. if (heartbeatHandler.resetLeaderElectionId()) { logger.info("getTopology: reset leaderElectionId to force this instance to the end of the instance order (thus incl not to remain leader)"); } } } return oldView; } final List<InstanceDescription> localInstances = localClusterView.getInstances(); topology.addInstances(localInstances); Collection<InstanceDescription> attachedInstances = announcementRegistry .listInstances(localClusterView); topology.addInstances(attachedInstances); return topology; } /** * Update the properties and sent a topology event if applicable */ public void updateProperties() { synchronized (lock) { logger.debug("updateProperties: calling doUpdateProperties."); doUpdateProperties(); logger.debug("updateProperties: calling handlePotentialTopologyChange."); handlePotentialTopologyChange(); logger.debug("updateProperties: done."); } } /** * Internal handle method which checks if anything in the topology has * changed and informs the TopologyEventListeners if such a change occurred. * <p> * All changes should go through this method. This method keeps track of * oldView/newView as well. */ private void handlePotentialTopologyChange() { if (!activated) { // ignore this call then - an early call to issue // a topologyevent before even activated logger.debug("handlePotentialTopologyChange: ignoring early change before activate finished."); return; } if (delayedEventPending && !delayedEventPendingFailed) { logger.debug("handlePotentialTopologyChange: ignoring potential change since a delayed event is pending."); return; } TopologyViewImpl newView = (TopologyViewImpl) getTopology(); if (initEventDelayed) { // this means activate could not yet send a TOPOLOGY_INIT event // (which can happen frequently) - so we have to do this now // that we potentially have a valid view if (!newView.isCurrent()) { // we cannot proceed until we're out of the isolated mode.. // SLING-4535 : while this has warning character, it happens very frequently, // eg also when binding a PropertyProvider (so normal processing) // hence lowering to info for now logger.info("handlePotentialTopologyChange: still in isolated mode - cannot send TOPOLOGY_INIT yet."); } else { logger.info("handlePotentialTopologyChange: new view is no longer isolated sending delayed TOPOLOGY_INIT now."); // SLING-4638: OK: newView is current==true as we're just coming out of initEventDelayed first time. enqueueForAll(Type.TOPOLOGY_INIT, null, newView); initEventDelayed = false; } return; } TopologyViewImpl oldView = this.oldView; Type difference; if (!newView.isCurrent()) { difference = Type.TOPOLOGY_CHANGING; } else { difference = newView.compareTopology(oldView); } if (difference == null) { // indicating: equals if (delayedEventPendingFailed) { // when the delayed event handling for some very odd reason could // not re-spawn itself (via runAfter) - in that case we now // have listeners in CHANGING state .. which we should wake up enqueueForAll(Type.TOPOLOGY_CHANGED, oldView, newView); delayedEventPendingFailed = false; delayedEventPending = false; } else { // then dont send any event then logger.debug("handlePotentialTopologyChange: identical views. not informing listeners"); } return; } else if (difference == Type.PROPERTIES_CHANGED) { enqueueForAll(Type.PROPERTIES_CHANGED, oldView, newView); return; } delayedEventPendingFailed = false; delayedEventPending = false; // else: TOPOLOGY_CHANGING or CHANGED if (logger.isDebugEnabled()) { logger.debug("handlePotentialTopologyChange: difference: {}, oldView={}, newView={}", new Object[] {difference, oldView, newView}); } // send a TOPOLOGY_CHANGING first logger.info("handlePotentialTopologyChange: sending "+Type.TOPOLOGY_CHANGING+ " to all listeners (that have not gotten one yet) (oldView={}).", oldView); oldView.markOld(); for (final TopologyEventListener da : eventListeners) { enqueueAsyncTopologyEvent(da, new TopologyEvent(Type.TOPOLOGY_CHANGING, oldView, null)); } int minEventDelay = config.getMinEventDelay(); if ((!newView.isCurrent()) && minEventDelay<=0) { // if newView is isolated // then we should not send a TOPOLOGY_CHANGED yet - but instead // wait until the view gets resolved. that is achieved by // going into event-delaying and retrying that way. // and if minEventDelay is not configured, then auto-switch // to a 1sec such minEventDelay: minEventDelay=1; } if (minEventDelay<=0) { // otherwise, send the TOPOLOGY_CHANGED now enqueueForAll(Type.TOPOLOGY_CHANGED, oldView, newView); return; } // then delay the sending of the next event logger.debug("handlePotentialTopologyChange: delaying event sending to avoid event flooding"); if (runAfter(minEventDelay /*seconds*/ , new Runnable() { public void run() { logger.debug("handlePotentialTopologyChange: acquiring synchronized(lock)..."); synchronized(lock) { logger.debug("handlePotentialTopologyChange: sending delayed event now"); if (!activated) { delayedEventPending = false; delayedEventPendingFailed = false; logger.debug("handlePotentialTopologyChange: no longer activated. not sending delayed event"); return; } final TopologyViewImpl newView = (TopologyViewImpl) getTopology(); // irrespective of the difference, send the latest topology // via a topology_changed event (since we already sent a changing) if (!newView.isCurrent()) { // if the newView is isolated at this stage we have sent // TOPOLOGY_CHANGING to the listeners, and they are now waiting // for TOPOLOGY_CHANGED. But we can't send them that yet.. // we must do a loop via the minEventDelay mechanism and log // accordingly if (runAfter(1/*sec*/, this)) { logger.warn("handlePotentialTopologyChange: local instance is isolated from topology. Waiting for rejoining..."); return; } // otherwise we have to fall back to still sending a TOPOLOGY_CHANGED // but that's unexpected! (back to delayedEventPending=false..) delayedEventPendingFailed = true; logger.warn("handlePotentialTopologyChange: local instance is isolated from topology but failed to trigger delay-job"); return; } enqueueForAll(Type.TOPOLOGY_CHANGED, DiscoveryServiceImpl.this.oldView, newView); delayedEventPending = false; delayedEventPendingFailed = false; } } })) { delayedEventPending = true; delayedEventPendingFailed = false; logger.debug("handlePotentialTopologyChange: delayed event triggering."); return; } else { logger.debug("handlePotentialTopologyChange: delaying event triggering did not work for some reason. " + "Will be retriggered lazily via later heartbeat."); delayedEventPending = true; delayedEventPendingFailed = true; return; } } private void enqueueForAll(Type eventType, TopologyViewImpl oldView, TopologyViewImpl newView) { if (oldView!=null) { oldView.markOld(); } logger.info("enqueueForAll: sending "+eventType+" to all listeners (oldView={}, newView={}).", oldView, newView); for (final TopologyEventListener da : eventListeners) { enqueueAsyncTopologyEvent(da, new TopologyEvent(eventType, oldView, newView)); } if (eventType!=Type.TOPOLOGY_CHANGING) { setOldView(newView); } if (heartbeatHandler!=null) { // trigger a heartbeat 'now' to pass it on to the topology asap heartbeatHandler.triggerHeartbeat(); } } /** * run the runnable after the indicated number of seconds, once. * @return true if the scheduling of the runnable worked, false otherwise */ private boolean runAfter(int seconds, final Runnable runnable) { final Scheduler theScheduler = scheduler; if (theScheduler == null) { logger.info("runAfter: no scheduler set"); return false; } logger.debug("runAfter: trying with scheduler.fireJob"); final Date date = new Date(System.currentTimeMillis() + seconds * 1000); try { theScheduler.fireJobAt(null, runnable, null, date); return true; } catch (Exception e) { logger.info("runAfter: could not schedule a job: "+e); return false; } } /** * Internal class caching some provider infos like service id and ranking. */ private final static class ProviderInfo implements Comparable<ProviderInfo> { public final PropertyProvider provider; public final Object propertyProperties; public final int ranking; public final long serviceId; public final Map<String, String> properties = new HashMap<String, String>(); public ProviderInfo(final PropertyProvider provider, final Map<String, Object> serviceProps) { this.provider = provider; this.propertyProperties = serviceProps.get(PropertyProvider.PROPERTY_PROPERTIES); final Object sr = serviceProps.get(Constants.SERVICE_RANKING); if (sr == null || !(sr instanceof Integer)) { this.ranking = 0; } else { this.ranking = (Integer) sr; } this.serviceId = (Long) serviceProps.get(Constants.SERVICE_ID); refreshProperties(); } public void refreshProperties() { properties.clear(); if (this.propertyProperties instanceof String) { final String val = provider.getProperty((String) this.propertyProperties); if (val != null) { putPropertyIfValid((String) this.propertyProperties, val); } } else if (this.propertyProperties instanceof String[]) { for (final String name : (String[]) this.propertyProperties) { final String val = provider.getProperty(name); if (val != null) { putPropertyIfValid(name, val); } } } } /** SLING-2883 : put property only if valid **/ private void putPropertyIfValid(final String name, final String val) { if (ResourceHelper.isValidPropertyName(name)) { this.properties.put(name, val); } } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(final ProviderInfo o) { // Sort by rank in ascending order. if (this.ranking < o.ranking) { return -1; // lower rank } else if (this.ranking > o.ranking) { return 1; // higher rank } // If ranks are equal, then sort by service id in descending order. return (this.serviceId < o.serviceId) ? 1 : -1; } @Override public boolean equals(final Object obj) { if (obj instanceof ProviderInfo) { return ((ProviderInfo) obj).serviceId == this.serviceId; } return false; } @Override public int hashCode() { return provider.hashCode(); } } /** * Handle the fact that the topology has likely changed */ public void handleTopologyChanged() { logger.debug("handleTopologyChanged: calling handlePotentialTopologyChange."); synchronized ( this.lock ) { handlePotentialTopologyChange(); } } /** SLING-2901 : send a TOPOLOGY_CHANGING event and shutdown the service thereafter **/ public void forcedShutdown() { synchronized(lock) { if (!activated) { logger.error("forcedShutdown: ignoring forced shutdown. Service is not activated."); return; } if (oldView == null) { logger.error("forcedShutdown: ignoring forced shutdown. No oldView available."); return; } logger.error("forcedShutdown: sending TOPOLOGY_CHANGING to all listeners"); // SLING-4638: make sure the oldView is really marked as old: oldView.markOld(); for (final TopologyEventListener da : eventListeners) { enqueueAsyncTopologyEvent(da, new TopologyEvent(Type.TOPOLOGY_CHANGING, oldView, null)); } logger.error("forcedShutdown: deactivating DiscoveryService."); // to make sure no further event is sent after this, flag this service as deactivated activated = false; } } }
/* * * Copyright (c) 2016-2017 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.vertx.maven.plugin; //import io.restassured.RestAssured; import io.fabric8.vertx.maven.plugin.utils.MojoUtils; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Assert; import java.io.*; import java.util.Optional; import java.util.Properties; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import static junit.framework.Assert.assertNotNull; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author kameshs */ @SuppressWarnings("unused") public class Verify { public static void verifyVertxJar(File jarFile) throws Exception { VertxJarVerifier vertxJarVerifier = new VertxJarVerifier(jarFile); vertxJarVerifier.verifyJarCreated(); vertxJarVerifier.verifyManifest(); } public static void verifyServiceRelocation(File jarFile) throws Exception { VertxJarServicesVerifier vertxJarVerifier = new VertxJarServicesVerifier(jarFile); vertxJarVerifier.verifyJarCreated(); vertxJarVerifier.verifyServicesContent(); } public static void verifyOrderServiceContent(File jarFile,String orderdedContent) throws Exception { VertxJarServicesVerifier vertxJarVerifier = new VertxJarServicesVerifier(jarFile); vertxJarVerifier.verifyJarCreated(); vertxJarVerifier.verifyOrderedServicesContent(orderdedContent); } public static void verifySetup(File pomFile) throws Exception { assertNotNull("Unable to find pom.xml", pomFile); MavenXpp3Reader xpp3Reader = new MavenXpp3Reader(); Model model = xpp3Reader.read(new FileInputStream(pomFile)); MavenProject project = new MavenProject(model); Optional<Plugin> vmPlugin = MojoUtils.hasPlugin(project, "io.fabric8:vertx-maven-plugin"); assertTrue(vmPlugin.isPresent()); //Check if the properties have been set correctly Properties properties = model.getProperties(); assertThat(properties.containsKey("vertx.projectVersion")).isTrue(); assertThat(properties.getProperty("vertx.projectVersion")) .isEqualTo(MojoUtils.getVersion("vertx-core-version")); assertThat(properties.containsKey("fabric8-vertx-maven-plugin.projectVersion")).isTrue(); assertThat(properties.getProperty("fabric8-vertx-maven-plugin.projectVersion")) .isEqualTo(MojoUtils.getVersion("vertx-maven-plugin-version")); //Check if the dependencies has been set correctly DependencyManagement dependencyManagement = model.getDependencyManagement(); assertThat(dependencyManagement).isNotNull(); assertThat(dependencyManagement.getDependencies().isEmpty()).isFalse(); //Check Vert.x dependencies BOM Optional<Dependency> vertxDeps = dependencyManagement.getDependencies().stream() .filter(d -> d.getArtifactId().equals("vertx-dependencies") && d.getGroupId().equals("io.vertx")) .findFirst(); assertThat(vertxDeps.isPresent()).isTrue(); assertThat(vertxDeps.get().getVersion()).isEqualTo("${vertx.projectVersion}"); //Check Vert.x core dependency Optional<Dependency> vertxCoreDep = model.getDependencies().stream() .filter(d -> d.getArtifactId().equals("vertx-core") && d.getGroupId().equals("io.vertx")) .findFirst(); assertThat(vertxCoreDep.isPresent()).isTrue(); assertThat(vertxCoreDep.get().getVersion()).isNull(); //Check Redeploy Configuration Plugin vmp = project.getPlugin("io.fabric8:vertx-maven-plugin"); Assert.assertNotNull(vmp); Xpp3Dom pluginConfig = (Xpp3Dom) vmp.getConfiguration(); Assert.assertNotNull(pluginConfig); String redeploy = pluginConfig.getChild("redeploy").getValue(); Assert.assertNotNull(redeploy); assertTrue(Boolean.valueOf(redeploy)); } public static void verifySetupWithVersion(File pomFile) throws Exception { MavenXpp3Reader xpp3Reader = new MavenXpp3Reader(); Model model = xpp3Reader.read(new FileInputStream(pomFile)); MavenProject project = new MavenProject(model); Properties projectProps = project.getProperties(); Assert.assertNotNull(projectProps); assertFalse(projectProps.isEmpty()); assertEquals(projectProps.getProperty("vertx.projectVersion"),"3.4.0"); } public static String read(InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.joining("\n")); } } public static Stream<String> readAsStream(InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.toList()).stream(); } } public static String argsToString(String[] args) { return Stream.of(args).collect(Collectors.joining(" ")); } public static class VertxJarVerifier { File jarFile; public VertxJarVerifier(File jarFile) { this.jarFile = jarFile; } protected void verifyJarCreated() { assertThat(jarFile).isNotNull(); assertThat(jarFile).isFile(); } protected void verifyManifest() throws Exception { Manifest manifest = new JarFile(jarFile).getManifest(); assertThat(manifest).isNotNull(); String mainClass = manifest.getMainAttributes().getValue("Main-Class"); String mainVerticle = manifest.getMainAttributes().getValue("Main-Verticle"); assertThat(mainClass).isNotNull().isEqualTo("io.vertx.core.Launcher"); assertThat(mainVerticle).isNotNull().isEqualTo("org.vertx.demo.MainVerticle"); } } public static class VertxJarServicesVerifier { JarFile jarFile; public VertxJarServicesVerifier(File jarFile) throws IOException { this.jarFile = new JarFile(jarFile); } protected void verifyJarCreated() { assertThat(jarFile).isNotNull(); } protected void verifyServicesContent() throws Exception { String expected = "foo.bar.baz.MyImpl\ncom.fasterxml.jackson.core.JsonFactory"; ZipEntry spiEntry1 = jarFile.getEntry("META-INF/services/com.fasterxml.jackson.core.JsonFactory"); ZipEntry spiEntry2 = jarFile.getEntry("META-INF/services/io.vertx.core.spi.FutureFactory"); assertThat(spiEntry1).isNotNull(); assertThat(spiEntry2).isNotNull(); InputStream in = jarFile.getInputStream(spiEntry1); String actual = read(in); assertThat(actual).isEqualTo(expected); in = jarFile.getInputStream(spiEntry2); actual = read(in); assertThat(actual).isEqualTo("io.vertx.core.impl.FutureFactoryImpl"); // This part is going to be used once Vert.x 3.4.0 is released // // TODO Uncomment me once Vert.x 3.4.0 is released // ZipEntry spiEntry3 = jarFile.getEntry("META-INF/services/org.codehaus.groovy.runtime.ExtensionModule"); // assertThat(spiEntry3).isNotNull(); // in = jarFile.getInputStream(spiEntry3); // actual = read(in); // assertThat(actual).contains("moduleName=vertx-demo-pkg") // .contains("moduleVersion=0.0.1") // .contains("io.vertx.groovy.ext.jdbc.GroovyStaticExtension") // .contains("io.vertx.groovy.ext.jdbc.GroovyExtension"); } protected void verifyOrderedServicesContent(String orderedContent) throws Exception { ZipEntry spiEntry = jarFile.getEntry("META-INF/services/io.fabric8.vmp.foo"); assertThat(spiEntry).isNotNull(); InputStream in = jarFile.getInputStream(spiEntry); String actual = read(in); assertThat(actual).isEqualTo(orderedContent); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.kafka.connect.runtime; import org.apache.kafka.connect.runtime.isolation.Plugins; import org.apache.kafka.connect.runtime.rest.entities.ConfigInfos; import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo; import org.apache.kafka.connect.runtime.rest.entities.ConnectorStateInfo; import org.apache.kafka.connect.runtime.rest.entities.TaskInfo; import org.apache.kafka.connect.util.Callback; import org.apache.kafka.connect.util.ConnectorTaskId; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; /** * <p> * The herder interface tracks and manages workers and connectors. It is the main interface for external components * to make changes to the state of the cluster. For example, in distributed mode, an implementation of this class * knows how to accept a connector configuration, may need to route it to the current leader worker for the cluster so * the config can be written to persistent storage, and then ensures the new connector is correctly instantiated on one * of the workers. * </p> * <p> * This class must implement all the actions that can be taken on the cluster (add/remove connectors, pause/resume tasks, * get state of connectors and tasks, etc). The non-Java interfaces to the cluster (REST API and CLI) are very simple * wrappers of the functionality provided by this interface. * </p> * <p> * In standalone mode, this implementation of this class will be trivial because no coordination is needed. In that case, * the implementation will mainly be delegating tasks directly to other components. For example, when creating a new * connector in standalone mode, there is no need to persist the config and the connector and its tasks must run in the * same process, so the standalone herder implementation can immediately instantiate and start the connector and its * tasks. * </p> */ public interface Herder { void start(); void stop(); /** * Get a list of connectors currently running in this cluster. This is a full list of connectors in the cluster gathered * from the current configuration. However, note * * @returns A list of connector names * @throws org.apache.kafka.connect.runtime.distributed.RequestTargetException if this node can not resolve the request * (e.g., because it has not joined the cluster or does not have configs in sync with the group) and it is * not the leader or the task owner (e.g., task restart must be handled by the worker which owns the task) * @throws org.apache.kafka.connect.errors.ConnectException if this node is the leader, but still cannot resolve the * request (e.g., it is not in sync with other worker's config state) */ void connectors(Callback<Collection<String>> callback); /** * Get the definition and status of a connector. */ void connectorInfo(String connName, Callback<ConnectorInfo> callback); /** * Get the configuration for a connector. * @param connName name of the connector * @param callback callback to invoke with the configuration */ void connectorConfig(String connName, Callback<Map<String, String>> callback); /** * Set the configuration for a connector. This supports creation and updating. * @param connName name of the connector * @param config the connectors configuration, or null if deleting the connector * @param allowReplace if true, allow overwriting previous configs; if false, throw AlreadyExistsException if a connector * with the same name already exists * @param callback callback to invoke when the configuration has been written */ void putConnectorConfig(String connName, Map<String, String> config, boolean allowReplace, Callback<Created<ConnectorInfo>> callback); /** * Delete a connector and its configuration. * @param connName name of the connector * @param callback callback to invoke when the configuration has been written */ void deleteConnectorConfig(String connName, Callback<Created<ConnectorInfo>> callback); /** * Requests reconfiguration of the task. This should only be triggered by * {@link HerderConnectorContext}. * * @param connName name of the connector that should be reconfigured */ void requestTaskReconfiguration(String connName); /** * Get the configurations for the current set of tasks of a connector. * @param connName connector to update * @param callback callback to invoke upon completion */ void taskConfigs(String connName, Callback<List<TaskInfo>> callback); /** * Set the configurations for the tasks of a connector. This should always include all tasks in the connector; if * there are existing configurations and fewer are provided, this will reduce the number of tasks, and if more are * provided it will increase the number of tasks. * @param connName connector to update * @param configs list of configurations * @param callback callback to invoke upon completion */ void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback); /** * Lookup the current status of a connector. * @param connName name of the connector */ ConnectorStateInfo connectorStatus(String connName); /** * Lookup the status of the a task. * @param id id of the task */ ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id); /** * Validate the provided connector config values against the configuration definition. * @param connectorConfig the provided connector config values */ ConfigInfos validateConnectorConfig(Map<String, String> connectorConfig); /** * Restart the task with the given id. * @param id id of the task * @param cb callback to invoke upon completion */ void restartTask(ConnectorTaskId id, Callback<Void> cb); /** * Restart the connector. * @param connName name of the connector * @param cb callback to invoke upon completion */ void restartConnector(String connName, Callback<Void> cb); /** * Pause the connector. This call will asynchronously suspend processing by the connector and all * of its tasks. * @param connector name of the connector */ void pauseConnector(String connector); /** * Resume the connector. This call will asynchronously start the connector and its tasks (if * not started already). * @param connector name of the connector */ void resumeConnector(String connector); /** * Returns a handle to the plugin factory used by this herder and its worker. * * @return a reference to the plugin factory. */ Plugins plugins(); /** * Get the cluster ID of the Kafka cluster backing this Connect cluster. * @return the cluster ID of the Kafka cluster backing this connect cluster */ String kafkaClusterId(); class Created<T> { private final boolean created; private final T result; public Created(boolean created, T result) { this.created = created; this.result = result; } public boolean created() { return created; } public T result() { return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Created<?> created1 = (Created<?>) o; return Objects.equals(created, created1.created) && Objects.equals(result, created1.result); } @Override public int hashCode() { return Objects.hash(created, result); } } }
package io.arabesque.pattern; import io.arabesque.conf.Configuration; import io.arabesque.embedding.Embedding; import io.arabesque.graph.Edge; import io.arabesque.graph.MainGraph; import io.arabesque.graph.Vertex; import io.arabesque.pattern.pool.PatternEdgePool; import io.arabesque.utils.collection.IntArrayList; import io.arabesque.utils.collection.IntCollectionAddConsumer; import com.koloboke.collect.map.IntIntCursor; import com.koloboke.collect.map.IntIntMap; import com.koloboke.collect.map.hash.HashIntIntMapFactory; import com.koloboke.collect.map.hash.HashIntIntMaps; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import java.io.*; // TODO: use murmur hash to do pattern hashing //import com.google.common.hash.Hashing; public abstract class BasicPattern implements Pattern { private static final Logger LOG = Logger.getLogger(BasicPattern.class); protected HashIntIntMapFactory positionMapFactory = HashIntIntMaps.getDefaultFactory().withDefaultValue(-1); // Basic structure {{ private IntArrayList vertices; private PatternEdgeArrayList edges; // K = vertex id, V = vertex position private IntIntMap vertexPositions; // }} // Incremental building {{ private IntArrayList previousWords; // TODO: is it previous or current ? private int numVerticesAddedFromPrevious; private int numAddedEdgesFromPrevious; // }} // Isomorphisms {{ private VertexPositionEquivalences vertexPositionEquivalences; private IntIntMap canonicalLabelling; // }} // Others {{ private transient final MainGraph mainGraph; private PatternEdgePool patternEdgePool; protected volatile boolean dirtyVertexPositionEquivalences; protected volatile boolean dirtyCanonicalLabelling; protected IntCollectionAddConsumer intAddConsumer = new IntCollectionAddConsumer(); // }} public BasicPattern() { mainGraph = Configuration.get().getMainGraph(); patternEdgePool = PatternEdgePool.instance(); vertices = new IntArrayList(); edges = createPatternEdgeArrayList(); vertexPositions = positionMapFactory.newMutableMap(); previousWords = new IntArrayList(); init(); } public BasicPattern(BasicPattern basicPattern) { this(); intAddConsumer.setCollection(vertices); basicPattern.vertices.forEach(intAddConsumer); edges.ensureCapacity(basicPattern.edges.size()); for (PatternEdge otherEdge : basicPattern.edges) { edges.add(createPatternEdge(otherEdge)); } vertexPositions.putAll(basicPattern.vertexPositions); } protected void init() { reset(); } @Override public void reset() { vertices.clear(); patternEdgePool.reclaimObjects(edges); edges.clear(); vertexPositions.clear(); setDirty(); resetIncremental(); } private void resetIncremental() { numVerticesAddedFromPrevious = 0; numAddedEdgesFromPrevious = 0; previousWords.clear(); } @Override public void setEmbedding(Embedding embedding) { try { if (canDoIncremental(embedding)) { setEmbeddingIncremental(embedding); } else { setEmbeddingFromScratch(embedding); } } catch (RuntimeException e) { LOG.error("Embedding: " + embedding); throw e; } } /** * Reset everything and do everything from scratch. * * @param embedding */ private void setEmbeddingFromScratch(Embedding embedding) { reset(); int numEdgesInEmbedding = embedding.getNumEdges(); int numVerticesInEmbedding = embedding.getNumVertices(); if (numEdgesInEmbedding == 0 && numVerticesInEmbedding == 0) { return; } ensureCanStoreNewVertices(numVerticesInEmbedding); ensureCanStoreNewEdges(numEdgesInEmbedding); IntArrayList embeddingVertices = embedding.getVertices(); for (int i = 0; i < numVerticesInEmbedding; ++i) { addVertex(embeddingVertices.getUnchecked(i)); } numVerticesAddedFromPrevious = embedding.getNumVerticesAddedWithExpansion(); IntArrayList embeddingEdges = embedding.getEdges(); for (int i = 0; i < numEdgesInEmbedding; ++i) { addEdge(embeddingEdges.getUnchecked(i)); } numAddedEdgesFromPrevious = embedding.getNumEdgesAddedWithExpansion(); updateUsedEmbeddingFromScratch(embedding); } private void updateUsedEmbeddingFromScratch(Embedding embedding) { previousWords.clear(); int embeddingNumWords = embedding.getNumWords(); previousWords.ensureCapacity(embeddingNumWords); IntArrayList words = embedding.getWords(); for (int i = 0; i < embeddingNumWords; i++) { previousWords.add(words.getUnchecked(i)); } } private void resetToPrevious() { removeLastNEdges(numAddedEdgesFromPrevious); removeLastNVertices(numVerticesAddedFromPrevious); setDirty(); } private void removeLastNEdges(int n) { int targetI = edges.size() - n; for (int i = edges.size() - 1; i >= targetI; --i) { patternEdgePool.reclaimObject(edges.remove(i)); } } private void removeLastNVertices(int n) { int targetI = vertices.size() - n; for (int i = vertices.size() - 1; i >= targetI; --i) { try { vertexPositions.remove(vertices.getUnchecked(i)); } catch (IllegalArgumentException e) { System.err.println(e.toString()); System.err.println("i=" + i); System.err.println("targetI=" + targetI); throw e; } } vertices.removeLast(n); } /** * Only the last word has changed, so skipped processing for the previous vertices. * * @param embedding */ private void setEmbeddingIncremental(Embedding embedding) { resetToPrevious(); numVerticesAddedFromPrevious = embedding.getNumVerticesAddedWithExpansion(); numAddedEdgesFromPrevious = embedding.getNumEdgesAddedWithExpansion(); ensureCanStoreNewVertices(numVerticesAddedFromPrevious); ensureCanStoreNewEdges(numAddedEdgesFromPrevious); IntArrayList embeddingVertices = embedding.getVertices(); int numVerticesInEmbedding = embedding.getNumVertices(); for (int i = (numVerticesInEmbedding - numVerticesAddedFromPrevious); i < numVerticesInEmbedding; ++i) { addVertex(embeddingVertices.getUnchecked(i)); } IntArrayList embeddingEdges = embedding.getEdges(); int numEdgesInEmbedding = embedding.getNumEdges(); for (int i = (numEdgesInEmbedding - numAddedEdgesFromPrevious); i < numEdgesInEmbedding; ++i) { addEdge(embeddingEdges.getUnchecked(i)); } updateUsedEmbeddingIncremental(embedding); } /** * By default only the last word changed. * * @param embedding */ private void updateUsedEmbeddingIncremental(Embedding embedding) { previousWords.setUnchecked(previousWords.size() - 1, embedding.getWords().getUnchecked(previousWords.size() - 1)); } private void ensureCanStoreNewEdges(int numAddedEdgesFromPrevious) { int newNumEdges = edges.size() + numAddedEdgesFromPrevious; edges.ensureCapacity(newNumEdges); } private void ensureCanStoreNewVertices(int numVerticesAddedFromPrevious) { int newNumVertices = vertices.size() + numVerticesAddedFromPrevious; vertices.ensureCapacity(newNumVertices); vertexPositions.ensureCapacity(newNumVertices); } /** * Can do incremental only if the last word is different. * * @param embedding * @return */ private boolean canDoIncremental(Embedding embedding) { if (embedding.getNumWords() == 0 || previousWords.size() != embedding.getNumWords()) { return false; } // Maximum we want 1 change (which we know by default that it exists in the last position). // so we check final IntArrayList words = embedding.getWords(); for (int i = previousWords.size() - 2; i >= 0; i--) { if (words.getUnchecked(i) != previousWords.getUnchecked(i)) { return false; } } return true; } @Override public int getNumberOfVertices() { return vertices.getSize(); } @Override public boolean addEdge(int edgeId) { Edge edge = mainGraph.getEdge(edgeId); return addEdge(edge); } public boolean addEdge(Edge edge) { int srcId = edge.getSourceId(); int srcPos = addVertex(srcId); int dstPos = addVertex(edge.getDestinationId()); PatternEdge patternEdge = createPatternEdge(edge, srcPos, dstPos, srcId); return addEdge(patternEdge); } public boolean addEdge(PatternEdge edge) { // TODO: Remove when we have directed edges if (edge.getSrcPos() > edge.getDestPos()) { edge.invert(); } edges.add(edge); setDirty(); return true; } public int addVertex(int vertexId) { int pos = vertexPositions.get(vertexId); if (pos == -1) { pos = vertices.size(); vertices.add(vertexId); vertexPositions.put(vertexId, pos); setDirty(); } return pos; } protected void setDirty() { dirtyCanonicalLabelling = true; dirtyVertexPositionEquivalences = true; } @Override public int getNumberOfEdges() { return edges.size(); } @Override public IntArrayList getVertices() { return vertices; } @Override public PatternEdgeArrayList getEdges() { return edges; } @Override public VertexPositionEquivalences getVertexPositionEquivalences() { if (dirtyVertexPositionEquivalences) { synchronized (this) { if (dirtyVertexPositionEquivalences) { if (vertexPositionEquivalences == null) { vertexPositionEquivalences = new VertexPositionEquivalences(); } vertexPositionEquivalences.setNumVertices(getNumberOfVertices()); vertexPositionEquivalences.clear(); fillVertexPositionEquivalences(vertexPositionEquivalences); dirtyVertexPositionEquivalences = false; } } } return vertexPositionEquivalences; } protected abstract void fillVertexPositionEquivalences(VertexPositionEquivalences vertexPositionEquivalences); @Override public IntIntMap getCanonicalLabeling() { if (dirtyCanonicalLabelling) { synchronized (this) { if (dirtyCanonicalLabelling) { if (canonicalLabelling == null) { canonicalLabelling = HashIntIntMaps.newMutableMap(getNumberOfVertices()); } canonicalLabelling.clear(); fillCanonicalLabelling(canonicalLabelling); dirtyCanonicalLabelling = false; } } } return canonicalLabelling; } protected abstract void fillCanonicalLabelling(IntIntMap canonicalLabelling); @Override public boolean turnCanonical() { resetIncremental(); IntIntMap canonicalLabelling = getCanonicalLabeling(); IntIntCursor canonicalLabellingCursor = canonicalLabelling.cursor(); boolean allEqual = true; while (canonicalLabellingCursor.moveNext()) { int oldPos = canonicalLabellingCursor.key(); int newPos = canonicalLabellingCursor.value(); if (oldPos != newPos) { allEqual = false; } } if (allEqual) { edges.sort(); return false; } IntArrayList oldVertices = new IntArrayList(vertices); for (int i = 0; i < vertices.size(); ++i) { int newPos = canonicalLabelling.get(i); // If position didn't change, do nothing if (newPos == i) { continue; } int vertexId = oldVertices.getUnchecked(i); vertices.setUnchecked(newPos, vertexId); vertexPositions.put(vertexId, newPos); } for (int i = 0; i < edges.size(); ++i) { PatternEdge edge = edges.get(i); int srcPos = edge.getSrcPos(); int dstPos = edge.getDestPos(); int convertedSrcPos = canonicalLabelling.get(srcPos); int convertedDstPos = canonicalLabelling.get(dstPos); if (convertedSrcPos < convertedDstPos) { edge.setSrcPos(convertedSrcPos); edge.setDestPos(convertedDstPos); } else { // If we changed the position of source and destination due to // relabel, we also have to change the labels to match this // change. int tmp = edge.getSrcLabel(); edge.setSrcPos(convertedDstPos); edge.setSrcLabel(edge.getDestLabel()); edge.setDestPos(convertedSrcPos); edge.setDestLabel(tmp); } } edges.sort(); return true; } @Override public void write(DataOutput dataOutput) throws IOException { edges.write(dataOutput); vertices.write(dataOutput); } @Override public void writeExternal(ObjectOutput objOutput) throws IOException { write (objOutput); } @Override public void readFields(DataInput dataInput) throws IOException { reset(); edges.readFields(dataInput); vertices.readFields(dataInput); for (int i = 0; i < vertices.size(); ++i) { vertexPositions.put(vertices.getUnchecked(i), i); } } @Override public void readExternal(ObjectInput objInput) throws IOException, ClassNotFoundException { readFields(objInput); } protected PatternEdgeArrayList createPatternEdgeArrayList() { return new PatternEdgeArrayList(); } protected PatternEdge createPatternEdge(Edge edge, int srcPos, int dstPos, int srcId) { PatternEdge patternEdge = patternEdgePool.createObject(); patternEdge.setFromEdge(edge, srcPos, dstPos, srcId); return patternEdge; } protected PatternEdge createPatternEdge(PatternEdge otherEdge) { PatternEdge patternEdge = patternEdgePool.createObject(); patternEdge.setFromOther(otherEdge); return patternEdge; } @Override public String toString() { return toOutputString(); } @Override public String toOutputString() { if (getNumberOfEdges() > 0) { return StringUtils.join(edges, ","); } else if (getNumberOfVertices() == 1) { Vertex vertex = mainGraph.getVertex(vertices.getUnchecked(0)); return "0(" + vertex.getVertexLabel() + ")"; } else { return ""; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BasicPattern that = (BasicPattern) o; return edges.equals(that.edges); } public boolean equals(Object o, int upTo) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BasicPattern that = (BasicPattern) o; if (this.getNumberOfEdges() < upTo || that.getNumberOfEdges() < upTo) return false; PatternEdgeArrayList otherEdges = that.getEdges(); for (int i = 0; i < upTo; i++) { if (!edges.getUnchecked(i).equals (otherEdges.getUnchecked(i))) return false; } return true; } @Override public int hashCode() { // TODO return //edges.isEmpty() ? mainGraph.getVertex(vertices.getUnchecked(0)).getVertexLabel() : edges.hashCode(); } public MainGraph getMainGraph() { return mainGraph; } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisfirehose.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The stream and role Amazon Resource Names (ARNs) for a Kinesis data stream used as the source for a delivery stream. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/KinesisStreamSourceConfiguration" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class KinesisStreamSourceConfiguration implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ARN of the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. * </p> */ private String kinesisStreamARN; /** * <p> * The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS Identity and * Access Management (IAM) ARN Format</a>. * </p> */ private String roleARN; /** * <p> * The ARN of the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. * </p> * * @param kinesisStreamARN * The ARN of the source Kinesis data stream. For more information, see <a href= * "https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. */ public void setKinesisStreamARN(String kinesisStreamARN) { this.kinesisStreamARN = kinesisStreamARN; } /** * <p> * The ARN of the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. * </p> * * @return The ARN of the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. */ public String getKinesisStreamARN() { return this.kinesisStreamARN; } /** * <p> * The ARN of the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. * </p> * * @param kinesisStreamARN * The ARN of the source Kinesis data stream. For more information, see <a href= * "https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kinesis-streams" * >Amazon Kinesis Data Streams ARN Format</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public KinesisStreamSourceConfiguration withKinesisStreamARN(String kinesisStreamARN) { setKinesisStreamARN(kinesisStreamARN); return this; } /** * <p> * The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS Identity and * Access Management (IAM) ARN Format</a>. * </p> * * @param roleARN * The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS * Identity and Access Management (IAM) ARN Format</a>. */ public void setRoleARN(String roleARN) { this.roleARN = roleARN; } /** * <p> * The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS Identity and * Access Management (IAM) ARN Format</a>. * </p> * * @return The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS * Identity and Access Management (IAM) ARN Format</a>. */ public String getRoleARN() { return this.roleARN; } /** * <p> * The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS Identity and * Access Management (IAM) ARN Format</a>. * </p> * * @param roleARN * The ARN of the role that provides access to the source Kinesis data stream. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam">AWS * Identity and Access Management (IAM) ARN Format</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public KinesisStreamSourceConfiguration withRoleARN(String roleARN) { setRoleARN(roleARN); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getKinesisStreamARN() != null) sb.append("KinesisStreamARN: ").append(getKinesisStreamARN()).append(","); if (getRoleARN() != null) sb.append("RoleARN: ").append(getRoleARN()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof KinesisStreamSourceConfiguration == false) return false; KinesisStreamSourceConfiguration other = (KinesisStreamSourceConfiguration) obj; if (other.getKinesisStreamARN() == null ^ this.getKinesisStreamARN() == null) return false; if (other.getKinesisStreamARN() != null && other.getKinesisStreamARN().equals(this.getKinesisStreamARN()) == false) return false; if (other.getRoleARN() == null ^ this.getRoleARN() == null) return false; if (other.getRoleARN() != null && other.getRoleARN().equals(this.getRoleARN()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKinesisStreamARN() == null) ? 0 : getKinesisStreamARN().hashCode()); hashCode = prime * hashCode + ((getRoleARN() == null) ? 0 : getRoleARN().hashCode()); return hashCode; } @Override public KinesisStreamSourceConfiguration clone() { try { return (KinesisStreamSourceConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisfirehose.model.transform.KinesisStreamSourceConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/** * MappingFrame.java * * This file was generated by MapForce 2017sp2. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the MapForce Documentation for further details. * http://www.altova.com/mapforce */ package com.mapforce; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import com.altova.types.*; public class MappingFrame extends JFrame implements com.altova.TraceTarget { java.util.Hashtable<String,String> mapArguments = new java.util.Hashtable<String,String>(); JPanel contentPane; TitledBorder titledBorder1; Box jHeader = new Box(BoxLayout.X_AXIS); Box jHeaderInfo = new Box(BoxLayout.Y_AXIS); Box jButtonPane = new Box(BoxLayout.X_AXIS); JScrollPane jScrollPaneStructures = new JScrollPane(); JPanel jPanelStructures = new JPanel(); JLabel jIconLabel = new JLabel(); JLabel jInfoLabel1 = new JLabel(); JLabel jInfoLabel2 = new JLabel(); JLabel jInfoLabel3 = new JLabel(); JButton jStartButton = new JButton(); JPanel jPanel1 = new JPanel(); JScrollPane jTraceScrollPane = new JScrollPane(); JTextArea jTraceTextArea = new JTextArea(); JLabel jinputLabel0 = new JLabel(); JTextField jinputTextField0 = new JTextField(); JLabel jINVOIC_D14B_ISO206252Label1 = new JLabel(); JTextField jINVOIC_D14B_ISO206252TextField1 = new JTextField(); public MappingFrame() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { jInfoLabel1.setText("THIS APPLICATION WAS GENERATED BY MapForce 2017sp2"); jInfoLabel2.setForeground(Color.blue); jInfoLabel2.setText("http://www.altova.com/mapforce"); jInfoLabel3.setText("Please check the input and output files, and press the Start button..."); jHeaderInfo.add(jInfoLabel1,0); jHeaderInfo.add(jInfoLabel2,1); jHeaderInfo.add(jInfoLabel3,2); jIconLabel.setIcon(new ImageIcon(MappingFrame.class.getResource("mapforce.png"))); jIconLabel.setText(""); jHeader.add(jIconLabel); jHeader.add(Box.createHorizontalStrut(15)); jHeader.add(jHeaderInfo); jHeader.add(Box.createGlue()); jStartButton.setFont(new java.awt.Font("Dialog", 0, 11)); jStartButton.setText("Start"); jStartButton.addActionListener(new MappingFrame_jStartButton_actionAdapter(this)); jButtonPane.add(Box.createHorizontalStrut(5)); jButtonPane.add(jStartButton); jButtonPane.add(Box.createGlue()); jScrollPaneStructures.setBorder(BorderFactory.createLineBorder(Color.black)); jScrollPaneStructures.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jScrollPaneStructures.setAutoscrolls(true); jPanelStructures.setLayout(null); fillScrollPane(); jScrollPaneStructures.getViewport().add(jPanelStructures, null); jTraceTextArea.setBackground(Color.white); jTraceTextArea.setForeground(Color.black); jTraceTextArea.setToolTipText(""); jTraceTextArea.setText(""); jTraceTextArea.setRows(20); jTraceScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jTraceScrollPane.setViewportBorder(null); jTraceScrollPane.setAutoscrolls(true); jTraceScrollPane.setBorder(BorderFactory.createLineBorder(Color.black)); jTraceScrollPane.setDebugGraphicsOptions(0); jTraceScrollPane.setToolTipText(""); jTraceScrollPane.setVerifyInputWhenFocusTarget(true); jTraceScrollPane.getViewport().add(jTraceTextArea, null); jTraceScrollPane.setPreferredSize(new Dimension(0, 200)); contentPane = (JPanel)this.getContentPane(); titledBorder1 = new TitledBorder(""); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); this.setSize(new Dimension(603, 511)); this.setTitle("Mapforce Application"); contentPane.add(jHeader, 0); contentPane.add(jScrollPaneStructures, 1); contentPane.add(jButtonPane, 2); contentPane.add(jTraceScrollPane, 3); } protected void fillScrollPane() { jinputLabel0.setText("Input Parameter : input"); jinputLabel0.setBounds(new Rectangle(15, 10, 438, 23)); jPanelStructures.add(jinputLabel0, null); jinputTextField0.setText("" ); jinputTextField0.setBounds(new Rectangle(15, 35, 438, 23)); jinputTextField0.setEditable(true); jinputTextField0.addKeyListener(new MappingFrame_jinputTextField0_keyAdapter( this ) ); jPanelStructures.add(jinputTextField0, null); jINVOIC_D14B_ISO206252Label1.setText("Instance of INVOIC_D14B_ISO20625.xsd:"); jINVOIC_D14B_ISO206252Label1.setBounds(new Rectangle(15, 60, 438, 23)); jPanelStructures.add(jINVOIC_D14B_ISO206252Label1, null); jINVOIC_D14B_ISO206252TextField1.setText("C:/GEFEG/Repositories/vda/Daten f\u00fcr XMLEDI/INVOIC_D14B_ISO20625.xml"); jINVOIC_D14B_ISO206252TextField1.setBounds(new Rectangle(15, 85, 438, 23)); jINVOIC_D14B_ISO206252TextField1.setEditable(false); jPanelStructures.add(jINVOIC_D14B_ISO206252TextField1, null); jPanelStructures.setLayout(null); jPanelStructures.setPreferredSize(new Dimension(85, 500)); jPanelStructures.setSize(new Dimension(85, 500)); jPanelStructures.setMinimumSize(new Dimension(85, 500)); jPanelStructures.setMaximumSize(new Dimension(85, 500)); } protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } void jStartButton_actionPerformed(ActionEvent e) { if (e.getSource().equals(jStartButton)) { jStartButton.setEnabled(false); jTraceTextArea.removeAll(); jTraceTextArea.append("Started...\n"); com.altova.TraceTarget ttc = this; try { MappingMapToINVOIC_D14B_ISO20625 MappingMapToINVOIC_D14B_ISO20625Object = new MappingMapToINVOIC_D14B_ISO20625(); MappingMapToINVOIC_D14B_ISO20625Object.registerTraceTarget(ttc); // run mapping // // you have different options to provide mapping input and output: // // files using file names (available for XML, text, and Excel): // com.altova.io.FileInput(String filename) // com.altova.io.FileOutput(String filename) // // streams (available for XML, text, and Excel): // com.altova.io.StreamInput(java.io.InputStream stream) // com.altova.io.StreamOutput(java.io.OutputStream stream) // // strings (available for XML and text): // com.altova.io.StringInput(String xmlcontent) // com.altova.io.StringOutput() (call getContent() after run() to get StringBuffer with content) // // Java IO reader/writer (available for XML and text): // com.altova.io.ReaderInput(java.io.Reader reader) // com.altova.io.WriterOutput(java.io.Writer writer) // // DOM documents (for XML only): // com.altova.io.DocumentInput(org.w3c.dom.Document document) // com.altova.io.DocumentOutput(org.w3c.dom.Document document) // // By default, run will close all inputs and outputs. If you do not want this, // call the following function: // MappingMapToINVOIC_D14B_ISO20625Object.setCloseObjectsAfterRun(false); { MappingMapToINVOIC_D14B_ISO20625Object.run( ( mapArguments.containsKey("input") ? com.altova.CoreTypes.castToString(mapArguments.get("input")): null )); } jTraceTextArea.append("Finished\n"); } catch (Exception ex) { jTraceTextArea.append("ERROR: " + ex.getMessage()); } jStartButton.setEnabled(true); } } void jinputTextField0_actionPerformed( KeyEvent e ) { if ( e.getSource().equals( jinputTextField0 ) ) { String value = jinputTextField0.getText(); if( value.length() != 0 ) mapArguments.put( "input", value ); else { if( mapArguments.containsKey( "input" ) ) mapArguments.remove( "input" ); } } } public void writeTrace(String info) { jTraceTextArea.append(info); } } class MappingFrame_jStartButton_actionAdapter implements java.awt.event.ActionListener { MappingFrame adaptee; MappingFrame_jStartButton_actionAdapter(MappingFrame adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.jStartButton_actionPerformed(e); } } class MappingFrame_jinputTextField0_keyAdapter implements java.awt.event.KeyListener { MappingFrame adaptee; MappingFrame_jinputTextField0_keyAdapter( MappingFrame adaptee ) { this.adaptee = adaptee; } public void keyTyped( KeyEvent e ) { adaptee.jinputTextField0_actionPerformed( e ); } public void keyPressed( KeyEvent e ) { adaptee.jinputTextField0_actionPerformed( e ); } public void keyReleased( KeyEvent e ) { adaptee.jinputTextField0_actionPerformed( e ); } }
/* * HE_Mesh Frederik Vanhoutte - www.wblut.com * * https://github.com/wblut/HE_Mesh * A Processing/Java library for for creating and manipulating polygonal meshes. * * Public Domain: http://creativecommons.org/publicdomain/zero/1.0/ */ package wblut.geom; import wblut.math.WB_Epsilon; import wblut.math.WB_HashCode; /** * */ public class WB_Coordinate extends WB_Coordinate2D { /** Coordinates. */ double z; /** * */ public WB_Coordinate() { x = y = z = 0; } /** * * * @param x * @param y */ public WB_Coordinate(final double x, final double y) { this.x = x; this.y = y; z = 0; } /** * * * @param x * @param y * @param z */ public WB_Coordinate(final double x, final double y, final double z) { this.x = x; this.y = y; this.z = z; } /** * * * @param x */ public WB_Coordinate(final double[] x) { if (x.length != 3) { throw new IllegalArgumentException("Array needs to be of length 3."); } this.x = x[0]; this.y = x[1]; this.z = x[2]; } /** * * @param p */ public WB_Coordinate(final WB_Coord p) { x = p.xd(); y = p.yd(); z = p.zd(); } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#getd(int) */ @Override public double getd(final int i) { if (i == 0) { return x; } if (i == 1) { return y; } if (i == 2) { return z; } if (i == 3) { return 0; } return Double.NaN; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#getf(int) */ @Override public float getf(final int i) { if (i == 0) { return (float) x; } if (i == 1) { return (float) y; } if (i == 2) { return (float) z; } if (i == 3) { return 0; } return Float.NaN; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#xd() */ @Override public double xd() { return x; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#yd() */ @Override public double yd() { return y; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#zd() */ @Override public double zd() { return z; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#wd() */ @Override public double wd() { return 0; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#xf() */ @Override public float xf() { return (float) x; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#yf() */ @Override public float yf() { return (float) y; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#zf() */ @Override public float zf() { return (float) z; } /* * (non-Javadoc) * * @see wblut.geom.WB_Coord#wf() */ @Override public float wf() { return 0; } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(final WB_Coord p) { int cmp = Double.compare(xd(), p.xd()); if (cmp != 0) { return cmp; } cmp = Double.compare(yd(), p.yd()); if (cmp != 0) { return cmp; } cmp = Double.compare(zd(), p.zd()); if (cmp != 0) { return cmp; } return Double.compare(wd(), p.wd()); } /** * * * @param p * @return */ @Override public int compareToY1st(final WB_Coord p) { int cmp = Double.compare(yd(), p.yd()); if (cmp != 0) { return cmp; } cmp = Double.compare(xd(), p.xd()); if (cmp != 0) { return cmp; } cmp = Double.compare(zd(), p.zd()); if (cmp != 0) { return cmp; } return Double.compare(wd(), p.wd()); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!(o instanceof WB_Coord)) { return false; } final WB_Coord p = (WB_Coord) o; if (!WB_Epsilon.isEqualAbs(xd(), p.xd())) { return false; } if (!WB_Epsilon.isEqualAbs(yd(), p.yd())) { return false; } if (!WB_Epsilon.isEqualAbs(zd(), p.zd())) { return false; } if (!WB_Epsilon.isEqualAbs(wd(), p.wd())) { return false; } return true; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return WB_HashCode.calculateHashCode(xd(), yd(), zd()); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "WB_SimpleCoordinate [x=" + xd() + ", y=" + yd() + ", z=" + zd() + "]"; } }
package com.suscipio_solutions.siplet.applet; import java.awt.Graphics; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.Socket; import com.suscipio_solutions.siplet.support.TelnetFilter; public class Siplet { public final static boolean debugDataOut=false; public final static long serialVersionUID=7; public static final float VERSION_MAJOR=(float)2.1; public static final long VERSION_MINOR=0; protected StringBuffer buf=new StringBuffer(""); protected String lastURL="consecromud.org"; protected int lastPort=23; protected Socket sock=null; protected InputStream rawin=null; protected BufferedReader[] in; protected DataOutputStream out; protected boolean connected=false; protected TelnetFilter Telnet=new TelnetFilter(this); protected StringBuffer buffer; protected int sillyCounter=0; public enum MSPStatus { Disabled, Internal, External } public void setFeatures(boolean mxp, MSPStatus msp, boolean mccp) { Telnet.setNeverMCCPSupport(!mccp); Telnet.setNeverMXPSupport(!mxp); Telnet.setNeverMSPSupport(msp); } public void init() { buffer = new StringBuffer(); } public String info() { return "Siplet V"+VERSION_MAJOR+"."+VERSION_MINOR+" "; } public void start() { if(debugDataOut) System.out.println("starting siplet "+VERSION_MAJOR+"."+VERSION_MINOR+" "); } public void stop() { if(debugDataOut) System.out.println("!stopped siplet!"); } public void destroy() { } public Siplet create() { return new Siplet();} public void addItem(String newWord) { if(debugDataOut) System.out.println(newWord); buffer.append(newWord); //repaint(); } public void paint(Graphics g) { // uncomment if we go back to being an applet //g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); //g.drawString(buffer.toString(), 5, 15); } public boolean connectToURL(){ return connectToURL(lastURL,lastPort);} public boolean connectToURL(String url, int port) { connected=false; if(sock!=null) disconnectFromURL(); try { lastURL=url; lastPort=port; if(debugDataOut) System.out.println("connecting to "+url+":"+port+" "); sock=new Socket(InetAddress.getByName(url),port); Thread.sleep(100); rawin=sock.getInputStream(); in=new BufferedReader[1]; in[0]=new BufferedReader(new InputStreamReader(sock.getInputStream(),"iso-8859-1")); out=new DataOutputStream(sock.getOutputStream()); Telnet=new TelnetFilter(this); connected=true; } catch(final Exception e) { e.printStackTrace(System.out); return false; } return true; } public boolean connectToURL(String url, int port, Socket sock) { connected=false; if(this.sock!=null) disconnectFromURL(); try { lastURL=url; lastPort=port; if(debugDataOut) System.out.println("internal connect to "+url+":"+port+" "); this.sock=sock; rawin=sock.getInputStream(); in=new BufferedReader[1]; in[0]=new BufferedReader(new InputStreamReader(sock.getInputStream(),"iso-8859-1")); out=new DataOutputStream(sock.getOutputStream()); Telnet=new TelnetFilter(this); connected=true; } catch(final Exception e) { e.printStackTrace(System.out); return false; } return true; } public void disconnectFromURL() { connected=false; try { if(out!=null) { out.write(new byte[]{(byte)255,(byte)253,18}); //iac, iacdo, logout out.flush(); } } catch(final Exception e) { } try { if((in!=null)&&(in[0]!=null)) in[0].close(); } catch(final Exception e) { } try { if(out!=null) out.close(); } catch(final Exception e) { } try { if(sock!=null) sock.close(); } catch(final Exception e) { } in=null; out=null; sock=null; } public void sendData(String data) { if(connected) { try { if(sock.isClosed()) disconnectFromURL(); else if(!sock.isConnected()) disconnectFromURL(); else { final byte[] bytes=Telnet.peruseInput(data); if(bytes!=null) { out.write(bytes); if((bytes.length==0)||((bytes[bytes.length-1]!=13)&&(bytes[bytes.length-1]!=10))) out.writeBytes("\n"); out.flush(); } } } catch(final IOException e) { disconnectFromURL(); } } } public String getJScriptCommands() { return Telnet.getEnquedJScript(); } public String getURLData() { synchronized(buf) { final String s=Telnet.getEnquedResponses(); if(s.length()>0) sendData(s); final StringBuilder data=new StringBuilder(""); if(Telnet.MSDPsupport()) data.append(Telnet.getMsdpHtml()); if(Telnet.GMCPsupport()) data.append(Telnet.getGmcpHtml()); int endAt=Telnet.HTMLFilter(buf); if(buf.length()==0) return data.toString(); if(endAt<0) endAt=buf.length(); if(endAt==0) return data.toString(); if(Telnet.isUIonHold()) return data.toString(); if(endAt<buf.length()) { data.append(buf.substring(0,endAt)); buf.delete(0,endAt); } else { data.append(buf.toString()); buf.setLength(0); } if(debugDataOut) if(data.length()>0) System.out.println("/DATA="+data.toString()); return data.toString(); } } public boolean isConnectedToURL(){return connected;} public void readURLData() { try { while(connected &&in[0].ready() &&(!sock.isClosed()) &&(sock.isConnected())) { try { Telnet.TelnetRead(buf,rawin,in); } catch(final java.io.InterruptedIOException e) { disconnectFromURL(); return; } catch(final Exception e) { if(e instanceof com.jcraft.jzlib.ZStreamException) { disconnectFromURL(); try{Thread.sleep(100);}catch(final Exception e2){} connectToURL(); } else { disconnectFromURL(); return; } } } if(sock.isClosed()) disconnectFromURL(); else if(!sock.isConnected()) disconnectFromURL(); else if(buf.length()>0) Telnet.TelenetFilter(buf,out,rawin,in); } catch(final Exception e) { disconnectFromURL(); return; } } }
/* * ProductFrame.java * * Created on January 1, 2012, 8:13 PM */ package server; import java.awt.*; import java.sql.ResultSet; import javax.swing.JComboBox; import javax.swing.JFrame; /** * * @author mfahim */ public class updateSupplier extends javax.swing.JFrame { /** Creates new form ProductFrame */ public updateSupplier() { initComponents(); this.setTitle(this.getClass().getSimpleName()); this.setIconImage(Toolkit.getDefaultToolkit().getImage("src/images/icon.png")); proCate.removeAllItems(); rs = Category.find_all_category(); try{ while(rs.next()){ proCate.addItem(rs.getString(1)); } }catch(Exception e){ System.out.println("Error :: In Adding items to JComboBox"); } Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle recframe = getBounds(); setLocation((screen.width - recframe.width)/2, (screen.height - recframe.height)/2); } public updateSupplier(JFrame f,String uStatus,String user) { initComponents(); this.setTitle(this.getClass().getSimpleName()); userStatus.setText(uStatus); systemUser.setText(user); this.setIconImage(Toolkit.getDefaultToolkit().getImage("src/images/icon.png")); proCate.removeAllItems(); rs = Category.find_all_category(); try{ while(rs.next()){ proCate.addItem(rs.getString(1)); } }catch(Exception e){ System.out.println("Error :: In Adding items to JComboBox"); } Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle recframe = getBounds(); setLocation((screen.width - recframe.width)/2, (screen.height - recframe.height)/2); frame = new JFrame(); frame = f; f.setVisible(false); f.dispose(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainContent2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); proSize = new javax.swing.JTextField(); proBrand = new javax.swing.JTextField(); proName = new javax.swing.JTextField(); proCate = new javax.swing.JComboBox(); proMan = new javax.swing.JTextField(); proVariety = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); proDes = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); newProCancel = new javax.swing.JButton(); mainContent1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); cateFam = new javax.swing.JTextField(); nameCate = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); subCate = new javax.swing.JTextField(); systemUser = new javax.swing.JToggleButton(); userStatus = new javax.swing.JToggleButton(); mainMenuPanel = new javax.swing.JPanel(); mainMenuJLabel = new javax.swing.JLabel(); mannageOrder = new javax.swing.JButton(); placeOrder = new javax.swing.JButton(); cancelOrder = new javax.swing.JButton(); updateProduct = new javax.swing.JButton(); searchProduct = new javax.swing.JButton(); newSupplier = new javax.swing.JButton(); updateSupplier = new javax.swing.JButton(); searchSupplier = new javax.swing.JButton(); updateStock = new javax.swing.JButton(); newStock = new javax.swing.JButton(); searchStock = new javax.swing.JButton(); newProduct = new javax.swing.JButton(); orderStatus = new javax.swing.JButton(); mannageProduct = new javax.swing.JButton(); mannageSupplier = new javax.swing.JButton(); mannageInventory = new javax.swing.JButton(); titlePanel = new javax.swing.JPanel(); vmLogo = new javax.swing.JLabel(); signOut = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("New Product"); setForeground(java.awt.Color.white); jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); jButton1.setText("Save"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); proCate.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); proCate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { proCateActionPerformed(evt); } }); proVariety.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { proVarietyActionPerformed(evt); } }); proDes.setColumns(20); proDes.setRows(5); jScrollPane1.setViewportView(proDes); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel2.setText("New Product :"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel4.setText("Name : "); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel5.setText("Brand : "); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel6.setText("Manufacture : "); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel7.setText("Size : "); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel8.setText("Category ID : "); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel9.setText("Variety :"); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel10.setText("Description :"); newProCancel.setFont(new java.awt.Font("Tahoma", 1, 11)); newProCancel.setText("Cancel"); newProCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProCancelActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout mainContent2Layout = new org.jdesktop.layout.GroupLayout(mainContent2); mainContent2.setLayout(mainContent2Layout); mainContent2Layout.setHorizontalGroup( mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, mainContent2Layout.createSequentialGroup() .add(28, 28, 28) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel6) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(proSize) .add(proMan) .add(proBrand) .add(proName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 143, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 37, Short.MAX_VALUE) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(jLabel10, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(proCate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(proVariety, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 115, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(mainContent2Layout.createSequentialGroup() .add(53, 53, 53) .add(newProCancel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButton1)) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 192, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(46, 46, 46)) .add(mainContent2Layout.createSequentialGroup() .addContainerGap() .add(jLabel2) .addContainerGap(525, Short.MAX_VALUE)) ); mainContent2Layout.setVerticalGroup( mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainContent2Layout.createSequentialGroup() .add(25, 25, 25) .add(jLabel2) .add(31, 31, 31) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainContent2Layout.createSequentialGroup() .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(proCate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel8)) .add(8, 8, 8) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(proVariety, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel9)) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainContent2Layout.createSequentialGroup() .add(42, 42, 42) .add(jLabel10)) .add(mainContent2Layout.createSequentialGroup() .add(18, 18, 18) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(18, 18, 18) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(newProCancel) .add(jButton1))) .add(mainContent2Layout.createSequentialGroup() .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel4) .add(proName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(8, 8, 8) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(proBrand, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel5)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(proMan, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel6)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainContent2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(proSize, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel7)))) .addContainerGap()) ); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel3.setText("Category Info :"); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel11.setText("Family : "); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel12.setText("Category :"); cateFam.setEditable(false); nameCate.setEditable(false); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); jLabel13.setText("Sub-Category :"); subCate.setEditable(false); subCate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { subCateActionPerformed(evt); } }); systemUser.setBackground(new java.awt.Color(0, 0, 0)); systemUser.setSelected(true); systemUser.setEnabled(false); userStatus.setBackground(new java.awt.Color(0, 0, 0)); userStatus.setSelected(true); userStatus.setEnabled(false); org.jdesktop.layout.GroupLayout mainContent1Layout = new org.jdesktop.layout.GroupLayout(mainContent1); mainContent1.setLayout(mainContent1Layout); mainContent1Layout.setHorizontalGroup( mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainContent1Layout.createSequentialGroup() .add(28, 28, 28) .add(mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(jLabel11, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jLabel12, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(nameCate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 159, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(mainContent1Layout.createSequentialGroup() .add(cateFam, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 159, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(34, 34, 34) .add(jLabel13) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(subCate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 144, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(99, Short.MAX_VALUE)) .add(mainContent1Layout.createSequentialGroup() .addContainerGap() .add(jLabel3) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 279, Short.MAX_VALUE) .add(userStatus) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(systemUser) .add(167, 167, 167)) ); mainContent1Layout.setVerticalGroup( mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainContent1Layout.createSequentialGroup() .add(mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainContent1Layout.createSequentialGroup() .addContainerGap(12, Short.MAX_VALUE) .add(jLabel3) .add(27, 27, 27)) .add(mainContent1Layout.createSequentialGroup() .add(mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(systemUser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(userStatus, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))) .add(mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cateFam, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(subCate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel11) .add(jLabel13)) .add(8, 8, 8) .add(mainContent1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(nameCate, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel12))) ); mainMenuJLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); mainMenuJLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); mainMenuJLabel.setText("Main Menu"); mannageOrder.setBackground(new java.awt.Color(51, 51, 51)); mannageOrder.setFont(new java.awt.Font("Tahoma", 1, 11)); mannageOrder.setText("Mannage Order"); mannageOrder.setEnabled(false); placeOrder.setText("Place Order"); placeOrder.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { placeOrderActionPerformed(evt); } }); cancelOrder.setText("Cancel Order"); cancelOrder.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelOrderActionPerformed(evt); } }); updateProduct.setText("Update Product"); updateProduct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateProductActionPerformed(evt); } }); searchProduct.setText("Search Product"); searchProduct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchProductActionPerformed(evt); } }); newSupplier.setText("New Supplier"); newSupplier.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newSupplierActionPerformed(evt); } }); updateSupplier.setText("Update Supplier"); updateSupplier.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateSupplierActionPerformed(evt); } }); searchSupplier.setText("Search Supplier"); searchSupplier.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchSupplierActionPerformed(evt); } }); updateStock.setText("Update Stock"); updateStock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateStockActionPerformed(evt); } }); newStock.setText("New Stock"); newStock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newStockActionPerformed(evt); } }); searchStock.setText("Search Stock"); searchStock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchStockActionPerformed(evt); } }); newProduct.setText("New Product"); newProduct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProductActionPerformed(evt); } }); orderStatus.setText("Order Status"); orderStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderStatusActionPerformed(evt); } }); mannageProduct.setBackground(new java.awt.Color(51, 51, 51)); mannageProduct.setFont(new java.awt.Font("Tahoma", 1, 11)); mannageProduct.setText("Mannage Product"); mannageProduct.setEnabled(false); mannageSupplier.setBackground(new java.awt.Color(51, 51, 51)); mannageSupplier.setFont(new java.awt.Font("Tahoma", 1, 11)); mannageSupplier.setText("Mannage Supplier"); mannageSupplier.setEnabled(false); mannageInventory.setBackground(new java.awt.Color(51, 51, 51)); mannageInventory.setFont(new java.awt.Font("Tahoma", 1, 11)); mannageInventory.setText("Mannage Inventory"); mannageInventory.setEnabled(false); org.jdesktop.layout.GroupLayout mainMenuPanelLayout = new org.jdesktop.layout.GroupLayout(mainMenuPanel); mainMenuPanel.setLayout(mainMenuPanelLayout); mainMenuPanelLayout.setHorizontalGroup( mainMenuPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainMenuPanelLayout.createSequentialGroup() .addContainerGap() .add(mainMenuPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mannageOrder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(placeOrder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, searchStock, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(updateStock, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(newStock, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(searchSupplier, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(updateSupplier, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(newSupplier, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, searchProduct, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(updateProduct, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(newProduct, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(cancelOrder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, mainMenuJLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(mannageSupplier, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, mannageInventory, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, mannageProduct, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE) .add(orderStatus, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)) .addContainerGap()) ); mainMenuPanelLayout.setVerticalGroup( mainMenuPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainMenuPanelLayout.createSequentialGroup() .add(17, 17, 17) .add(mainMenuJLabel) .add(18, 18, 18) .add(mannageOrder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(4, 4, 4) .add(placeOrder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cancelOrder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(orderStatus, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(mannageProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(newProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(updateProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(searchProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mannageSupplier, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(newSupplier, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(updateSupplier, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(searchSupplier, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mannageInventory, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(newStock, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(updateStock, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(searchStock, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); vmLogo.setFont(new java.awt.Font("Times New Roman", 3, 24)); vmLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); vmLogo.setText("Value Mart"); signOut.setBackground(new java.awt.Color(0, 0, 0)); signOut.setFont(new java.awt.Font("Tahoma", 1, 11)); signOut.setForeground(new java.awt.Color(255, 255, 255)); signOut.setText("Sign Out"); signOut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { signOutActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout titlePanelLayout = new org.jdesktop.layout.GroupLayout(titlePanel); titlePanel.setLayout(titlePanelLayout); titlePanelLayout.setHorizontalGroup( titlePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(titlePanelLayout.createSequentialGroup() .add(vmLogo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 466, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(signOut) .addContainerGap(39, Short.MAX_VALUE)) ); titlePanelLayout.setVerticalGroup( titlePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(titlePanelLayout.createSequentialGroup() .addContainerGap() .add(titlePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(vmLogo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE) .add(signOut))) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(mainMenuPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(mainContent1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.LEADING, mainContent2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(205, Short.MAX_VALUE) .add(titlePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(57, 57, 57) .add(mainContent1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainContent2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(mainMenuPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(titlePanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(387, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Product p = new Product(); p.set_product_name(proName.getText()); p.set_product_brand(proBrand.getText()); p.set_product_manufacture(proMan.getText()); p.set_size(proSize.getText()); p.set_variety(proVariety.getText()); JComboBox cb = (JComboBox)evt.getSource(); String cateID = (String)cb.getSelectedItem(); p.set_category_id(Integer.parseInt(cateID)); p.set_product_description(proDes.getText()); p.insert_product(); }//GEN-LAST:event_jButton1ActionPerformed private void proVarietyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proVarietyActionPerformed // TODO add your handling code here: }//GEN-LAST:event_proVarietyActionPerformed private void subCateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_subCateActionPerformed // TODO add your handling code here: }//GEN-LAST:event_subCateActionPerformed private void proCateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proCateActionPerformed JComboBox cb = (JComboBox)evt.getSource(); String getCate = (String)cb.getSelectedItem(); try{ rsCate = Category.quick_find_category(getCate); while(rsCate.next()){ cateFam.setText(rsCate.getString("family")); subCate.setText(rsCate.getString("subcategory")); nameCate.setText(rsCate.getString("category_name")); } }catch(Exception e){ System.out.println("Error :: Category not Found."); } }//GEN-LAST:event_proCateActionPerformed private void signOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_signOutActionPerformed choiceFrame cFrame = new choiceFrame(this); cFrame.setVisible(true); }//GEN-LAST:event_signOutActionPerformed private void newProCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProCancelActionPerformed proName.setText(""); proBrand.setText(""); proMan.setText(""); proSize.setText(""); proVariety.setText(""); proCate.setAutoscrolls(true); proDes.setText(""); }//GEN-LAST:event_newProCancelActionPerformed private void searchSupplierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchSupplierActionPerformed searchSupplier sSupFrame = new searchSupplier(this,userStatus.getText(),systemUser.getText()); sSupFrame.setVisible(true); }//GEN-LAST:event_searchSupplierActionPerformed private void placeOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_placeOrderActionPerformed placeOrder pOrderFrame = new placeOrder(this,userStatus.getText(),systemUser.getText()); pOrderFrame.setVisible(true); }//GEN-LAST:event_placeOrderActionPerformed private void cancelOrderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelOrderActionPerformed cancelOrder cOrderFrame = new cancelOrder(this,userStatus.getText(),systemUser.getText()); cOrderFrame.setVisible(true); }//GEN-LAST:event_cancelOrderActionPerformed private void orderStatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderStatusActionPerformed orderStatus sOrderFrame = new orderStatus(this,userStatus.getText(),systemUser.getText()); sOrderFrame.setVisible(true); }//GEN-LAST:event_orderStatusActionPerformed private void newProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProductActionPerformed updateSupplier nProFrame = new updateSupplier(this,userStatus.getText(),systemUser.getText()); nProFrame.setVisible(true); }//GEN-LAST:event_newProductActionPerformed private void updateProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateProductActionPerformed updateProduct uProFrame = new updateProduct(this,userStatus.getText(),systemUser.getText()); uProFrame.setVisible(true); }//GEN-LAST:event_updateProductActionPerformed private void searchProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchProductActionPerformed searchProduct sProFrame = new searchProduct(this,userStatus.getText(),systemUser.getText()); sProFrame.setVisible(true); }//GEN-LAST:event_searchProductActionPerformed private void newSupplierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newSupplierActionPerformed updateSupplier nSupFrame = new updateSupplier(this,userStatus.getText(),systemUser.getText()); nSupFrame.setVisible(true); }//GEN-LAST:event_newSupplierActionPerformed private void updateSupplierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSupplierActionPerformed updateSupplier uSupFrame = new updateSupplier(this,userStatus.getText(),systemUser.getText()); uSupFrame.setVisible(true); }//GEN-LAST:event_updateSupplierActionPerformed private void newStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newStockActionPerformed newStock nStockFrame = new newStock(this,userStatus.getText(),systemUser.getText()); nStockFrame.setVisible(true); }//GEN-LAST:event_newStockActionPerformed private void updateStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateStockActionPerformed updateStock uStockFrame = new updateStock(this,userStatus.getText(),systemUser.getText()); uStockFrame.setVisible(true); }//GEN-LAST:event_updateStockActionPerformed private void searchStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchStockActionPerformed searchStock sStockFrame = new searchStock(this,userStatus.getText(),systemUser.getText()); sStockFrame.setVisible(true); }//GEN-LAST:event_searchStockActionPerformed private JFrame frame; private ResultSet rs ; private ResultSet rsCate ; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelOrder; private javax.swing.JTextField cateFam; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPanel mainContent1; private javax.swing.JPanel mainContent2; private javax.swing.JLabel mainMenuJLabel; private javax.swing.JPanel mainMenuPanel; private javax.swing.JButton mannageInventory; private javax.swing.JButton mannageOrder; private javax.swing.JButton mannageProduct; private javax.swing.JButton mannageSupplier; private javax.swing.JTextField nameCate; private javax.swing.JButton newProCancel; private javax.swing.JButton newProduct; private javax.swing.JButton newStock; private javax.swing.JButton newSupplier; private javax.swing.JButton orderStatus; private javax.swing.JButton placeOrder; private javax.swing.JTextField proBrand; private javax.swing.JComboBox proCate; private javax.swing.JTextArea proDes; private javax.swing.JTextField proMan; private javax.swing.JTextField proName; private javax.swing.JTextField proSize; private javax.swing.JTextField proVariety; private javax.swing.JButton searchProduct; private javax.swing.JButton searchStock; private javax.swing.JButton searchSupplier; private javax.swing.JButton signOut; private javax.swing.JTextField subCate; private javax.swing.JToggleButton systemUser; private javax.swing.JPanel titlePanel; private javax.swing.JButton updateProduct; private javax.swing.JButton updateStock; private javax.swing.JButton updateSupplier; private javax.swing.JToggleButton userStatus; private javax.swing.JLabel vmLogo; // End of variables declaration//GEN-END:variables }
package yourbay.me.castimages.cast; import android.content.Context; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.MediaRouteActionProvider; import android.support.v7.media.MediaRouteSelector; import android.support.v7.media.MediaRouter; import android.util.Log; import android.view.MenuItem; import com.google.android.gms.cast.Cast; import com.google.android.gms.cast.CastDevice; import com.google.android.gms.cast.CastMediaControlIntent; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import java.io.IOException; /** * Created by ram on 15/1/7. */ public class CastHelper { private final static String TAG = "CastHelper"; private boolean IS_DEBUG_MODE = true; private MediaRouter mMediaRouter; private MediaRouteSelector mMediaRouteSelector; private CastDevice mSelectedDevice; private CastRouterCallback mMediaRouterCallback = new CastRouterCallback(); private GoogleApiClient mApiClient; private Cast.Listener mCastClientListener = new Cast.Listener() { @Override public void onApplicationStatusChanged() { if (IS_DEBUG_MODE) { Log.d(TAG, "onApplicationStatusChanged: " + (mApiClient != null ? Cast.CastApi.getApplicationStatus(mApiClient) : "")); } } @Override public void onVolumeChanged() { if (IS_DEBUG_MODE) { Log.d(TAG, "onVolumeChanged: " + (mApiClient != null ? Cast.CastApi.getVolume(mApiClient) : "")); } } @Override public void onApplicationDisconnected(int errorCode) { if (IS_DEBUG_MODE) { Log.d(TAG, "onApplicationDisconnected: " + errorCode); } teardown(); } }; private String mSessionId; private boolean mApplicationStarted; private boolean mWaitingForReconnect; private ConnectionCallbacks mConnectionCallbacks = new ConnectionCallbacks(); private ConnectionFailedListener mConnectionFailedListener = new ConnectionFailedListener(); private HelloWorldChannel mHelloWorldChannel; private Context mContext; public CastHelper(Context context) { mContext = context; mMediaRouter = MediaRouter.getInstance(context); mMediaRouteSelector = new MediaRouteSelector.Builder().addControlCategory(CastMediaControlIntent.categoryForCast(Consts.APP_ID)).build(); if (IS_DEBUG_MODE) { Log.d(TAG, "onCreate " + mMediaRouter + " " + mMediaRouteSelector); } } private void onDeviceSelected() { if (IS_DEBUG_MODE) { Log.d(TAG, "onDeviceSelected"); } Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(mSelectedDevice, mCastClientListener); mApiClient = new GoogleApiClient.Builder(mContext)// .addApi(Cast.API, apiOptionsBuilder.build())// .addConnectionCallbacks(mConnectionCallbacks)// .addOnConnectionFailedListener(mConnectionFailedListener)// .build(); mApiClient.connect(); } private void launchReceiverApp() { if (mApiClient == null) { return; } Cast.CastApi.launchApplication(mApiClient, Consts.APP_ID, true).setResultCallback(new ResultCallback<Cast.ApplicationConnectionResult>() { @Override public void onResult(Cast.ApplicationConnectionResult result) { Status status = result.getStatus(); if (IS_DEBUG_MODE) { Log.d(TAG, "launchReceiverApp onResult=" + status.isSuccess() + " StatusCode=" + status.getStatusCode() + " StatusMessage=" + status.getStatusMessage()); } if (status.isSuccess()) { mApplicationStarted = true; mHelloWorldChannel = new HelloWorldChannel(); try { Cast.CastApi.setMessageReceivedCallbacks(mApiClient, mHelloWorldChannel.getNamespace(), mHelloWorldChannel); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Exception while creating channel", e); } } else { teardown(); } } }); } private void reconnectReceiverApp(Bundle connectionHint) { if ((connectionHint != null) && connectionHint.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING)) { if (IS_DEBUG_MODE) { Log.d(TAG, "App is no longer running"); } teardown(); } else { if (IS_DEBUG_MODE) { Log.d(TAG, "Re-create the custom message channel"); } try { Cast.CastApi.setMessageReceivedCallbacks(mApiClient, mHelloWorldChannel.getNamespace(), mHelloWorldChannel); } catch (IOException e) { Log.e(TAG, "Exception while creating channel", e); } } } private void teardown() { if (IS_DEBUG_MODE) { Log.d(TAG, "teardown"); } if (mApiClient != null) { if (mApplicationStarted) { if (mApiClient.isConnected() || mApiClient.isConnecting()) { try { Cast.CastApi.stopApplication(mApiClient, mSessionId); if (mHelloWorldChannel != null) { Cast.CastApi.removeMessageReceivedCallbacks(mApiClient, mHelloWorldChannel.getNamespace()); mHelloWorldChannel = null; } } catch (IOException e) { Log.e(TAG, "Exception while removing channel", e); } mApiClient.disconnect(); } mApplicationStarted = false; } mApiClient = null; } mSelectedDevice = null; mWaitingForReconnect = false; } public void onCreateOptionsMenu(MenuItem item) { MediaRouteActionProvider mProvider = (MediaRouteActionProvider) MenuItemCompat.getActionProvider(item); mProvider.setRouteSelector(mMediaRouteSelector); } public void start() { mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN); } public void stop() { mMediaRouter.removeCallback(mMediaRouterCallback); } public GoogleApiClient getApiClient() { return mApiClient; } private class CastRouterCallback extends MediaRouter.Callback { @Override public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) { mSelectedDevice = CastDevice.getFromBundle(info.getExtras()); onDeviceSelected(); } @Override public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) { teardown(); mSelectedDevice = null; } } private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks { @Override public void onConnected(Bundle connectionHint) { Log.d(TAG, "ConnectionCallbacks onConnected: " + connectionHint); if (mWaitingForReconnect) { mWaitingForReconnect = false; reconnectReceiverApp(connectionHint); } else { launchReceiverApp(); } } @Override public void onConnectionSuspended(int cause) { mWaitingForReconnect = true; } } private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener { @Override public void onConnectionFailed(ConnectionResult result) { teardown(); } } private class HelloWorldChannel implements Cast.MessageReceivedCallback { public String getNamespace() { return "urn:x-cast:com.example.custom"; } @Override public void onMessageReceived(CastDevice castDevice, String namespace, String message) { Log.d(TAG, "onMessageReceived: " + message); } } }
/* * Copyright 1999-2010 University of Chicago * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * * See the License for the specific language governing permissions and limitations under the License. */ package org.globus.gsi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.globus.gsi.util.CertificateUtil; import org.globus.gsi.trustmanager.X509ProxyCertPathValidator; import org.globus.gsi.stores.ResourceCertStoreParameters; import org.globus.gsi.stores.ResourceSigningPolicyStore; import org.globus.gsi.stores.ResourceSigningPolicyStoreParameters; import org.globus.gsi.provider.GlobusProvider; import org.globus.gsi.provider.KeyStoreParametersFactory; import java.io.File; import java.security.cert.CertStore; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.security.cert.CertificateEncodingException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import org.globus.common.ChainedIOException; import org.globus.common.CoGProperties; import org.globus.gsi.bc.BouncyCastleUtil; /** * Provides a Java object representation of Globus credential which can include the proxy file or host * certificates. * @deprecated */ public class GlobusCredential implements Serializable { private Log logger = LogFactory.getLog(getClass()); private X509Credential cred; private static GlobusCredential defaultCred; private static transient long credentialLastModified = -1; // indicates if default credential was explicitely set // and if so - if the credential expired it try // to load the proxy from a file. private static transient boolean credentialSet = false; private static transient File credentialFile = null; static { new ProviderLoader(); } /** * Creates a GlobusCredential from a private key and a certificate chain. * * @param key * the private key * @param certs * the certificate chain */ public GlobusCredential(PrivateKey key, X509Certificate[] certs) { cred = new X509Credential(key, certs); } /** * Creates a GlobusCredential from a proxy file. * * @param proxyFile * the file to load the credential from. * @exception GlobusCredentialException * if the credential failed to load. */ public GlobusCredential(String proxyFile) throws GlobusCredentialException { try { cred = new X509Credential(proxyFile); } catch (Exception e) { throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Creates a GlobusCredential from certificate file and a unencrypted key file. * * @param certFile * the file containing the certificate * @param unencryptedKeyFile * the file containing the private key. The key must be unencrypted. * @exception GlobusCredentialException * if something goes wrong. */ public GlobusCredential(String certFile, String unencryptedKeyFile) throws GlobusCredentialException { if (certFile == null || unencryptedKeyFile == null) { throw new IllegalArgumentException(); } try { cred = new X509Credential(certFile, unencryptedKeyFile); } catch (Exception e) { throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Creates a GlobusCredential from an input stream. * * @param input * the stream to load the credential from. * @exception GlobusCredentialException * if the credential failed to load. */ public GlobusCredential(InputStream input) throws GlobusCredentialException { try { cred = new X509Credential(input); } catch (Exception e) { throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Saves the credential into a specified output stream. The self-signed certificates in the certificate * chain will not be saved. The output stream should always be closed after calling this function. * * @param out * the output stream to write the credential to. * @exception IOException * if any error occurred during saving. */ public void save(OutputStream out) throws IOException { try { cred.save(out); } catch (CertificateEncodingException e) { throw new ChainedIOException(e.getMessage(), e); } } /** * Verifies the validity of the credentials. All certificate path validation is performed using trusted * certificates in default locations. * * @exception GlobusCredentialException * if one of the certificates in the chain expired or if path validiation fails. */ public void verify() throws GlobusCredentialException { try { String caCertsLocation = "file:" + CoGProperties.getDefault().getCaCertLocations(); String crlPattern = caCertsLocation + "/*.r*"; String sigPolPattern = caCertsLocation + "/*.signing_policy"; KeyStore keyStore = KeyStore.getInstance(GlobusProvider.KEYSTORE_TYPE, GlobusProvider.PROVIDER_NAME); CertStore crlStore = CertStore.getInstance(GlobusProvider.CERTSTORE_TYPE, new ResourceCertStoreParameters(null,crlPattern)); ResourceSigningPolicyStore sigPolStore = new ResourceSigningPolicyStore(new ResourceSigningPolicyStoreParameters(sigPolPattern)); keyStore.load(KeyStoreParametersFactory.createTrustStoreParameters(caCertsLocation)); X509ProxyCertPathParameters parameters = new X509ProxyCertPathParameters(keyStore, crlStore, sigPolStore, false); X509ProxyCertPathValidator validator = new X509ProxyCertPathValidator(); validator.engineValidate(CertificateUtil.getCertPath(this.cred.getCertificateChain()), parameters); } catch (Exception e) { e.printStackTrace(); throw new GlobusCredentialException(GlobusCredentialException.FAILURE, e.getMessage(), e); } } /** * Returns the identity certificate of this credential. The identity certificate is the first certificate * in the chain that is not an impersonation proxy certificate. * * @return <code>X509Certificate</code> the identity cert. Null, if unable to get the identity certificate * (an error occurred) */ public X509Certificate getIdentityCertificate() { return cred.getIdentityCertificate(); } /** * Returns the path length constraint. The shortest length in the chain of certificates is returned as the * credential's path length. * * @return The path length constraint of the credential. -1 is any error occurs. */ public int getPathConstraint() { return cred.getPathConstraint(); } /** * Returns the identity of this credential. * * @see #getIdentityCertificate() * * @return The identity cert in Globus format (e.g. /C=US/..). Null, if unable to get the identity (an * error occurred) */ public String getIdentity() { return cred.getIdentity(); } /** * Returns the private key of this credential. * * @return <code>PrivateKey</code> the private key */ public PrivateKey getPrivateKey() { try { return (PrivateKey) cred.getPrivateKey(); } catch (Exception e) { return null; } } /** * Returns the certificate chain of this credential. * * @return <code>X509Certificate []</code> the certificate chain */ public X509Certificate[] getCertificateChain() { return cred.getCertificateChain(); } /** * Returns the number of certificates in the credential without the self-signed certificates. * * @return number of certificates without counting self-signed certificates */ public int getCertNum() { return cred.getCertNum(); } /** * Returns strength of the private/public key in bits. * * @return strength of the key in bits. Returns -1 if unable to determine it. */ public int getStrength() { try { return cred.getStrength(); } catch (Exception e) { return -1; } } /** * Returns the subject DN of the first certificate in the chain. * * @return subject DN. */ public String getSubject() { return cred.getSubject(); } /** * Returns the issuer DN of the first certificate in the chain. * * @return issuer DN. */ public String getIssuer() { return cred.getIssuer(); } /** * Returns the certificate type of the first certificate in the chain. Returns -1 if unable to determine * the certificate type (an error occurred) * * @see BouncyCastleUtil#getCertificateType(X509Certificate) * * @return the type of first certificate in the chain. -1 if unable to determine the certificate type. */ public int getProxyType() { return cred.getProxyType().getCode(); } /** * Returns time left of this credential. The time left of the credential is based on the certificate with * the shortest validity time. * * @return time left in seconds. Returns 0 if the certificate has expired. */ public long getTimeLeft() { return cred.getTimeLeft(); } /** * Returns the default credential. The default credential is usually the user proxy certificate. <BR> * The credential will be loaded on the initial call. It must not be expired. All subsequent calls to this * function return cached credential object. Once the credential is cached, and the underlying file * changes, the credential will be reloaded. * * @return the default credential. * @exception GlobusCredentialException * if the credential expired or some other error with the credential. */ public synchronized static GlobusCredential getDefaultCredential() throws GlobusCredentialException { if (defaultCred == null) { reloadDefaultCredential(); } else if (!credentialSet) { if (credentialFile.lastModified() == credentialLastModified) { defaultCred.verify(); } else { defaultCred = null; reloadDefaultCredential(); } } return defaultCred; } private static void reloadDefaultCredential() throws GlobusCredentialException { String proxyLocation = CoGProperties.getDefault().getProxyFile(); defaultCred = new GlobusCredential(proxyLocation); credentialFile = new File(proxyLocation); credentialLastModified = credentialFile.lastModified(); defaultCred.verify(); } /** * Sets default credential. * * @param cred * the credential to set a default. */ public synchronized static void setDefaultCredential(GlobusCredential cred) { credentialSet = (cred != null); } public String toString() { return cred.toString(); } }
/* * $Id$ * This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc * * Copyright (c) 2000-2012 Stephane GALLAND. * Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports, * Universite de Technologie de Belfort-Montbeliard. * Copyright (c) 2013-2016 The original authors, and other authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.arakhne.afc.math.tree.node; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Collection; import java.util.List; import org.eclipse.xtext.xbase.lib.Pure; import org.arakhne.afc.math.tree.TreeNode; /** * This is the generic implementation of a binary * tree. * * <p><h3>moveTo</h3> * According to its definition in * {@link TreeNode#moveTo(TreeNode, int)}, the binary * tree node implementation of <code>moveTo</code> * replaces any existing node at the position given as * parameter of <code>moveTo</code>.. * * @param <D> is the type of the data inside the tree * @param <N> is the type of the tree nodes. * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 13.0 */ public abstract class BinaryTreeNode<D, N extends BinaryTreeNode<D, N>> extends AbstractTreeNode<D, N> { private static final long serialVersionUID = -3061156557458672703L; private N left; private N right; /** * Empty node. */ public BinaryTreeNode() { this(DEFAULT_LINK_LIST_USE); } /** Construct node. * @param data are the initial data. */ public BinaryTreeNode(Collection<D> data) { super(DEFAULT_LINK_LIST_USE, data); this.left = null; this.right = null; } /** Construct node. * @param data are the initial data. */ public BinaryTreeNode(D data) { this(DEFAULT_LINK_LIST_USE, data); } /** Construct node. * @param useLinkedList indicates if a linked list must be used to store the data. * If <code>false</code>, an ArrayList will be used. */ public BinaryTreeNode(boolean useLinkedList) { super(useLinkedList); this.left = null; this.right = null; } /** Construct node. * @param useLinkedList indicates if a linked list must be used to store the data. * If <code>false</code>, an ArrayList will be used. * @param copyDataCollection indicates if the given data collection is copied * if <code>true</code> or the inner data collection will be the given * collection itself if <code>false</code>. * @param data are the initial data. */ public BinaryTreeNode(boolean useLinkedList, boolean copyDataCollection, List<D> data) { super(useLinkedList, copyDataCollection, data); this.left = null; this.right = null; } /** Construct node. * @param useLinkedList indicates if a linked list must be used to store the data. * If <code>false</code>, an ArrayList will be used. * @param data are the initial data. */ public BinaryTreeNode(boolean useLinkedList, D data) { super(useLinkedList, data); this.left = null; this.right = null; } @Override @Pure public Class<? extends Enum<?>> getPartitionEnumeration() { return BinaryTreeZone.class; } /** Invoked when this object must be deserialized. * * @param in is the input stream. * @throws IOException in case of input stream access error. * @throws ClassNotFoundException if some class was not found. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (this.left != null) { this.left.setParentNodeReference(toN(), false); } if (this.right != null) { this.right.setParentNodeReference(toN(), false); } } /** Clear the tree. * * <p>Caution: this method also destroyes the * links between the child nodes inside the tree. * If you want to unlink the first-level * child node with * this node but leave the rest of the tree * unchanged, please call <code>setChildAt(i,null)</code>. */ @Override public void clear() { if (this.left != null) { final N child = this.left; setLeftChild(null); child.clear(); } if (this.right != null) { final N child = this.right; setRightChild(null); child.clear(); } removeAllUserData(); } @Override @Pure public int getChildCount() { return 2; } @Override @Pure public int getNotNullChildCount() { return this.notNullChildCount; } @Override @Pure public N getChildAt(int index) throws IndexOutOfBoundsException { switch (index) { case 0: return this.left; case 1: return this.right; default: throw new IndexOutOfBoundsException(); } } /** Replies the child node at the specified position. * * @param index is the position of the child to reply. * @return the child or <code>null</code> */ @Pure public final N getChildAt(BinaryTreeZone index) { switch (index) { case LEFT: return this.left; case RIGHT: return this.right; default: throw new IndexOutOfBoundsException(); } } /** Set the left child of this node. * * @param newChild is the new left child * @return <code>true</code> on success, otherwise <code>false</code> */ public boolean setLeftChild(N newChild) { final N oldChild = this.left; if (oldChild == newChild) { return false; } if (oldChild != null) { oldChild.setParentNodeReference(null, true); --this.notNullChildCount; firePropertyChildRemoved(0, oldChild); } if (newChild != null) { final N oldParent = newChild.getParentNode(); if (oldParent != this) { newChild.removeFromParent(); } } this.left = newChild; if (newChild != null) { ++this.notNullChildCount; newChild.setParentNodeReference(toN(), true); firePropertyChildAdded(0, newChild); } return true; } /** Set the left child of this node. * * @return the left child or <code>null</code> if it does not exist */ @Pure public final N getLeftChild() { return this.left; } /** Set the right child of this node. * * @param newChild is the new left child * @return <code>true</code> on success, otherwise <code>false</code> */ public boolean setRightChild(N newChild) { final N oldChild = this.right; if (oldChild == newChild) { return false; } if (oldChild != null) { oldChild.setParentNodeReference(null, true); --this.notNullChildCount; firePropertyChildRemoved(1, oldChild); } if (newChild != null) { final N oldParent = newChild.getParentNode(); if (oldParent != this) { newChild.removeFromParent(); } } this.right = newChild; if (newChild != null) { newChild.setParentNodeReference(toN(), true); ++this.notNullChildCount; firePropertyChildAdded(1, newChild); } return true; } /** Set the right child of this node. * * @return the right child or <code>null</code> if it does not exist */ @Pure public final N getRightChild() { return this.right; } @Override @Pure public boolean isLeaf() { return this.left == null && this.right == null; } @Override public boolean setChildAt(int index, N newChild) throws IndexOutOfBoundsException { switch (index) { case 0: return setLeftChild(newChild); case 1: return setRightChild(newChild); default: throw new IndexOutOfBoundsException(); } } /** Set the child for the specified zone. * * @param zone is the zone to set * @param newChild is the child to insert * @return <code>true</code> if the child was added, otherwise <code>false</code> */ public final boolean setChildAt(BinaryTreeZone zone, N newChild) { switch (zone) { case LEFT: return setLeftChild(newChild); case RIGHT: return setRightChild(newChild); default: throw new IndexOutOfBoundsException(); } } @Override protected void setChildAtWithoutEventFiring(int index, N newChild) throws IndexOutOfBoundsException { switch (index) { case 0: if (this.left != null) { --this.notNullChildCount; } this.left = newChild; if (this.left != null) { ++this.notNullChildCount; } break; case 1: if (this.right != null) { --this.notNullChildCount; } this.right = newChild; if (this.right != null) { ++this.notNullChildCount; } break; default: throw new IndexOutOfBoundsException(); } } @Override public boolean moveTo(N newParent, int index) { return moveTo(newParent, index, false); } @Override public boolean removeChild(N child) { if (child != null) { if (child == this.left) { return setLeftChild(null); } else if (child == this.right) { return setRightChild(null); } } return false; } @Pure @Override public int indexOf(N child) { if (child == this.left) { return 0; } if (child == this.right) { return 1; } return -1; } @Override public void getChildren(Object[] array) { if (array != null) { if (array.length > 0) { array[0] = this.left; } if (array.length > 1) { array[1] = this.right; } } } @Pure @Override public int getMinHeight() { return 1 + Math.min( this.left != null ? this.left.getMinHeight() : 0, this.right != null ? this.right.getMinHeight() : 0); } @Pure @Override public int getMaxHeight() { return 1 + Math.max( this.left != null ? this.left.getMaxHeight() : 0, this.right != null ? this.right.getMaxHeight() : 0); } /** Replies the heights of all the leaf nodes. * The order of the heights is given by a depth-first iteration. * * @param currentHeight is the current height of this node. * @param heights is the list of heights to fill */ @Override protected void getHeights(int currentHeight, List<Integer> heights) { if (isLeaf()) { heights.add(new Integer(currentHeight)); } else { if (this.left != null) { this.left.getHeights(currentHeight + 1, heights); } if (this.right != null) { this.right.getHeights(currentHeight + 1, heights); } } } /** * This is the generic implementation of a ternary * tree. * * @param <D> is the type of the data inside the tree * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 13.0 */ public static class DefaultBinaryTreeNode<D> extends BinaryTreeNode<D, DefaultBinaryTreeNode<D>> { private static final long serialVersionUID = -1756893035646038303L; /** * Empty node. */ public DefaultBinaryTreeNode() { super(); } /** * @param data are the initial user data. * */ public DefaultBinaryTreeNode(Collection<D> data) { super(data); } /** * @param data are the initial user data. * */ public DefaultBinaryTreeNode(D data) { super(data); } } /** * This is the generic implementation of a * tree for which each node has two children. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 13.0 */ public enum BinaryTreeZone { /** This is the index of the child that correspond to * the voxel at front/left/up position. */ LEFT, /** This is the index of the child that correspond to * the voxel at back/right/down position. */ RIGHT; /** Replies the zone corresponding to the given index. * The index is the same as the ordinal value of the * enumeration. If the given index does not correspond * to an ordinal value, <code>null</code> is replied. * * @param index the index. * @return the zone or <code>null</code> */ @Pure public static BinaryTreeZone fromInteger(int index) { if (index < 0) { return null; } final BinaryTreeZone[] nodes = values(); if (index >= nodes.length) { return null; } return nodes[index]; } } }
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.sql.analyzer; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.model.sql.analyzer.builder.request.RequestBuilder; import org.jkiss.dbeaver.model.sql.analyzer.builder.request.RequestResult; import org.jkiss.dbeaver.model.sql.completion.SQLCompletionProposalBase; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.jkiss.dbeaver.model.sql.analyzer.builder.Builder.Consumer.empty; public class SQLCompletionAnalyzerTest { @Test public void testKeywordCompletion() throws DBException { final RequestResult request = RequestBuilder .empty() .prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SEL|"); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("SELECT", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * |"); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("FROM", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM T |"); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("WHERE", proposals.get(0).getReplacementString()); } } @Test public void testColumnNamesCompletion() throws DBException { final RequestResult request = RequestBuilder .tables(s -> { s.table("Table1", t -> { t.attribute("Col1"); t.attribute("Col2"); t.attribute("Col3"); }); s.table("Table2", t -> { t.attribute("Col4"); t.attribute("Col5"); t.attribute("Col6"); }); s.table("Table 3", t -> { t.attribute("Col7"); t.attribute("Col8"); t.attribute("Col9"); }); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request .request("SELECT | FROM Table1"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT * FROM Table1 WHERE |"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT * FROM Table1 WHERE Table1.|"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT * FROM Table1 t WHERE t.|"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT * FROM \"Table 3\" t WHERE t.|"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col7", proposals.get(0).getReplacementString()); Assert.assertEquals("Col8", proposals.get(1).getReplacementString()); Assert.assertEquals("Col9", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT t.| FROM Table1 t"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT t2.| FROM Table1 t, Table2 t2"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col4", proposals.get(0).getReplacementString()); Assert.assertEquals("Col5", proposals.get(1).getReplacementString()); Assert.assertEquals("Col6", proposals.get(2).getReplacementString()); } } @Test public void testColumnWithNonExistingAliases() throws DBException { final RequestResult request = RequestBuilder.tables(s-> { s.table("Table1", t -> { t.attribute("Col1"); t.attribute("Col2"); }); s.table("Table2", t -> { t.attribute("Col4"); t.attribute("Col5"); }); }).prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Table1 join Table2 t on t.|", false); Assert.assertEquals("Col4", proposals.get(0).getReplacementString()); Assert.assertEquals("Col5", proposals.get(1).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Table1 b join Table2 on b.|", false); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); } } @Test public void testColumnNamesExpandCompletion() throws DBException { final RequestResult request = RequestBuilder .tables(s -> { s.table("Table1", t -> { t.attribute("Col1"); t.attribute("Col2"); t.attribute("Col3"); }); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request .request("SELECT *| FROM Table1", false); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Col1, Col2, Col3", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT t.*| FROM Table1 t", false); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Col1, t.Col2, t.Col3", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request .request("SELECT Table1.*| FROM Table1", false); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Col1, Table1.Col2, Table1.Col3", proposals.get(0).getReplacementString()); } } @Test public void testTableNamesCompletion() throws DBException { final RequestResult request = RequestBuilder .tables(s -> { s.table("Table1", empty()); s.table("Table2", empty()); s.table("Table3", empty()); s.table("Tbl4", empty()); s.table("Tbl5", empty()); s.table("Tbl6", empty()); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM |"); Assert.assertTrue(proposals.size() >= 3); Assert.assertEquals("Table1", proposals.get(0).getReplacementString()); Assert.assertEquals("Table2", proposals.get(1).getReplacementString()); Assert.assertEquals("Table3", proposals.get(2).getReplacementString()); // TODO: Is 'WHERE' even supposed to be here? // Assert.assertEquals("WHERE", proposals.get(3).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Tb|"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Tbl4", proposals.get(0).getReplacementString()); Assert.assertEquals("Tbl5", proposals.get(1).getReplacementString()); Assert.assertEquals("Tbl6", proposals.get(2).getReplacementString()); } } @Test public void testSchemaTableNamesCompletion() throws DBException { final RequestResult request = RequestBuilder .schemas(d -> { d.schema("Schema1", s -> { s.table("Table1", empty()); s.table("Table2", empty()); s.table("Table3", empty()); }); d.schema("Schema2", s -> { s.table("Table4", empty()); s.table("Table5", empty()); s.table("Table6", empty()); }); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Sch|"); Assert.assertEquals(2, proposals.size()); Assert.assertEquals("Schema1", proposals.get(0).getReplacementString()); Assert.assertEquals("Schema2", proposals.get(1).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Schema1.|"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Table1", proposals.get(0).getReplacementString()); Assert.assertEquals("Table2", proposals.get(1).getReplacementString()); Assert.assertEquals("Table3", proposals.get(2).getReplacementString()); } } @Test public void testDatabaseSchemaTableNamesCompletion() throws DBException { final RequestResult request = RequestBuilder .databases(x -> { x.database("Database1", d -> { d.schema("Schema1", s -> { s.table("Table1", empty()); s.table("Table2", empty()); s.table("Table3", empty()); }); }); x.database("Database2", d -> { d.schema("Schema2", s -> { s.table("Table4", empty()); s.table("Table5", empty()); s.table("Table6", empty()); }); }); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Da|"); Assert.assertEquals(2, proposals.size()); Assert.assertEquals("Database1", proposals.get(0).getReplacementString()); Assert.assertEquals("Database2", proposals.get(1).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Database1.|"); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Schema1", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Database1.Schema1.|"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Table1", proposals.get(0).getReplacementString()); Assert.assertEquals("Table2", proposals.get(1).getReplacementString()); Assert.assertEquals("Table3", proposals.get(2).getReplacementString()); } } @Test @Ignore("See #12159") public void testQuotedNamesCompletion() throws DBException { final RequestResult request = RequestBuilder .databases(x -> { x.database("Database1", d -> { d.schema("Schema1", s -> { s.table("Table1", t -> { t.attribute("Col1"); t.attribute("Col2"); t.attribute("Col3"); }); }); }); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM \"Dat|\""); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Database1", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM \"Database1\".\"Sch|\""); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Schema1", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM \"Database1\".\"Schema1\".\"Tab|\""); Assert.assertEquals(1, proposals.size()); Assert.assertEquals("Table1", proposals.get(0).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM \"Database1\".\"Schema1\".\"Table1\".\"Col|\""); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } } @Test public void testColumnsQuotedNamesCompletion() throws DBException { final RequestResult request = RequestBuilder .databases(x -> { x.database("Database1", d -> { d.schema("Schema1", s -> { s.table("Table1", t -> { t.attribute("Col1"); t.attribute("Col2"); t.attribute("Col3"); }); }); }); }) .prepare(); { final List<SQLCompletionProposalBase> proposals = request.request("SELECT | FROM Database1.Schema1.Table1"); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT | FROM \"Database1\".Schema1.\"Table1\""); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } { final List<SQLCompletionProposalBase> proposals = request.request("SELECT | FROM \"Database1\".\"Schema1\".\"Table1\""); Assert.assertEquals(3, proposals.size()); Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); Assert.assertEquals("Col3", proposals.get(2).getReplacementString()); } } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.editor.colors.impl; import com.intellij.application.options.EditorFontsConstants; import com.intellij.configurationStore.SerializableScheme; import com.intellij.ide.ui.ColorBlindness; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.colors.*; import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.options.FontSize; import com.intellij.openapi.options.SchemeState; import com.intellij.openapi.util.*; import com.intellij.ui.ColorUtil; import com.intellij.util.JdomKt; import com.intellij.util.ObjectUtils; import com.intellij.util.PlatformUtils; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.containers.JBIterable; import gnu.trove.THashMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import static com.intellij.openapi.editor.colors.CodeInsightColors.*; import static com.intellij.openapi.editor.colors.EditorColors.*; import static com.intellij.openapi.util.Couple.of; import static com.intellij.ui.ColorUtil.fromHex; @SuppressWarnings("UseJBColor") public abstract class AbstractColorsScheme extends EditorFontCacheImpl implements EditorColorsScheme, SerializableScheme { public static final TextAttributes INHERITED_ATTRS_MARKER = new TextAttributes(); public static final Color INHERITED_COLOR_MARKER = ColorUtil.marker("INHERITED_COLOR_MARKER"); public static final Color NULL_COLOR_MARKER = ColorUtil.marker("NULL_COLOR_MARKER"); public static final int CURR_VERSION = 142; // todo: unify with UIUtil.DEF_SYSTEM_FONT_SIZE private static final FontSize DEFAULT_FONT_SIZE = FontSize.SMALL; protected EditorColorsScheme myParentScheme; protected FontSize myQuickDocFontSize = DEFAULT_FONT_SIZE; @NotNull private FontPreferences myFontPreferences = new DelegatingFontPreferences(() -> AppEditorFontOptions.getInstance().getFontPreferences()); @NotNull private FontPreferences myConsoleFontPreferences = new DelegatingFontPreferences(() -> myFontPreferences); private final ValueElementReader myValueReader = new TextAttributesReader(); private String mySchemeName; private boolean myIsSaveNeeded; private boolean myCanBeDeleted = true; // version influences XML format and triggers migration private int myVersion = CURR_VERSION; protected Map<ColorKey, Color> myColorsMap = ContainerUtilRt.newHashMap(); protected Map<TextAttributesKey, TextAttributes> myAttributesMap = new THashMap<>(); @NonNls private static final String EDITOR_FONT = "font"; @NonNls private static final String CONSOLE_FONT = "console-font"; @NonNls private static final String EDITOR_FONT_NAME = "EDITOR_FONT_NAME"; @NonNls private static final String CONSOLE_FONT_NAME = "CONSOLE_FONT_NAME"; private Color myDeprecatedBackgroundColor = null; @NonNls private static final String SCHEME_ELEMENT = "scheme"; @NonNls public static final String NAME_ATTR = "name"; @NonNls private static final String VERSION_ATTR = "version"; @NonNls private static final String BASE_ATTRIBUTES_ATTR = "baseAttributes"; @NonNls private static final String DEFAULT_SCHEME_ATTR = "default_scheme"; @NonNls private static final String PARENT_SCHEME_ATTR = "parent_scheme"; @NonNls private static final String OPTION_ELEMENT = "option"; @NonNls private static final String COLORS_ELEMENT = "colors"; @NonNls private static final String ATTRIBUTES_ELEMENT = "attributes"; @NonNls private static final String VALUE_ELEMENT = "value"; @NonNls private static final String BACKGROUND_COLOR_NAME = "BACKGROUND"; @NonNls private static final String LINE_SPACING = "LINE_SPACING"; @NonNls private static final String CONSOLE_LINE_SPACING = "CONSOLE_LINE_SPACING"; @NonNls private static final String FONT_SCALE = "FONT_SCALE"; @NonNls private static final String EDITOR_FONT_SIZE = "EDITOR_FONT_SIZE"; @NonNls private static final String CONSOLE_FONT_SIZE = "CONSOLE_FONT_SIZE"; @NonNls private static final String EDITOR_LIGATURES = "EDITOR_LIGATURES"; @NonNls private static final String CONSOLE_LIGATURES = "CONSOLE_LIGATURES"; @NonNls private static final String EDITOR_QUICK_JAVADOC_FONT_SIZE = "EDITOR_QUICK_DOC_FONT_SIZE"; //region Meta info-related fields private final Properties myMetaInfo = new Properties(); private final static SimpleDateFormat META_INFO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); @NonNls private static final String META_INFO_ELEMENT = "metaInfo"; @NonNls private static final String PROPERTY_ELEMENT = "property"; @NonNls private static final String PROPERTY_NAME_ATTR = "name"; @NonNls private static final String META_INFO_CREATION_TIME = "created"; @NonNls private static final String META_INFO_MODIFIED_TIME = "modified"; @NonNls private static final String META_INFO_IDE = "ide"; @NonNls private static final String META_INFO_IDE_VERSION = "ideVersion"; @NonNls private static final String META_INFO_ORIGINAL = "originalScheme"; //endregion protected AbstractColorsScheme(EditorColorsScheme parentScheme) { myParentScheme = parentScheme; } public AbstractColorsScheme() { } public void setDefaultMetaInfo(@Nullable AbstractColorsScheme parentScheme) { myMetaInfo.setProperty(META_INFO_CREATION_TIME, META_INFO_DATE_FORMAT.format(new Date())); myMetaInfo.setProperty(META_INFO_IDE, PlatformUtils.getPlatformPrefix()); myMetaInfo.setProperty(META_INFO_IDE_VERSION, ApplicationInfoEx.getInstanceEx().getStrictVersion()); if (parentScheme != null && parentScheme != EmptyColorScheme.INSTANCE) { myMetaInfo.setProperty(META_INFO_ORIGINAL, parentScheme.getName()); } } @NotNull @Override public Color getDefaultBackground() { final Color c = getAttributes(HighlighterColors.TEXT).getBackgroundColor(); return c != null ? c : Color.white; } @NotNull @Override public Color getDefaultForeground() { final Color c = getAttributes(HighlighterColors.TEXT).getForegroundColor(); return c != null ? c : Color.black; } @NotNull @Override public String getName() { return mySchemeName; } @Override public void setFont(EditorFontType key, Font font) { } @Override public abstract Object clone(); public void copyTo(AbstractColorsScheme newScheme) { newScheme.myQuickDocFontSize = myQuickDocFontSize; if (myConsoleFontPreferences instanceof DelegatingFontPreferences) { newScheme.setUseEditorFontPreferencesInConsole(); } else { newScheme.setConsoleFontPreferences(myConsoleFontPreferences); } if (myFontPreferences instanceof DelegatingFontPreferences) { newScheme.setUseAppFontPreferencesInEditor(); } else { newScheme.setFontPreferences(myFontPreferences); } newScheme.myAttributesMap = new THashMap<>(myAttributesMap); newScheme.myColorsMap = new HashMap<>(myColorsMap); newScheme.myVersion = myVersion; } @NotNull public Set<ColorKey> getColorKeys() { return myColorsMap.keySet(); } @Override public void setEditorFontName(String fontName) { ModifiableFontPreferences currPreferences = ensureEditableFontPreferences(); boolean useLigatures = currPreferences.useLigatures(); int editorFontSize = getEditorFontSize(); currPreferences.clear(); currPreferences.register(fontName, editorFontSize); currPreferences.setUseLigatures(useLigatures); initFonts(); } @Override public void setEditorFontSize(int fontSize) { fontSize = EditorFontsConstants.checkAndFixEditorFontSize(fontSize); ensureEditableFontPreferences().register(myFontPreferences.getFontFamily(), fontSize); initFonts(); } @Override public void setUseAppFontPreferencesInEditor() { myFontPreferences = new DelegatingFontPreferences(()-> AppEditorFontOptions.getInstance().getFontPreferences()); initFonts(); } @Override public boolean isUseAppFontPreferencesInEditor() { return myFontPreferences instanceof DelegatingFontPreferences; } @Override public void setQuickDocFontSize(@NotNull FontSize fontSize) { if (myQuickDocFontSize != fontSize) { myQuickDocFontSize = fontSize; myIsSaveNeeded = true; } } @Override public void setLineSpacing(float lineSpacing) { ensureEditableFontPreferences().setLineSpacing(lineSpacing); } @NotNull @Override public Font getFont(EditorFontType key) { return myFontPreferences instanceof DelegatingFontPreferences ? EditorFontCache.getInstance().getFont(key) : super.getFont(key); } @Override public void setName(@NotNull String name) { mySchemeName = name; } @NotNull @Override public FontPreferences getFontPreferences() { return myFontPreferences; } @Override public void setFontPreferences(@NotNull FontPreferences preferences) { preferences.copyTo(ensureEditableFontPreferences()); initFonts(); } @Override public String getEditorFontName() { return getFont(EditorFontType.PLAIN).getFamily(); } @Override public int getEditorFontSize() { return myFontPreferences.getSize(myFontPreferences.getFontFamily()); } @NotNull @Override public FontSize getQuickDocFontSize() { return myQuickDocFontSize; } @Override public float getLineSpacing() { return myFontPreferences.getLineSpacing(); } protected void initFonts() { reset(); } @Override protected EditorColorsScheme getFontCacheScheme() { return this; } public String toString() { return getName(); } @Override public void readExternal(@NotNull Element parentNode) { UISettings settings = UISettings.getInstanceOrNull(); ColorBlindness blindness = settings == null ? null : settings.getColorBlindness(); myValueReader.setAttribute(blindness == null ? null : blindness.name()); if (SCHEME_ELEMENT.equals(parentNode.getName())) { readScheme(parentNode); } else { List<Element> children = parentNode.getChildren(SCHEME_ELEMENT); if (children.isEmpty()) { throw new InvalidDataException("Scheme is not valid"); } for (Element element : children) { readScheme(element); } } initFonts(); myVersion = CURR_VERSION; } private void readScheme(Element node) { myDeprecatedBackgroundColor = null; if (!SCHEME_ELEMENT.equals(node.getName())) { return; } setName(node.getAttributeValue(NAME_ATTR)); int readVersion = Integer.parseInt(node.getAttributeValue(VERSION_ATTR, "0")); if (readVersion > CURR_VERSION) { throw new IllegalStateException("Unsupported color scheme version: " + readVersion); } myVersion = readVersion; String isDefaultScheme = node.getAttributeValue(DEFAULT_SCHEME_ATTR); boolean isDefault = isDefaultScheme != null && Boolean.parseBoolean(isDefaultScheme); if (!isDefault) { myParentScheme = getDefaultScheme(node.getAttributeValue(PARENT_SCHEME_ATTR, EmptyColorScheme.NAME)); } myMetaInfo.clear(); Ref<Float> fontScale = Ref.create(); boolean clearEditorFonts = true; boolean clearConsoleFonts = true; for (Element childNode : node.getChildren()) { String childName = childNode.getName(); switch (childName) { case OPTION_ELEMENT: readSettings(childNode, isDefault, fontScale); break; case EDITOR_FONT: readFontSettings(ensureEditableFontPreferences(), childNode, isDefault, fontScale.get(), clearEditorFonts); clearEditorFonts = false; break; case CONSOLE_FONT: readFontSettings(ensureEditableConsoleFontPreferences(), childNode, isDefault, fontScale.get(), clearConsoleFonts); clearConsoleFonts = false; break; case COLORS_ELEMENT: readColors(childNode); break; case ATTRIBUTES_ELEMENT: readAttributes(childNode); break; case META_INFO_ELEMENT: readMetaInfo(childNode); break; } } if (myDeprecatedBackgroundColor != null) { TextAttributes textAttributes = myAttributesMap.get(HighlighterColors.TEXT); if (textAttributes == null) { textAttributes = new TextAttributes(Color.black, myDeprecatedBackgroundColor, null, EffectType.BOXED, Font.PLAIN); myAttributesMap.put(HighlighterColors.TEXT, textAttributes); } else { textAttributes.setBackgroundColor(myDeprecatedBackgroundColor); } } if (myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty()) { myFontPreferences.copyTo(myConsoleFontPreferences); } initFonts(); } @NotNull private static EditorColorsScheme getDefaultScheme(@NotNull String name) { DefaultColorSchemesManager manager = DefaultColorSchemesManager.getInstance(); EditorColorsScheme defaultScheme = manager.getScheme(name); if (defaultScheme == null) { defaultScheme = new TemporaryParent(name); } return defaultScheme; } private void readMetaInfo(@NotNull Element metaInfoElement) { myMetaInfo.clear(); for (Element e: metaInfoElement.getChildren()) { if (PROPERTY_ELEMENT.equals(e.getName())) { String propertyName = e.getAttributeValue(PROPERTY_NAME_ATTR); if (propertyName != null) { myMetaInfo.setProperty(propertyName, e.getText()); } } } } public void readAttributes(@NotNull Element childNode) { for (Element e : childNode.getChildren(OPTION_ELEMENT)) { String keyName = e.getAttributeValue(NAME_ATTR); Element valueElement = e.getChild(VALUE_ELEMENT); TextAttributesKey key = TextAttributesKey.find(keyName); TextAttributes attr = valueElement != null ? myValueReader.read(TextAttributes.class, valueElement) : e.getAttributeValue(BASE_ATTRIBUTES_ATTR) != null ? INHERITED_ATTRS_MARKER : null; if (attr != null) { myAttributesMap.put(key, attr); migrateErrorStripeColorFrom14(key, attr); } } } private void migrateErrorStripeColorFrom14(@NotNull TextAttributesKey name, @NotNull TextAttributes attr) { if (myVersion >= 141 || myParentScheme == null) return; Couple<Color> m = DEFAULT_STRIPE_COLORS.get(name.getExternalName()); if (m != null && Comparing.equal(m.first, attr.getErrorStripeColor())) { attr.setErrorStripeColor(m.second); } } @SuppressWarnings("UseJBColor") private static final Map<String, Couple<Color>> DEFAULT_STRIPE_COLORS = new THashMap<String, Couple<Color>>() { { put(ERRORS_ATTRIBUTES.getExternalName(), of(Color.red, fromHex("CF5B56"))); put(WARNINGS_ATTRIBUTES.getExternalName(), of(Color.yellow, fromHex("EBC700"))); put("EXECUTIONPOINT_ATTRIBUTES", of(Color.blue, fromHex("3763b0"))); put(IDENTIFIER_UNDER_CARET_ATTRIBUTES.getExternalName(), of(fromHex("CCCFFF"), fromHex("BAA8FF"))); put(WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES.getExternalName(), of(fromHex("FFCCE5"), fromHex("F0ADF0"))); put(TEXT_SEARCH_RESULT_ATTRIBUTES.getExternalName(), of(fromHex("586E75"), fromHex("71B362"))); put(TODO_DEFAULT_ATTRIBUTES.getExternalName(), of(fromHex("268BD2"), fromHex("54AAE3"))); } }; private void readColors(Element childNode) { for (Element colorElement : childNode.getChildren(OPTION_ELEMENT)) { String keyName = colorElement.getAttributeValue(NAME_ATTR); Color valueColor = myValueReader.read(Color.class, colorElement); if (valueColor == null && colorElement.getAttributeValue(BASE_ATTRIBUTES_ATTR) != null) { valueColor = INHERITED_COLOR_MARKER; } if (BACKGROUND_COLOR_NAME.equals(keyName)) { // This setting has been deprecated to usages of HighlighterColors.TEXT attributes. myDeprecatedBackgroundColor = valueColor; } ColorKey name = ColorKey.find(keyName); myColorsMap.put(name, ObjectUtils.notNull(valueColor, NULL_COLOR_MARKER)); } } private void readSettings(@NotNull Element childNode, boolean isDefault, @NotNull Ref<Float> fontScale) { switch (childNode.getAttributeValue(NAME_ATTR)) { case FONT_SCALE: { fontScale.set(myValueReader.read(Float.class, childNode)); break; } case LINE_SPACING: { Float value = myValueReader.read(Float.class, childNode); if (value != null) setLineSpacing(value); break; } case EDITOR_FONT_SIZE: { int value = readFontSize(childNode, isDefault, fontScale.get()); if (value > 0) setEditorFontSize(value); break; } case EDITOR_FONT_NAME: { String value = myValueReader.read(String.class, childNode); if (value != null) setEditorFontName(value); break; } case CONSOLE_LINE_SPACING: { Float value = myValueReader.read(Float.class, childNode); if (value != null) setConsoleLineSpacing(value); break; } case CONSOLE_FONT_SIZE: { int value = readFontSize(childNode, isDefault, fontScale.get()); if (value > 0) setConsoleFontSize(value); break; } case CONSOLE_FONT_NAME: { String value = myValueReader.read(String.class, childNode); if (value != null) setConsoleFontName(value); break; } case EDITOR_QUICK_JAVADOC_FONT_SIZE: { FontSize value = myValueReader.read(FontSize.class, childNode); if (value != null) myQuickDocFontSize = value; break; } case EDITOR_LIGATURES: { Boolean value = myValueReader.read(Boolean.class, childNode); if (value != null) ensureEditableFontPreferences().setUseLigatures(value); break; } case CONSOLE_LIGATURES: { Boolean value = myValueReader.read(Boolean.class, childNode); if (value != null) { ensureEditableConsoleFontPreferences().setUseLigatures(value); } break; } } } private int readFontSize(Element element, boolean isDefault, Float fontScale) { if (isDefault) { return UISettings.getDefFontSize(); } Integer intSize = myValueReader.read(Integer.class, element); if (intSize == null) { return -1; } return UISettings.restoreFontSize(intSize, fontScale); } private void readFontSettings(@NotNull ModifiableFontPreferences preferences, @NotNull Element element, boolean isDefaultScheme, @Nullable Float fontScale, boolean clearFonts) { if (clearFonts) preferences.clearFonts(); List children = element.getChildren(OPTION_ELEMENT); String fontFamily = null; int size = -1; for (Object child : children) { Element e = (Element)child; if (EDITOR_FONT_NAME.equals(e.getAttributeValue(NAME_ATTR))) { fontFamily = myValueReader.read(String.class, e); } else if (EDITOR_FONT_SIZE.equals(e.getAttributeValue(NAME_ATTR))) { size = readFontSize(e, isDefaultScheme, fontScale); } } if (fontFamily != null && size > 1) { preferences.register(fontFamily, size); } else if (fontFamily != null) { preferences.addFontFamily(fontFamily); } } public void writeExternal(Element parentNode) { parentNode.setAttribute(NAME_ATTR, getName()); parentNode.setAttribute(VERSION_ATTR, Integer.toString(myVersion)); /* * FONT_SCALE is used to correctly identify the font size in both the JRE-managed HiDPI mode and * the IDE-managed HiDPI mode: {@link UIUtil#isJreHiDPIEnabled()}. Also, it helps to distinguish * the "hidpi-aware" scheme version from the previous one. Namely, the absence of the FONT_SCALE * attribute in the scheme indicates the previous "hidpi-unaware" scheme and the restored font size * is reset to default. It's assumed this (transition case) happens only once, after which the IDE * will be able to restore the font size according to its scale and the IDE HiDPI mode. The default * FONT_SCALE value should also be written by that reason. */ if (!(myFontPreferences instanceof DelegatingFontPreferences) || !(myConsoleFontPreferences instanceof DelegatingFontPreferences)) { JdomKt.addOptionTag(parentNode, FONT_SCALE, String.valueOf(UISettings.getDefFontScale())); // must precede font options } if (myParentScheme != null && myParentScheme != EmptyColorScheme.INSTANCE) { parentNode.setAttribute(PARENT_SCHEME_ATTR, myParentScheme.getName()); } if (!myMetaInfo.isEmpty()) { parentNode.addContent(metaInfoToElement()); } if (getLineSpacing() != FontPreferences.DEFAULT_LINE_SPACING) { JdomKt.addOptionTag(parentNode, LINE_SPACING, String.valueOf(getLineSpacing())); } // IJ has used a 'single customizable font' mode for ages. That's why we want to support that format now, when it's possible // to specify fonts sequence (see getFontPreferences()), there are big chances that many clients still will use a single font. // That's why we want to use old format when zero or one font is selected and 'extended' format otherwise. boolean useOldFontFormat = myFontPreferences.getEffectiveFontFamilies().size() <= 1; if (!(myFontPreferences instanceof DelegatingFontPreferences)) { if (useOldFontFormat) { JdomKt.addOptionTag(parentNode, EDITOR_FONT_SIZE, String.valueOf(getEditorFontSize())); JdomKt.addOptionTag(parentNode, EDITOR_FONT_NAME, myFontPreferences.getFontFamily()); } else { writeFontPreferences(EDITOR_FONT, parentNode, myFontPreferences); } writeLigaturesPreferences(parentNode, myFontPreferences, EDITOR_LIGATURES); } if (!(myConsoleFontPreferences instanceof DelegatingFontPreferences)) { if (myConsoleFontPreferences.getEffectiveFontFamilies().size() <= 1) { JdomKt.addOptionTag(parentNode, CONSOLE_FONT_NAME, getConsoleFontName()); if (getConsoleFontSize() != getEditorFontSize()) { JdomKt.addOptionTag(parentNode, CONSOLE_FONT_SIZE, Integer.toString(getConsoleFontSize())); } } else { writeFontPreferences(CONSOLE_FONT, parentNode, myConsoleFontPreferences); } writeLigaturesPreferences(parentNode, myConsoleFontPreferences, CONSOLE_LIGATURES); if (getConsoleLineSpacing() != FontPreferences.DEFAULT_LINE_SPACING) { JdomKt.addOptionTag(parentNode, CONSOLE_LINE_SPACING, Float.toString(getConsoleLineSpacing())); } } if (DEFAULT_FONT_SIZE != getQuickDocFontSize()) { JdomKt.addOptionTag(parentNode, EDITOR_QUICK_JAVADOC_FONT_SIZE, getQuickDocFontSize().toString()); } Element colorElements = new Element(COLORS_ELEMENT); Element attrElements = new Element(ATTRIBUTES_ELEMENT); writeColors(colorElements); writeAttributes(attrElements); if (!colorElements.getChildren().isEmpty()) { parentNode.addContent(colorElements); } if (!attrElements.getChildren().isEmpty()) { parentNode.addContent(attrElements); } myIsSaveNeeded = false; } private static void writeLigaturesPreferences(Element parentNode, FontPreferences preferences, String optionName) { if (preferences.useLigatures()) { JdomKt.addOptionTag(parentNode, optionName, String.valueOf(true)); } } private static void writeFontPreferences(@NotNull String key, @NotNull Element parent, @NotNull FontPreferences preferences) { for (String fontFamily : preferences.getRealFontFamilies()) { Element element = new Element(key); JdomKt.addOptionTag(element, EDITOR_FONT_NAME, fontFamily); JdomKt.addOptionTag(element, EDITOR_FONT_SIZE, String.valueOf(preferences.getSize(fontFamily))); parent.addContent(element); } } private void writeAttributes(@NotNull Element attrElements) throws WriteExternalException { List<TextAttributesKey> list = new ArrayList<>(myAttributesMap.keySet()); list.sort(null); for (TextAttributesKey key : list) { writeAttribute(attrElements, key); } } private void writeAttribute(@NotNull Element attrElements, @NotNull TextAttributesKey key) { TextAttributes attributes = myAttributesMap.get(key); if (attributes == INHERITED_ATTRS_MARKER) { TextAttributesKey baseKey = key.getFallbackAttributeKey(); // IDEA-162774 do not store if inheritance = on in the parent scheme TextAttributes parentAttributes = myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedAttributes(key) : null; boolean parentOverwritingInheritance = parentAttributes != null && parentAttributes != INHERITED_ATTRS_MARKER; if (baseKey != null && parentOverwritingInheritance) { attrElements.addContent(new Element(OPTION_ELEMENT) .setAttribute(NAME_ATTR, key.getExternalName()) .setAttribute(BASE_ATTRIBUTES_ATTR, baseKey.getExternalName())); } return; } if (myParentScheme != null) { // fallback attributes must be not used, otherwise derived scheme as copy will not have such key TextAttributes parentAttributes = myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedAttributes(key) : myParentScheme.getAttributes(key); if (parentAttributes != null && attributes.equals(parentAttributes)) { return; } } Element valueElement = new Element(VALUE_ELEMENT); attributes.writeExternal(valueElement); attrElements.addContent(new Element(OPTION_ELEMENT).setAttribute(NAME_ATTR, key.getExternalName()).addContent(valueElement)); } public void optimizeAttributeMap() { EditorColorsScheme parentScheme = myParentScheme; if (parentScheme == null) { return; } myAttributesMap.keySet().removeAll(JBIterable.from(myAttributesMap.keySet()).filter( key -> { TextAttributes attrs = myAttributesMap.get(key); if (attrs == INHERITED_ATTRS_MARKER) { return !hasExplicitlyDefinedAttributes(parentScheme, key); } TextAttributes parent = parentScheme instanceof DefaultColorsScheme ? ((DefaultColorsScheme)parentScheme).getAttributes(key, false) : parentScheme.getAttributes(key); return Comparing.equal(parent, attrs); } ).toList()); myColorsMap.keySet().removeAll(JBIterable.from(myColorsMap.keySet()).filter( key -> { Color color = myColorsMap.get(key); if (color == INHERITED_COLOR_MARKER) { return !hasExplicitlyDefinedColors(parentScheme, key); } Color parent = parentScheme instanceof DefaultColorsScheme ? ((DefaultColorsScheme)parentScheme).getColor(key, false) : parentScheme.getColor(key); return Comparing.equal(parent, color == NULL_COLOR_MARKER ? null : color); } ).toList()); } private static boolean hasExplicitlyDefinedAttributes(@NotNull EditorColorsScheme scheme, @NotNull TextAttributesKey key) { TextAttributes directAttrs = scheme instanceof DefaultColorsScheme ? ((DefaultColorsScheme)scheme).getDirectlyDefinedAttributes(key) : null; return directAttrs != null && directAttrs != INHERITED_ATTRS_MARKER; } private static boolean hasExplicitlyDefinedColors(@NotNull EditorColorsScheme scheme, @NotNull ColorKey key) { Color directColor = scheme instanceof DefaultColorsScheme ? ((DefaultColorsScheme)scheme).getDirectlyDefinedColor(key) : null; return directColor != null && directColor != INHERITED_COLOR_MARKER; } @NotNull private Element metaInfoToElement() { Element metaInfoElement = new Element(META_INFO_ELEMENT); myMetaInfo.setProperty(META_INFO_MODIFIED_TIME, META_INFO_DATE_FORMAT.format(new Date())); List<String> sortedPropertyNames = new ArrayList<>(myMetaInfo.stringPropertyNames()); sortedPropertyNames.sort(null); for (String propertyName : sortedPropertyNames) { String value = myMetaInfo.getProperty(propertyName); Element propertyInfo = new Element(PROPERTY_ELEMENT); propertyInfo.setAttribute(PROPERTY_NAME_ATTR, propertyName); propertyInfo.setText(value); metaInfoElement.addContent(propertyInfo); } return metaInfoElement; } private void writeColors(Element colorElements) { List<ColorKey> list = new ArrayList<>(myColorsMap.keySet()); list.sort(null); for (ColorKey key : list) { writeColor(colorElements, key); } } private void writeColor(@NotNull Element colorElements, @NotNull ColorKey key) { Color color = myColorsMap.get(key); if (color == INHERITED_COLOR_MARKER) { ColorKey fallbackKey = key.getFallbackColorKey(); Color parentFallback = myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedColor(key) : null; boolean parentOverwritingInheritance = parentFallback != null && parentFallback != INHERITED_COLOR_MARKER; if (fallbackKey != null && parentOverwritingInheritance) { colorElements.addContent(new Element(OPTION_ELEMENT) .setAttribute(NAME_ATTR, key.getExternalName()) .setAttribute(BASE_ATTRIBUTES_ATTR, fallbackKey.getExternalName())); } return; } if (myParentScheme != null) { Color parent = myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedColor(key) : myParentScheme.getColor(key); if (parent != null && colorsEqual(color, parent)) { return; } } String rgb = color == NULL_COLOR_MARKER ? "" : Integer.toString(color.getRGB() & 0xFFFFFF, 16); JdomKt.addOptionTag(colorElements, key.getExternalName(), rgb); } private static boolean colorsEqual(@Nullable Color c1, @Nullable Color c2) { if (c1 == NULL_COLOR_MARKER) return c1 == c2; return Comparing.equal(c1, c2 == NULL_COLOR_MARKER ? null : c2); } private ModifiableFontPreferences ensureEditableFontPreferences() { if (!(myFontPreferences instanceof ModifiableFontPreferences)) { ModifiableFontPreferences editablePrefs = new FontPreferencesImpl(); myFontPreferences.copyTo(editablePrefs); myFontPreferences = editablePrefs; ((FontPreferencesImpl)myFontPreferences).setChangeListener(() -> initFonts()); } return (ModifiableFontPreferences)myFontPreferences; } @NotNull @Override public FontPreferences getConsoleFontPreferences() { return myConsoleFontPreferences; } @Override public void setUseEditorFontPreferencesInConsole() { myConsoleFontPreferences = new DelegatingFontPreferences(() -> myFontPreferences); initFonts(); } @Override public boolean isUseEditorFontPreferencesInConsole() { return myConsoleFontPreferences instanceof DelegatingFontPreferences; } @Override public void setConsoleFontPreferences(@NotNull FontPreferences preferences) { preferences.copyTo(ensureEditableConsoleFontPreferences()); initFonts(); } @Override public String getConsoleFontName() { return myConsoleFontPreferences.getFontFamily(); } private ModifiableFontPreferences ensureEditableConsoleFontPreferences() { if (!(myConsoleFontPreferences instanceof ModifiableFontPreferences)) { ModifiableFontPreferences editablePrefs = new FontPreferencesImpl(); myConsoleFontPreferences.copyTo(editablePrefs); myConsoleFontPreferences = editablePrefs; } return (ModifiableFontPreferences)myConsoleFontPreferences; } @Override public void setConsoleFontName(String fontName) { ModifiableFontPreferences consolePreferences = ensureEditableConsoleFontPreferences(); int consoleFontSize = getConsoleFontSize(); consolePreferences.clear(); consolePreferences.register(fontName, consoleFontSize); } @Override public int getConsoleFontSize() { String font = getConsoleFontName(); UISettings uiSettings = UISettings.getInstanceOrNull(); if ((uiSettings == null || !uiSettings.getPresentationMode()) && myConsoleFontPreferences.hasSize(font)) { return myConsoleFontPreferences.getSize(font); } return getEditorFontSize(); } @Override public void setConsoleFontSize(int fontSize) { ModifiableFontPreferences consoleFontPreferences = ensureEditableConsoleFontPreferences(); fontSize = EditorFontsConstants.checkAndFixEditorFontSize(fontSize); consoleFontPreferences.register(getConsoleFontName(), fontSize); initFonts(); } @Override public float getConsoleLineSpacing() { return myConsoleFontPreferences.getLineSpacing(); } @Override public void setConsoleLineSpacing(float lineSpacing) { ensureEditableConsoleFontPreferences().setLineSpacing(lineSpacing); } @Nullable protected TextAttributes getFallbackAttributes(@NotNull TextAttributesKey fallbackKey) { TextAttributesKey cur = fallbackKey; while (true) { TextAttributes attrs = getDirectlyDefinedAttributes(cur); TextAttributesKey next = cur.getFallbackAttributeKey(); if (attrs != null && (attrs != INHERITED_ATTRS_MARKER || next == null)) { return attrs; } if (next == null) return null; cur = next; } } @Nullable protected Color getFallbackColor(@NotNull ColorKey fallbackKey) { ColorKey cur = fallbackKey; while (true) { Color color = getDirectlyDefinedColor(cur); if (color == NULL_COLOR_MARKER) return null; ColorKey next = cur.getFallbackColorKey(); if (color != null && (color != INHERITED_COLOR_MARKER || next == null)) { return color; } if (next == null) return null; cur = next; } } /** * Looks for explicitly specified attributes either in the scheme or its parent scheme. No fallback keys are used. * * @param key The key to use for search. * @return Explicitly defined attribute or {@code null} if not found. */ @Nullable public TextAttributes getDirectlyDefinedAttributes(@NotNull TextAttributesKey key) { TextAttributes attributes = myAttributesMap.get(key); return attributes != null ? attributes : myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedAttributes(key) : null; } /** * Looks for explicitly specified color either in the scheme or its parent scheme. No fallback keys are used. * * @param key The key to use for search. * @return Explicitly defined color or {@code null} if not found. */ @Nullable public Color getDirectlyDefinedColor(@NotNull ColorKey key) { Color color = myColorsMap.get(key); return color != null ? color : myParentScheme instanceof AbstractColorsScheme ? ((AbstractColorsScheme)myParentScheme).getDirectlyDefinedColor(key) : null; } @NotNull @Override public SchemeState getSchemeState() { return myIsSaveNeeded ? SchemeState.POSSIBLY_CHANGED : SchemeState.UNCHANGED; } public void setSaveNeeded(boolean value) { myIsSaveNeeded = value; } public boolean isReadOnly() { return false; } @NotNull @Override public Properties getMetaProperties() { return myMetaInfo; } public boolean canBeDeleted() { return myCanBeDeleted; } public void setCanBeDeleted(boolean canBeDeleted) { myCanBeDeleted = canBeDeleted; } public boolean isVisible() { return true; } public static boolean isVisible(@NotNull EditorColorsScheme scheme) { return !(scheme instanceof AbstractColorsScheme) || ((AbstractColorsScheme)scheme).isVisible(); } @Nullable public AbstractColorsScheme getOriginal() { String originalSchemeName = getMetaProperties().getProperty(META_INFO_ORIGINAL); if (originalSchemeName != null) { EditorColorsScheme originalScheme = EditorColorsManager.getInstance().getScheme(originalSchemeName); if (originalScheme instanceof AbstractColorsScheme) return (AbstractColorsScheme)originalScheme; } return null; } public EditorColorsScheme getParentScheme() { return myParentScheme; } @NotNull @Override public Element writeScheme() { Element root = new Element("scheme"); writeExternal(root); return root; } public boolean settingsEqual(Object other) { return settingsEqual(other, null); } public boolean settingsEqual(Object other, @Nullable Predicate<ColorKey> colorKeyFilter) { if (!(other instanceof AbstractColorsScheme)) return false; AbstractColorsScheme otherScheme = (AbstractColorsScheme)other; // parent is used only for default schemes (e.g. Darcula bundled in all ide (opposite to IDE-specific, like Cobalt)) if (getBaseDefaultScheme(this) != getBaseDefaultScheme(otherScheme)) { return false; } for (String propertyName : myMetaInfo.stringPropertyNames()) { if (propertyName.equals(META_INFO_CREATION_TIME) || propertyName.equals(META_INFO_MODIFIED_TIME) || propertyName.equals(META_INFO_IDE) || propertyName.equals(META_INFO_IDE_VERSION) || propertyName.equals(META_INFO_ORIGINAL) ) { continue; } if (!Comparing.equal(myMetaInfo.getProperty(propertyName), otherScheme.myMetaInfo.getProperty(propertyName))) { return false; } } return areDelegatingOrEqual(myFontPreferences, otherScheme.getFontPreferences()) && areDelegatingOrEqual(myConsoleFontPreferences, otherScheme.getConsoleFontPreferences()) && attributesEqual(otherScheme) && colorsEqual(otherScheme, colorKeyFilter); } protected static boolean areDelegatingOrEqual(@NotNull FontPreferences preferences1, @NotNull FontPreferences preferences2) { boolean isDelegating1 = preferences1 instanceof DelegatingFontPreferences; boolean isDelegating2 = preferences2 instanceof DelegatingFontPreferences; return isDelegating1 || isDelegating2 ? isDelegating1 && isDelegating2 : preferences1.equals(preferences2); } protected boolean attributesEqual(AbstractColorsScheme otherScheme) { return myAttributesMap.equals(otherScheme.myAttributesMap); } protected boolean colorsEqual(AbstractColorsScheme otherScheme, @Nullable Predicate<ColorKey> colorKeyFilter) { if (myColorsMap.size() != otherScheme.myColorsMap.size()) return false; for (ColorKey key : myColorsMap.keySet()) { Color c1 = myColorsMap.get(key); Color c2 = otherScheme.myColorsMap.get(key); if (!colorsEqual(c1, c2)) return false; } return true; } @Nullable private static EditorColorsScheme getBaseDefaultScheme(@NotNull EditorColorsScheme scheme) { if (!(scheme instanceof AbstractColorsScheme)) { return null; } if (scheme instanceof DefaultColorsScheme) { return scheme; } EditorColorsScheme parent = ((AbstractColorsScheme)scheme).myParentScheme; return parent != null ? getBaseDefaultScheme(parent) : null; } private static class TemporaryParent extends EditorColorsSchemeImpl { private static final Logger LOG = Logger.getInstance(TemporaryParent.class); private final String myParentName; private boolean isErrorReported; public TemporaryParent(@NotNull String parentName) { super(EmptyColorScheme.INSTANCE); myParentName = parentName; } public String getParentName() { return myParentName; } @Override public TextAttributes getAttributes(@Nullable TextAttributesKey key) { reportError(); return super.getAttributes(key); } @Nullable @Override public Color getColor(ColorKey key) { reportError(); return super.getColor(key); } private void reportError() { if (!isErrorReported) { LOG.error("Unresolved link to " + myParentName); isErrorReported = true; } } } public void setParent(@NotNull EditorColorsScheme newParent) { assert newParent instanceof ReadOnlyColorsScheme : "New parent scheme must be read-only"; myParentScheme = newParent; } void resolveParent(@NotNull Function<String,EditorColorsScheme> nameResolver) { if (myParentScheme instanceof TemporaryParent) { String parentName = ((TemporaryParent)myParentScheme).getParentName(); EditorColorsScheme newParent = nameResolver.apply(parentName); if (!(newParent instanceof ReadOnlyColorsScheme)) { throw new InvalidDataException(parentName); } myParentScheme = newParent; } } }
package com.example.ideveloper.sunshine; /** * Created by iDeveloper on 2/28/15. */ import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A placeholder fragment containing a simple view. */ public class ForecastFragment extends Fragment { private ArrayAdapter<String> mForecastAdapter; public ForecastFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment,menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id==R.id.action_refresh){ FetchWeatherTask weatherTask= new FetchWeatherTask(); weatherTask.execute("20903"); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); String[] foreCastArray= { "Today - Sunny - 88/63", "Tomorrow - Foggy - 70/46", "Weds - Cloudy - 72/63", "Thurs - Asteroids - 75/65", "Fri - Heavy Rain -65/66", "Sat - HELP TRAPPED IN WEATHERSTATION - 60/51", "Sun - Sunny - 80/68" }; List<String> weekForeCast=new ArrayList<String>(Arrays.asList(foreCastArray)); mForecastAdapter=new ArrayAdapter<String>( getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForeCast); ListView listView=(ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String forecast= mForecastAdapter.getItem(position); //Toast.makeText(getActivity(),forecast,Toast.LENGTH_SHORT).show(); Intent intent= new Intent(getActivity(),DetailActivity.class).putExtra(Intent.EXTRA_TEXT,forecast); startActivity(intent); } }); return rootView; } private class FetchWeatherTask extends AsyncTask<String,Void,String[]> { private final String LOG_TAG=FetchWeatherTask.class.getSimpleName(); protected String[] doInBackground(String... params) { if(params.length==0){ return null; } HttpURLConnection urlConnection=null; BufferedReader reader= null; String[] strArray={}; //will contain the raw json response as a string. String forecastJsonStr=null; String format="json"; String units="metric"; int numDays=7; try { //Construct the URL for thr OpenWeatherMap query //possible parameters are available at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL="http://api.openweathermap.org/data/2.5/forecast/daily"; final String QUERY_PARAM="q"; final String FORMAT_PARAM="mode"; final String UNITS_PARAM="units"; final String DAYS_PARAM="cnt"; Uri builtUri= Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM,params[0]) .appendQueryParameter(FORMAT_PARAM,format) .appendQueryParameter(UNITS_PARAM,units) .appendQueryParameter(DAYS_PARAM,Integer.toString(numDays)).build(); URL url= new URL(builtUri.toString()); Log.v(LOG_TAG,"Built URI "+builtUri.toString()); urlConnection=(HttpURLConnection)url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); //read the input stream into a string InputStream inputStream= urlConnection.getInputStream(); StringBuffer buffer= new StringBuffer(); if(inputStream==null){ //nothing to do. forecastJsonStr=null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while((line=reader.readLine())!=null ) { //Since it's JSON, adding a newline isn't necessary (it won't affect parsing) buffer.append(line +"\n"); } if(buffer.length()==0) { forecastJsonStr=null; } forecastJsonStr=buffer.toString(); Log.e(LOG_TAG, forecastJsonStr); try{ WeatherDataParser d= new WeatherDataParser(); strArray =d.getWeatherDataFromJson( forecastJsonStr,numDays); }catch (JSONException e){ Log.e(LOG_TAG,e.getMessage(),e); e.printStackTrace(); } } catch (IOException e) { Log.e(LOG_TAG, "Error", e); forecastJsonStr=null; } finally { if(urlConnection !=null){ urlConnection.disconnect(); } if(reader !=null){ try{ reader.close(); }catch (final IOException e){ Log.e(LOG_TAG,"Error CLosing stream",e); } } } return strArray; } @Override protected void onPostExecute(String[] result) { if(result !=null){ mForecastAdapter.clear(); for (String dayForecastStr:result){ mForecastAdapter.add(dayForecastStr); } } } } }
/** */ package analysismetamodel.impl; import analysismetamodel.AnalysismetamodelPackage; import analysismetamodel.EnsembleInvocableByCustomFunc; import analysismetamodel.KnowledgeBinding; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ensemble Invocable By Custom Func</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link analysismetamodel.impl.EnsembleInvocableByCustomFuncImpl#getOutputKnowledgeBinding <em>Output Knowledge Binding</em>}</li> * <li>{@link analysismetamodel.impl.EnsembleInvocableByCustomFuncImpl#getInputKnowledgeBindings <em>Input Knowledge Bindings</em>}</li> * <li>{@link analysismetamodel.impl.EnsembleInvocableByCustomFuncImpl#isDoCartesianProduct <em>Do Cartesian Product</em>}</li> * </ul> * </p> * * @generated */ public class EnsembleInvocableByCustomFuncImpl extends MinimalEObjectImpl.Container implements EnsembleInvocableByCustomFunc { /** * The cached value of the '{@link #getOutputKnowledgeBinding() <em>Output Knowledge Binding</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOutputKnowledgeBinding() * @generated * @ordered */ protected KnowledgeBinding outputKnowledgeBinding; /** * The cached value of the '{@link #getInputKnowledgeBindings() <em>Input Knowledge Bindings</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInputKnowledgeBindings() * @generated * @ordered */ protected EList<KnowledgeBinding> inputKnowledgeBindings; /** * The default value of the '{@link #isDoCartesianProduct() <em>Do Cartesian Product</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDoCartesianProduct() * @generated * @ordered */ protected static final boolean DO_CARTESIAN_PRODUCT_EDEFAULT = false; /** * The cached value of the '{@link #isDoCartesianProduct() <em>Do Cartesian Product</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDoCartesianProduct() * @generated * @ordered */ protected boolean doCartesianProduct = DO_CARTESIAN_PRODUCT_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EnsembleInvocableByCustomFuncImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AnalysismetamodelPackage.Literals.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KnowledgeBinding getOutputKnowledgeBinding() { return outputKnowledgeBinding; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOutputKnowledgeBinding(KnowledgeBinding newOutputKnowledgeBinding, NotificationChain msgs) { KnowledgeBinding oldOutputKnowledgeBinding = outputKnowledgeBinding; outputKnowledgeBinding = newOutputKnowledgeBinding; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING, oldOutputKnowledgeBinding, newOutputKnowledgeBinding); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOutputKnowledgeBinding(KnowledgeBinding newOutputKnowledgeBinding) { if (newOutputKnowledgeBinding != outputKnowledgeBinding) { NotificationChain msgs = null; if (outputKnowledgeBinding != null) msgs = ((InternalEObject)outputKnowledgeBinding).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING, null, msgs); if (newOutputKnowledgeBinding != null) msgs = ((InternalEObject)newOutputKnowledgeBinding).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING, null, msgs); msgs = basicSetOutputKnowledgeBinding(newOutputKnowledgeBinding, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING, newOutputKnowledgeBinding, newOutputKnowledgeBinding)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<KnowledgeBinding> getInputKnowledgeBindings() { if (inputKnowledgeBindings == null) { inputKnowledgeBindings = new EObjectResolvingEList<KnowledgeBinding>(KnowledgeBinding.class, this, AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__INPUT_KNOWLEDGE_BINDINGS); } return inputKnowledgeBindings; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isDoCartesianProduct() { return doCartesianProduct; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDoCartesianProduct(boolean newDoCartesianProduct) { boolean oldDoCartesianProduct = doCartesianProduct; doCartesianProduct = newDoCartesianProduct; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__DO_CARTESIAN_PRODUCT, oldDoCartesianProduct, doCartesianProduct)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING: return basicSetOutputKnowledgeBinding(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING: return getOutputKnowledgeBinding(); case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__INPUT_KNOWLEDGE_BINDINGS: return getInputKnowledgeBindings(); case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__DO_CARTESIAN_PRODUCT: return isDoCartesianProduct(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING: setOutputKnowledgeBinding((KnowledgeBinding)newValue); return; case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__INPUT_KNOWLEDGE_BINDINGS: getInputKnowledgeBindings().clear(); getInputKnowledgeBindings().addAll((Collection<? extends KnowledgeBinding>)newValue); return; case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__DO_CARTESIAN_PRODUCT: setDoCartesianProduct((Boolean)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING: setOutputKnowledgeBinding((KnowledgeBinding)null); return; case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__INPUT_KNOWLEDGE_BINDINGS: getInputKnowledgeBindings().clear(); return; case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__DO_CARTESIAN_PRODUCT: setDoCartesianProduct(DO_CARTESIAN_PRODUCT_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__OUTPUT_KNOWLEDGE_BINDING: return outputKnowledgeBinding != null; case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__INPUT_KNOWLEDGE_BINDINGS: return inputKnowledgeBindings != null && !inputKnowledgeBindings.isEmpty(); case AnalysismetamodelPackage.ENSEMBLE_INVOCABLE_BY_CUSTOM_FUNC__DO_CARTESIAN_PRODUCT: return doCartesianProduct != DO_CARTESIAN_PRODUCT_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (DoCartesianProduct: "); result.append(doCartesianProduct); result.append(')'); return result.toString(); } } //EnsembleInvocableByCustomFuncImpl
package org.robolectric.shadows; import android.app.Application; import android.appwidget.AppWidgetManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.IContentProvider; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.PowerManager; import android.view.Display; import android.view.LayoutInflater; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.Toast; import org.robolectric.RuntimeEnvironment; import org.robolectric.manifest.AndroidManifest; import org.robolectric.Shadows; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.manifest.BroadcastReceiverData; import org.robolectric.res.ResourceLoader; import org.robolectric.util.Scheduler; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static android.content.pm.PackageManager.PERMISSION_DENIED; import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static org.robolectric.Shadows.shadowOf; import static org.robolectric.internal.Shadow.newInstanceOf; /** * Shadows the {@code android.app.Application} class. */ @SuppressWarnings({"UnusedDeclaration"}) @Implements(Application.class) public class ShadowApplication extends ShadowContextWrapper { @RealObject private Application realApplication; private AndroidManifest appManifest; private ResourceLoader resourceLoader; private ContentResolver contentResolver; private List<Intent> startedActivities = new ArrayList<Intent>(); private List<Intent> startedServices = new ArrayList<Intent>(); private List<Intent> stoppedServies = new ArrayList<Intent>(); private List<Intent> broadcastIntents = new ArrayList<Intent>(); private List<ServiceConnection> unboundServiceConnections = new ArrayList<ServiceConnection>(); private List<Wrapper> registeredReceivers = new ArrayList<Wrapper>(); private Map<String, Intent> stickyIntents = new LinkedHashMap<String, Intent>(); private Looper mainLooper = ShadowLooper.myLooper(); private Handler mainHandler = new Handler(mainLooper); private Scheduler backgroundScheduler = new Scheduler(); private Map<String, Map<String, Object>> sharedPreferenceMap = new HashMap<String, Map<String, Object>>(); private ArrayList<Toast> shownToasts = new ArrayList<Toast>(); private PowerManager.WakeLock latestWakeLock; private ShadowAlertDialog latestAlertDialog; private ShadowDialog latestDialog; private ShadowPopupMenu latestPopupMenu; private Object bluetoothAdapter = newInstanceOf("android.bluetooth.BluetoothAdapter"); private Resources resources; private AssetManager assetManager; private Set<String> grantedPermissions = new HashSet<String>(); // these are managed by the AppSingletonizier... kinda gross, sorry [xw] LayoutInflater layoutInflater; AppWidgetManager appWidgetManager; private ServiceConnection serviceConnection; private ComponentName componentNameForBindService; private IBinder serviceForBindService; private List<String> unbindableActions = new ArrayList<String>(); private boolean strictI18n = false; private boolean checkActivities; private PopupWindow latestPopupWindow; private ListPopupWindow latestListPopupWindow; public static ShadowApplication getInstance() { return RuntimeEnvironment.application == null ? null : shadowOf(RuntimeEnvironment.application); } /** * Runs any background tasks previously queued by {@link android.os.AsyncTask#execute(Object[])}. * * <p> * Note: calling this method does not pause or un-pause the scheduler. */ public static void runBackgroundTasks() { getInstance().getBackgroundScheduler().advanceBy(0); } public static void setDisplayMetricsDensity(float densityMultiplier) { shadowOf(getInstance().getResources()).setDensity(densityMultiplier); } public static void setDefaultDisplay(Display display) { shadowOf(getInstance().getResources()).setDisplay(display); } /** * Associates a {@code ResourceLoader} with an {@code Application} instance. * * @param appManifest Android manifest. * @param resourceLoader Resource loader. */ public void bind(AndroidManifest appManifest, ResourceLoader resourceLoader) { if (this.resourceLoader != null) throw new RuntimeException("ResourceLoader already set!"); this.appManifest = appManifest; this.resourceLoader = resourceLoader; if (appManifest != null) { setPackageName(appManifest.getPackageName()); setApplicationName(appManifest.getApplicationName()); this.registerBroadcastReceivers(appManifest); } } private void registerBroadcastReceivers(AndroidManifest androidManifest) { for (BroadcastReceiverData receiver : androidManifest.getBroadcastReceivers()) { IntentFilter filter = new IntentFilter(); for (String action : receiver.getActions()) { filter.addAction(action); } String receiverClassName = replaceLastDotWith$IfInnerStaticClass(receiver.getClassName()); registerReceiver((BroadcastReceiver) newInstanceOf(receiverClassName), filter); } } private static String replaceLastDotWith$IfInnerStaticClass(String receiverClassName) { String[] splits = receiverClassName.split("\\."); String staticInnerClassRegex = "[A-Z][a-zA-Z]*"; if (splits[splits.length - 1].matches(staticInnerClassRegex) && splits[splits.length - 2].matches(staticInnerClassRegex)) { int lastDotIndex = receiverClassName.lastIndexOf("."); StringBuilder buffer = new StringBuilder(receiverClassName); buffer.setCharAt(lastDotIndex, '$'); return buffer.toString(); } return receiverClassName; } public List<Toast> getShownToasts() { return shownToasts; } public Scheduler getBackgroundScheduler() { return backgroundScheduler; } @Override @Implementation public Context getApplicationContext() { return realApplication; } @Override @Implementation public AssetManager getAssets() { if (assetManager == null) { assetManager = ShadowAssetManager.bind(newInstanceOf(AssetManager.class), appManifest, resourceLoader); } return assetManager; } @Override @Implementation public Resources getResources() { if (resources == null) { resources = new Resources(realApplication.getAssets(), null, new Configuration()); } return resources; } /** * Reset (set to null) resources instance, so they will be reloaded next time they are * {@link #getResources gotten} */ public void resetResources(){ resources = null; } @Implementation @Override public ContentResolver getContentResolver() { if (contentResolver == null) { contentResolver = new ContentResolver(realApplication) { @Override protected IContentProvider acquireProvider(Context c, String name) { return null; } @Override public boolean releaseProvider(IContentProvider icp) { return false; } @Override protected IContentProvider acquireUnstableProvider(Context c, String name) { return null; } @Override public boolean releaseUnstableProvider(IContentProvider icp) { return false; } @Override public void unstableProviderDied(IContentProvider icp) { } }; } return contentResolver; } @Implementation @Override public void startActivity(Intent intent) { verifyActivityInManifest(intent); startedActivities.add(intent); } @Implementation @Override public void startActivity(Intent intent, Bundle options) { verifyActivityInManifest(intent); startedActivities.add(intent); } @Implementation @Override public ComponentName startService(Intent intent) { startedServices.add(intent); if (intent.getComponent() != null) { return intent.getComponent(); } return new ComponentName("some.service.package", "SomeServiceName-FIXME"); } @Implementation @Override public boolean stopService(Intent name) { stoppedServies.add(name); return startedServices.contains(name); } public void setComponentNameAndServiceForBindService(ComponentName name, IBinder service) { this.componentNameForBindService = name; this.serviceForBindService = service; } @Implementation public boolean bindService(Intent intent, final ServiceConnection serviceConnection, int i) { if (unbindableActions.contains(intent.getAction())) { return false; } startedServices.add(intent); shadowOf(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { serviceConnection.onServiceConnected(componentNameForBindService, serviceForBindService); } }, 0); return true; } @Override @Implementation public void unbindService(final ServiceConnection serviceConnection) { unboundServiceConnections.add(serviceConnection); shadowOf(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { serviceConnection.onServiceDisconnected(componentNameForBindService); } }, 0); } public List<ServiceConnection> getUnboundServiceConnections() { return unboundServiceConnections; } /** * Consumes the most recent {@code Intent} started by {@link #startActivity(android.content.Intent)} and returns it. * * @return the most recently started {@code Intent} */ @Override public Intent getNextStartedActivity() { if (startedActivities.isEmpty()) { return null; } else { return startedActivities.remove(0); } } /** * Returns the most recent {@code Intent} started by {@link #startActivity(android.content.Intent)} without * consuming it. * * @return the most recently started {@code Intent} */ @Override public Intent peekNextStartedActivity() { if (startedActivities.isEmpty()) { return null; } else { return startedActivities.get(0); } } /** * Consumes the most recent {@code Intent} started by {@link #startService(android.content.Intent)} and returns it. * * @return the most recently started {@code Intent} */ @Override public Intent getNextStartedService() { if (startedServices.isEmpty()) { return null; } else { return startedServices.remove(0); } } /** * Returns the most recent {@code Intent} started by {@link #startService(android.content.Intent)} without * consuming it. * * @return the most recently started {@code Intent} */ @Override public Intent peekNextStartedService() { if (startedServices.isEmpty()) { return null; } else { return startedServices.get(0); } } /** * Clears all {@code Intent} started by {@link #startService(android.content.Intent)} */ @Override public void clearStartedServices() { startedServices.clear(); } /** * Consumes the {@code Intent} requested to stop a service by {@link #stopService(android.content.Intent)} * from the bottom of the stack of stop requests. */ @Override public Intent getNextStoppedService() { if (stoppedServies.isEmpty()) { return null; } else { return stoppedServies.remove(0); } } /** * Non-Android accessor (and a handy way to get a working {@code ResourceLoader} * * @return the {@code ResourceLoader} associated with this Application */ public ResourceLoader getResourceLoader() { return resourceLoader; } @Override @Implementation public void sendBroadcast(Intent intent) { sendBroadcastWithPermission(intent, null); } @Override @Implementation public void sendBroadcast(Intent intent, String receiverPermission) { sendBroadcastWithPermission(intent, receiverPermission); } @Override @Implementation public void sendOrderedBroadcast(Intent intent, String receiverPermission) { sendOrderedBroadcastWithPermission(intent, receiverPermission); } /* Returns the BroadcaseReceivers wrappers, matching intent's action and permissions. */ private List<Wrapper> getAppropriateWrappers(Intent intent, String receiverPermission) { broadcastIntents.add(intent); List<Wrapper> result = new ArrayList<Wrapper>(); List<Wrapper> copy = new ArrayList<Wrapper>(); copy.addAll(registeredReceivers); for (Wrapper wrapper : copy) { if (hasMatchingPermission(wrapper.broadcastPermission, receiverPermission) && wrapper.intentFilter.matchAction(intent.getAction())) { final int match = wrapper.intentFilter.matchData(intent.getType(), intent.getScheme(), intent.getData()); if (match != IntentFilter.NO_MATCH_DATA && match != IntentFilter.NO_MATCH_TYPE) { result.add(wrapper); } } } return result; } private void postIntent(Intent intent, Wrapper wrapper, final AtomicBoolean abort) { final Handler scheduler = (wrapper.scheduler != null) ? wrapper.scheduler : this.mainHandler; final BroadcastReceiver receiver = wrapper.broadcastReceiver; final ShadowBroadcastReceiver shReceiver = Shadows.shadowOf(receiver); final Intent broadcastIntent = intent; scheduler.post(new Runnable() { @Override public void run() { shReceiver.onReceive(realApplication, broadcastIntent, abort); } }); } private void postToWrappers(List<Wrapper> wrappers, Intent intent, String receiverPermission) { AtomicBoolean abort = new AtomicBoolean(false); // abort state is shared among all broadcast receivers for (Wrapper wrapper: wrappers) { postIntent(intent, wrapper, abort); } } /** * Broadcasts the {@code Intent} by iterating through the registered receivers, invoking their filters including * permissions, and calling {@code onReceive(Application, Intent)} as appropriate. Does not enqueue the * {@code Intent} for later inspection. * * @param intent the {@code Intent} to broadcast * todo: enqueue the Intent for later inspection */ private void sendBroadcastWithPermission(Intent intent, String receiverPermission) { List<Wrapper> wrappers = getAppropriateWrappers(intent, receiverPermission); postToWrappers(wrappers, intent, receiverPermission); } private void sendOrderedBroadcastWithPermission(Intent intent, String receiverPermission) { List<Wrapper> wrappers = getAppropriateWrappers(intent, receiverPermission); // sort by the decrease of priorities Collections.sort(wrappers, new Comparator<Wrapper>() { @Override public int compare(Wrapper o1, Wrapper o2) { return Integer.compare(o2.getIntentFilter().getPriority(), o1.getIntentFilter().getPriority()); } }); postToWrappers(wrappers, intent, receiverPermission); } public List<Intent> getBroadcastIntents() { return broadcastIntents; } @Implementation public void sendStickyBroadcast(Intent intent) { stickyIntents.put(intent.getAction(), intent); sendBroadcast(intent); } /** * Always returns {@code null} * * @return {@code null} */ @Override @Implementation public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { return registerReceiverWithContext(receiver, filter, null, null, realApplication); } @Override @Implementation public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return registerReceiverWithContext(receiver, filter, broadcastPermission, scheduler, realApplication); } Intent registerReceiverWithContext(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { if (receiver != null) { registeredReceivers.add(new Wrapper(receiver, filter, context, broadcastPermission, scheduler)); } return processStickyIntents(filter, receiver, context); } private void verifyActivityInManifest(Intent intent) { if (checkActivities && getPackageManager().resolveActivity(intent, -1) == null) { throw new ActivityNotFoundException(intent.getAction()); } } private Intent processStickyIntents(IntentFilter filter, BroadcastReceiver receiver, Context context) { Intent result = null; for (Intent stickyIntent : stickyIntents.values()) { if (filter.matchAction(stickyIntent.getAction())) { if (result == null) { result = stickyIntent; } if (receiver != null) { receiver.onReceive(context, stickyIntent); } else if (result != null) { break; } } } return result; } @Override @Implementation public void unregisterReceiver(BroadcastReceiver broadcastReceiver) { boolean found = false; Iterator<Wrapper> iterator = registeredReceivers.iterator(); while (iterator.hasNext()) { Wrapper wrapper = iterator.next(); if (wrapper.broadcastReceiver == broadcastReceiver) { iterator.remove(); found = true; } } if (!found) { throw new IllegalArgumentException("Receiver not registered: " + broadcastReceiver); } } /** * Iterates through all of the registered receivers on this {@code Application} and if any of them match the given * {@code Context} object throws a {@code RuntimeException} * * @param context the {@code Context} to check for on each of the remaining registered receivers * @param type the type to report for the context if an exception is thrown * @throws RuntimeException if there are any recievers registered with the given {@code Context} */ public void assertNoBroadcastListenersRegistered(Context context, String type) { for (Wrapper registeredReceiver : registeredReceivers) { if (registeredReceiver.context == context) { RuntimeException e = new IllegalStateException(type + " " + context + " leaked has leaked IntentReceiver " + registeredReceiver.broadcastReceiver + " that was originally registered here. " + "Are you missing a call to unregisterReceiver()?"); e.setStackTrace(registeredReceiver.exception.getStackTrace()); throw e; } } } public void assertNoBroadcastListenersOfActionRegistered(Context context, String action) { for (Wrapper registeredReceiver : registeredReceivers) { if (registeredReceiver.context == context) { Iterator<String> actions = registeredReceiver.intentFilter.actionsIterator(); while (actions.hasNext()) { if (actions.next().equals(action)) { RuntimeException e = new IllegalStateException("Unexpected BroadcastReceiver on " + context + " with action " + action + " " + registeredReceiver.broadcastReceiver + " that was originally registered here:"); e.setStackTrace(registeredReceiver.exception.getStackTrace()); throw e; } } } } } public boolean hasReceiverForIntent(Intent intent) { for (Wrapper wrapper : registeredReceivers) { if (wrapper.intentFilter.matchAction(intent.getAction())) { return true; } } return false; } public List<BroadcastReceiver> getReceiversForIntent(Intent intent) { ArrayList<BroadcastReceiver> broadcastReceivers = new ArrayList<BroadcastReceiver>(); for (Wrapper wrapper : registeredReceivers) { if (wrapper.intentFilter.matchAction(intent.getAction())) { broadcastReceivers.add(wrapper.getBroadcastReceiver()); } } return broadcastReceivers; } /** * Non-Android accessor. * * @return list of {@link Wrapper}s for registered receivers */ public List<Wrapper> getRegisteredReceivers() { return registeredReceivers; } /** * Non-Android accessor. * * @return the layout inflater used by this {@code Application} */ public LayoutInflater getLayoutInflater() { return layoutInflater; } /** * Non-Android accessor. * * @return the app widget manager used by this {@code Application} */ public AppWidgetManager getAppWidgetManager() { return appWidgetManager; } @Override @Implementation public Looper getMainLooper() { return mainLooper; } public Map<String, Map<String, Object>> getSharedPreferenceMap() { return sharedPreferenceMap; } public ShadowAlertDialog getLatestAlertDialog() { return latestAlertDialog; } public void setLatestAlertDialog(ShadowAlertDialog latestAlertDialog) { this.latestAlertDialog = latestAlertDialog; } public ShadowDialog getLatestDialog() { return latestDialog; } public void setLatestDialog(ShadowDialog latestDialog) { this.latestDialog = latestDialog; } public Object getBluetoothAdapter() { return bluetoothAdapter; } public void declareActionUnbindable(String action) { unbindableActions.add(action); } @Deprecated public void setSystemService(String key, Object service) { ((ShadowContextImpl) shadowOf(realApplication.getBaseContext())).setSystemService(key, service); } public PowerManager.WakeLock getLatestWakeLock() { return latestWakeLock; } public void addWakeLock( PowerManager.WakeLock wl ) { latestWakeLock = wl; } public void clearWakeLocks() { latestWakeLock = null; } public boolean isStrictI18n() { return strictI18n; } public void setStrictI18n(boolean strictI18n) { this.strictI18n = strictI18n; } public AndroidManifest getAppManifest() { return appManifest; } private final Map<String, Object> singletons = new HashMap<String, Object>(); public <T> T getSingleton(Class<T> clazz, Provider<T> provider) { synchronized (singletons) { //noinspection unchecked T item = (T) singletons.get(clazz.getName()); if (item == null) { singletons.put(clazz.getName(), item = provider.get()); } return item; } } /** * Set to true if you'd like Robolectric to strictly simulate the real Android behavior when * calling {@link Context#startActivity(android.content.Intent)}. Real Android throws a * {@link android.content.ActivityNotFoundException} if given * an {@link Intent} that is not known to the {@link android.content.pm.PackageManager} * * By default, this behavior is off (false). * * @param checkActivities True to validate activities. */ public void checkActivities(boolean checkActivities) { this.checkActivities = checkActivities; } public ShadowPopupMenu getLatestPopupMenu() { return latestPopupMenu; } public void setLatestPopupMenu(ShadowPopupMenu latestPopupMenu) { this.latestPopupMenu = latestPopupMenu; } public PopupWindow getLatestPopupWindow() { return latestPopupWindow; } public void setLatestPopupWindow(PopupWindow latestPopupWindow) { this.latestPopupWindow = latestPopupWindow; } public ListPopupWindow getLatestListPopupWindow() { return latestListPopupWindow; } public void setLatestListPopupWindow(ListPopupWindow latestListPopupWindow) { this.latestListPopupWindow = latestListPopupWindow; } public class Wrapper { public BroadcastReceiver broadcastReceiver; public IntentFilter intentFilter; public Context context; public Throwable exception; public String broadcastPermission; public Handler scheduler; public Wrapper(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, Context context, String broadcastPermission, Handler scheduler) { this.broadcastReceiver = broadcastReceiver; this.intentFilter = intentFilter; this.context = context; this.broadcastPermission = broadcastPermission; this.scheduler = scheduler; exception = new Throwable(); } public BroadcastReceiver getBroadcastReceiver() { return broadcastReceiver; } public IntentFilter getIntentFilter() { return intentFilter; } public Context getContext() { return context; } } @Implementation public int checkPermission(String permission, int pid, int uid) { return grantedPermissions.contains(permission) ? PERMISSION_GRANTED : PERMISSION_DENIED; } public void grantPermissions(String... permissionNames) { for (String permissionName : permissionNames) { grantedPermissions.add(permissionName); } } public void denyPermissions(String... permissionNames) { for (String permissionName : permissionNames) { grantedPermissions.remove(permissionName); } } private boolean hasMatchingPermission(String permission1, String permission2) { return permission1 == null ? permission2 == null : permission1.equals(permission2); } }
package com.bitgate.nucleus.render.tag; import com.bitgate.nucleus.render.tag.system.SystemDocumentTag; import com.bitgate.nucleus.render.RenderContext; import com.bitgate.nucleus.render.tag.system.SystemTextTag; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.List; import java.util.Map; /** * This class is the heart of a renderable tag in the uQML language. Any created tags must extend this class in order * to be rendered properly. */ public class DocumentTag { private static final org.slf4j.Logger log = LoggerFactory.getLogger(DocumentTag.class); private String tagName; protected final Node thisNode; protected StringBuilder data; protected List<DocumentTag> children; private final String varname; /** * This is an enumeration that indicates whether or not the subnodes in a tree should be processed. Setting the * flag to {@code NO_TRAVERSE} will not process the tags within the node; they will be reserved for traversal by * the tag at evaluation time. */ public enum DocumentTagTraversal { /** Indicates that the system should traverse all nodes, and wrap them. */ TRAVERSE_NODES, /** Indicates that only the top level node should be wrapped, all subnodes are excluded from processing. */ NO_TRAVERSE } /** * This constructor allows you to construct a new {@code DocumentTag} with or without recursion. The node traversal * will occur when {@link DocumentTagTraversal#TRAVERSE_NODES} is set. If not set, the elements will not be walked, * so that this can manually be done through other tags. This is useful for things like evaluations, or if/then/else * logic, where the nodes are not parsed until the condition is met. * * @param node The {@link Node} object to parse. * @param traversal {@link DocumentTagTraversal} flag indicating whether or not the nodes in this tree should be walked. */ public DocumentTag(Node node, DocumentTagTraversal traversal) { this.thisNode = node; this.varname = getAttribute(thisNode, "var"); if (traversal == DocumentTagTraversal.TRAVERSE_NODES) { walkNodeTree(); } } /** * The current node for the {@code DocumentTag}. Sets {@code "this"} reference to the current {@link Node} being * processed. Automatically walks any of the child nodes from this position, and stores references to them, while * rendering the body of each of the tags within. (This is the same as calling the constructor with the * {@link DocumentTagTraversal#TRAVERSE_NODES} value set.) * * <p>Storing child tags allows you to render dynamic content in the background, store the rendered results in a * separate variable, or anything else you wish to do. * * @param node {@link Node} object. */ public DocumentTag(Node node) { this(node, DocumentTagTraversal.TRAVERSE_NODES); } private void walkNodeTree() { String value = thisNode.getNodeValue(); data = new StringBuilder(((value == null) ? "" : value)); tagName = thisNode.getNodeName(); if (thisNode.getNodeType() != Node.ELEMENT_NODE) { return; } NodeList list = thisNode.getChildNodes(); int size = list.getLength(); if (size > 0) { children = Lists.newArrayList(); } else { children = null; } for(int i = 0; i < size; i++) { if (list.item(i) == null) { log.info("Dropping null child in tag {}: data='{}'", tagName, data); continue; } DocumentTag t = DocumentTag.getTag(list.item(i)); if (t instanceof SystemDocumentTag) { if (t.children != null) { t.children.forEach(child -> children.add(child)); } } else { children.add(t); } } } /** * This function is used to wrap a given {@link Node} with its {@code DocumentTag} wrapped rendering engine. Any * time a document is parsed, this is the first call that should be made after the XML tree has been created. A * document <b>must</b> be wrapped in a {@code DocumentTag}, or it cannot be rendered: the most you could do is treat * it as an XML document. * * @param tag {@link Node} to wrap. * @return {@code DocumentTag} wrapped object. */ public static DocumentTag getTag(Node tag) { if (tag == null) { return null; } try { switch(tag.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: return new SystemTextTag(tag); case Node.ELEMENT_NODE: return DocumentTagRegistry.getTag(tag); default: log.info("Unknown element type: {}", tag.getNodeType()); return null; } } catch(RuntimeException e) { log.warn("Bad element exception", e); } return null; } /** * This is a helper method used to retrieve the attributes of a {@link Node}. Attributes are the additional * parameters specified in a node, for instance: {@code <nodeName attribute1="value"/>} - {@code attribute1} * would be the attribute. * * @param node The {@link Node} to handle. * @param elementName {@code String} name of the attribute to retrieve. * @return {@code String} containing the value, {@code null} if not found or empty. */ public static String getAttribute(Node node, String elementName) { if (node instanceof Element) { String attributeValue = ((Element) node).getAttribute(elementName); return attributeValue.length() > 0 ? attributeValue : null; } return null; } /** * This is a helper method that walks the child nodes of the parent, making the contents of the nodes available * as key/values. Child nodes of the parent may only appear once in the list. * * @param parent The {@link Node} from which to retrieve the children. * @return {@link Map} of {@link String} and {@link DocumentTag} children, where the key is the name of the child subnode. */ public static Map<String, DocumentTag> getChildNodes(Node parent) { Map<String, DocumentTag> nodelist = Maps.newHashMap(); if ((parent == null || !parent.hasChildNodes()) || parent.getNodeType() != Node.ELEMENT_NODE) { return Maps.newHashMap(); } NodeList list = parent.getChildNodes(); int size = list.getLength(); for(int i = 0; i < size; i++) { if (list.item(i) == null) { continue; } Node child = list.item(i); if (child.getNodeType() == Node.TEXT_NODE) { continue; } if (child.getNodeType() != Node.ELEMENT_NODE) { return Maps.newHashMap(); } String childname = child.getNodeName().toLowerCase(); if (child.hasAttributes()) { NamedNodeMap nnm = child.getAttributes(); int numNNM = nnm.getLength(); String adder = ""; String attrList = ""; for(int x = 0; x < numNNM; x++) { Node nnmNode = nnm.item(x); String nodeName = nnmNode.getNodeName().toLowerCase(); String nodeValue = nnmNode.getNodeValue().toLowerCase(); attrList += adder + nodeName + "='" + nodeValue + "'"; adder = ","; } String newChildName = childname + "[" + attrList + "]"; nodelist.put(newChildName, new DocumentTag(child)); } nodelist.put(childname, new DocumentTag(child)); } log.info("getChildNodes: dict={}", nodelist); return nodelist; } /** * Renders the contents of a tag by walking its children, and appending the results in a {@link StringBuffer}. * * @param docTag The root {@link DocumentTag} to process. * @param context The currently active {@link RenderContext}. * @return {@link StringBuffer} containing the result. */ public static StringBuilder getBody(DocumentTag docTag, RenderContext context) { StringBuilder buf = new StringBuilder(); // if (docTag == null) { // c.setExceptionState(true, "Unable to process document body: No element data is available."); // return null; // } if (docTag.children == null) { return null; } // This is done as a convenience so that the render mode can be set automatically, and variables copied // for you without having to remember to do all of that. RenderContext c = new RenderContext(context.getVariableStore()); for(DocumentTag tag : docTag.children) { StringBuilder temp; if ((temp = tag.render(c)) == null) { return null; } buf.append(temp); } return buf; } /** * This is the rendering entry point for the {@link DocumentTag}. Any tags that override this method must return * a string that contains the dynamically rendered result. * * @param renderContext Immutable {@link RenderContext} object. * @return {@link StringBuffer} containing the rendered output. */ public StringBuilder render(final RenderContext renderContext) { // if (c.isCancelled()) { // return new StringBuffer(); // } // final StringBuilder result = new StringBuilder(); if (children != null) { for (DocumentTag t : children) { StringBuilder res; // if (c.isBreakState() || c.isCancelled()) { // return new StringBuffer(); // } try { if ((res = t.render(renderContext)) == null) { return null; } } catch (Exception ex) { log.info("An exception occurred while trying to render.", ex); // c.setExceptionState(true, "An exception occurred while trying to render: " + Debug.getStackTrace(ex)); return new StringBuilder(); } // if (c.isCancelled()) { // return new StringBuffer(); // } result.append(res); } } return result; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.cassandra.db.view; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.UUID; import javax.annotation.Nullable; import com.google.common.collect.Iterables; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.config.ViewDefinition; import org.apache.cassandra.config.Schema; import org.apache.cassandra.cql3.ColumnIdentifier; import org.apache.cassandra.db.AbstractReadCommandBuilder; import org.apache.cassandra.db.AbstractReadCommandBuilder.SinglePartitionSliceBuilder; import org.apache.cassandra.db.CBuilder; import org.apache.cassandra.db.Clustering; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.DecoratedKey; import org.apache.cassandra.db.DeletionInfo; import org.apache.cassandra.db.DeletionTime; import org.apache.cassandra.db.LivenessInfo; import org.apache.cassandra.db.Mutation; import org.apache.cassandra.db.RangeTombstone; import org.apache.cassandra.db.ReadCommand; import org.apache.cassandra.db.ReadOrderGroup; import org.apache.cassandra.db.SinglePartitionReadCommand; import org.apache.cassandra.db.Slice; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.partitions.AbstractBTreePartition; import org.apache.cassandra.db.partitions.PartitionIterator; import org.apache.cassandra.db.partitions.PartitionUpdate; import org.apache.cassandra.db.rows.BTreeRow; import org.apache.cassandra.db.rows.Cell; import org.apache.cassandra.db.rows.ColumnData; import org.apache.cassandra.db.rows.ComplexColumnData; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.db.rows.RowIterator; import org.apache.cassandra.schema.KeyspaceMetadata; import org.apache.cassandra.service.pager.QueryPager; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.transport.Server; /** * A View copies data from a base table into a view table which can be queried independently from the * base. Every update which targets the base table must be fed through the {@link ViewManager} to ensure * that if a view needs to be updated, the updates are properly created and fed into the view. * * This class does the job of translating the base row to the view row. * * It handles reading existing state and figuring out what tombstones need to be generated. * * {@link View#createMutations(AbstractBTreePartition, TemporalRow.Set, boolean)} is the "main method" * */ public class View { /** * The columns should all be updated together, so we use this object as group. */ private static class Columns { //These are the base column definitions in terms of the *views* partitioning. //Meaning we can see (for example) the partition key of the view contains a clustering key //from the base table. public final List<ColumnDefinition> partitionDefs; public final List<ColumnDefinition> primaryKeyDefs; public final List<ColumnDefinition> baseComplexColumns; private Columns(List<ColumnDefinition> partitionDefs, List<ColumnDefinition> primaryKeyDefs, List<ColumnDefinition> baseComplexColumns) { this.partitionDefs = partitionDefs; this.primaryKeyDefs = primaryKeyDefs; this.baseComplexColumns = baseComplexColumns; } } public final String name; private volatile ViewDefinition definition; private final ColumnFamilyStore baseCfs; private Columns columns; private final boolean viewHasAllPrimaryKeys; private final boolean includeAllColumns; private ViewBuilder builder; public View(ViewDefinition definition, ColumnFamilyStore baseCfs) { this.baseCfs = baseCfs; name = definition.viewName; includeAllColumns = definition.includeAllColumns; viewHasAllPrimaryKeys = updateDefinition(definition); } public ViewDefinition getDefinition() { return definition; } /** * Lookup column definitions in the base table that correspond to the view columns (should be 1:1) * * Notify caller if all primary keys in the view are ALL primary keys in the base. We do this to simplify * tombstone checks. * * @param columns a list of columns to lookup in the base table * @param definitions lists to populate for the base table definitions * @return true if all view PKs are also Base PKs */ private boolean resolveAndAddColumns(Iterable<ColumnIdentifier> columns, List<ColumnDefinition>... definitions) { boolean allArePrimaryKeys = true; for (ColumnIdentifier identifier : columns) { ColumnDefinition cdef = baseCfs.metadata.getColumnDefinition(identifier); assert cdef != null : "Could not resolve column " + identifier.toString(); for (List<ColumnDefinition> list : definitions) { list.add(cdef); } allArePrimaryKeys = allArePrimaryKeys && cdef.isPrimaryKeyColumn(); } return allArePrimaryKeys; } /** * This updates the columns stored which are dependent on the base CFMetaData. * * @return true if the view contains only columns which are part of the base's primary key; false if there is at * least one column which is not. */ public boolean updateDefinition(ViewDefinition definition) { this.definition = definition; CFMetaData viewCfm = definition.metadata; List<ColumnDefinition> partitionDefs = new ArrayList<>(viewCfm.partitionKeyColumns().size()); List<ColumnDefinition> primaryKeyDefs = new ArrayList<>(viewCfm.partitionKeyColumns().size() + viewCfm.clusteringColumns().size()); List<ColumnDefinition> baseComplexColumns = new ArrayList<>(); // We only add the partition columns to the partitions list, but both partition columns and clustering // columns are added to the primary keys list boolean partitionAllPrimaryKeyColumns = resolveAndAddColumns(Iterables.transform(viewCfm.partitionKeyColumns(), cd -> cd.name), primaryKeyDefs, partitionDefs); boolean clusteringAllPrimaryKeyColumns = resolveAndAddColumns(Iterables.transform(viewCfm.clusteringColumns(), cd -> cd.name), primaryKeyDefs); for (ColumnDefinition cdef : baseCfs.metadata.allColumns()) { if (cdef.isComplex()) { baseComplexColumns.add(cdef); } } this.columns = new Columns(partitionDefs, primaryKeyDefs, baseComplexColumns); return partitionAllPrimaryKeyColumns && clusteringAllPrimaryKeyColumns; } /** * Check to see if the update could possibly modify a view. Cases where the view may be updated are: * <ul> * <li>View selects all columns</li> * <li>Update contains any range tombstones</li> * <li>Update touches one of the columns included in the view</li> * </ul> * * If the update contains any range tombstones, there is a possibility that it will not touch a range that is * currently included in the view. * * @return true if {@param partition} modifies a column included in the view */ public boolean updateAffectsView(AbstractBTreePartition partition) { // If we are including all of the columns, then any update will be included if (includeAllColumns) return true; // If there are range tombstones, tombstones will also need to be generated for the view // This requires a query of the base rows and generating tombstones for all of those values if (!partition.deletionInfo().isLive()) return true; // Check each row for deletion or update for (Row row : partition) { if (!row.deletion().isLive()) return true; if (row.primaryKeyLivenessInfo().isLive(FBUtilities.nowInSeconds())) return true; for (ColumnData data : row) { if (definition.metadata.getColumnDefinition(data.column().name) != null) return true; } } return false; } /** * Creates the clustering columns for the view based on the specified row and resolver policy * * @param temporalRow The current row * @param resolver The policy to use when selecting versions of cells use * @return The clustering object to use for the view */ private Clustering viewClustering(TemporalRow temporalRow, TemporalRow.Resolver resolver) { CFMetaData viewCfm = definition.metadata; int numViewClustering = viewCfm.clusteringColumns().size(); CBuilder clustering = CBuilder.create(viewCfm.comparator); for (int i = 0; i < numViewClustering; i++) { ColumnDefinition definition = viewCfm.clusteringColumns().get(i); clustering.add(temporalRow.clusteringValue(definition, resolver)); } return clustering.build(); } /** * @return Mutation containing a range tombstone for a base partition key and TemporalRow. */ private PartitionUpdate createTombstone(TemporalRow temporalRow, DecoratedKey partitionKey, Row.Deletion deletion, TemporalRow.Resolver resolver, int nowInSec) { CFMetaData viewCfm = definition.metadata; Row.Builder builder = BTreeRow.unsortedBuilder(nowInSec); builder.newRow(viewClustering(temporalRow, resolver)); builder.addRowDeletion(deletion); return PartitionUpdate.singleRowUpdate(viewCfm, partitionKey, builder.build()); } /** * @return PartitionUpdate containing a complex tombstone for a TemporalRow, and the collection's column identifier. */ private PartitionUpdate createComplexTombstone(TemporalRow temporalRow, DecoratedKey partitionKey, ColumnDefinition deletedColumn, DeletionTime deletionTime, TemporalRow.Resolver resolver, int nowInSec) { CFMetaData viewCfm = definition.metadata; Row.Builder builder = BTreeRow.unsortedBuilder(nowInSec); builder.newRow(viewClustering(temporalRow, resolver)); builder.addComplexDeletion(deletedColumn, deletionTime); return PartitionUpdate.singleRowUpdate(viewCfm, partitionKey, builder.build()); } /** * @return View's DecoratedKey or null, if one of the view's primary key components has an invalid resolution from * the TemporalRow and its Resolver */ private DecoratedKey viewPartitionKey(TemporalRow temporalRow, TemporalRow.Resolver resolver) { List<ColumnDefinition> partitionDefs = this.columns.partitionDefs; Object[] partitionKey = new Object[partitionDefs.size()]; for (int i = 0; i < partitionKey.length; i++) { ByteBuffer value = temporalRow.clusteringValue(partitionDefs.get(i), resolver); if (value == null) return null; partitionKey[i] = value; } CFMetaData metadata = definition.metadata; return metadata.decorateKey(CFMetaData.serializePartitionKey(metadata .getKeyValidatorAsClusteringComparator() .make(partitionKey))); } /** * @return mutation which contains the tombstone for the referenced TemporalRow, or null if not necessary. * TemporalRow's can reference at most one view row; there will be at most one row to be tombstoned, so only one * mutation is necessary */ private PartitionUpdate createRangeTombstoneForRow(TemporalRow temporalRow) { // Primary Key and Clustering columns do not generate tombstones if (viewHasAllPrimaryKeys) return null; boolean hasUpdate = false; List<ColumnDefinition> primaryKeyDefs = this.columns.primaryKeyDefs; for (ColumnDefinition viewPartitionKeys : primaryKeyDefs) { if (!viewPartitionKeys.isPrimaryKeyColumn() && temporalRow.clusteringValue(viewPartitionKeys, TemporalRow.oldValueIfUpdated) != null) hasUpdate = true; } if (!hasUpdate) return null; TemporalRow.Resolver resolver = TemporalRow.earliest; return createTombstone(temporalRow, viewPartitionKey(temporalRow, resolver), Row.Deletion.shadowable(new DeletionTime(temporalRow.viewClusteringTimestamp(), temporalRow.nowInSec)), resolver, temporalRow.nowInSec); } /** * @return Mutation which is the transformed base table mutation for the view. */ private PartitionUpdate createUpdatesForInserts(TemporalRow temporalRow) { TemporalRow.Resolver resolver = TemporalRow.latest; DecoratedKey partitionKey = viewPartitionKey(temporalRow, resolver); CFMetaData viewCfm = definition.metadata; if (partitionKey == null) { // Not having a partition key means we aren't updating anything return null; } Row.Builder regularBuilder = BTreeRow.unsortedBuilder(temporalRow.nowInSec); CBuilder clustering = CBuilder.create(viewCfm.comparator); for (int i = 0; i < viewCfm.clusteringColumns().size(); i++) { clustering.add(temporalRow.clusteringValue(viewCfm.clusteringColumns().get(i), resolver)); } regularBuilder.newRow(clustering.build()); regularBuilder.addPrimaryKeyLivenessInfo(LivenessInfo.create(viewCfm, temporalRow.viewClusteringTimestamp(), temporalRow.viewClusteringTtl(), temporalRow.viewClusteringLocalDeletionTime())); for (ColumnDefinition columnDefinition : viewCfm.allColumns()) { if (columnDefinition.isPrimaryKeyColumn()) continue; for (Cell cell : temporalRow.values(columnDefinition, resolver)) { regularBuilder.addCell(cell); } } return PartitionUpdate.singleRowUpdate(viewCfm, partitionKey, regularBuilder.build()); } /** * @param partition Update which possibly contains deletion info for which to generate view tombstones. * @return View Tombstones which delete all of the rows which have been removed from the base table with * {@param partition} */ private Collection<Mutation> createForDeletionInfo(TemporalRow.Set rowSet, AbstractBTreePartition partition) { final TemporalRow.Resolver resolver = TemporalRow.earliest; DeletionInfo deletionInfo = partition.deletionInfo(); List<Mutation> mutations = new ArrayList<>(); // Check the complex columns to see if there are any which may have tombstones we need to create for the view if (!columns.baseComplexColumns.isEmpty()) { for (Row row : partition) { if (!row.hasComplexDeletion()) continue; TemporalRow temporalRow = rowSet.getClustering(row.clustering()); assert temporalRow != null; for (ColumnDefinition definition : columns.baseComplexColumns) { ComplexColumnData columnData = row.getComplexColumnData(definition); if (columnData != null) { DeletionTime time = columnData.complexDeletion(); if (!time.isLive()) { DecoratedKey targetKey = viewPartitionKey(temporalRow, resolver); if (targetKey != null) mutations.add(new Mutation(createComplexTombstone(temporalRow, targetKey, definition, time, resolver, temporalRow.nowInSec))); } } } } } ReadCommand command = null; if (!deletionInfo.isLive()) { // We have to generate tombstones for all of the affected rows, but we don't have the information in order // to create them. This requires that we perform a read for the entire range that is being tombstoned, and // generate a tombstone for each. This may be slow, because a single range tombstone can cover up to an // entire partition of data which is not distributed on a single partition node. DecoratedKey dk = rowSet.dk; if (!deletionInfo.getPartitionDeletion().isLive()) { command = SinglePartitionReadCommand.fullPartitionRead(baseCfs.metadata, rowSet.nowInSec, dk); } else { SinglePartitionSliceBuilder builder = new SinglePartitionSliceBuilder(baseCfs, dk); Iterator<RangeTombstone> tombstones = deletionInfo.rangeIterator(false); while (tombstones.hasNext()) { RangeTombstone tombstone = tombstones.next(); builder.addSlice(tombstone.deletedSlice()); } command = builder.build(); } } if (command == null) { SinglePartitionSliceBuilder builder = null; for (Row row : partition) { if (!row.deletion().isLive()) { if (builder == null) builder = new SinglePartitionSliceBuilder(baseCfs, rowSet.dk); builder.addSlice(Slice.make(row.clustering())); } } if (builder != null) command = builder.build(); } if (command != null) { //We may have already done this work for //another MV update so check if (!rowSet.hasTombstonedExisting()) { QueryPager pager = command.getPager(null, Server.CURRENT_VERSION); // Add all of the rows which were recovered from the query to the row set while (!pager.isExhausted()) { try (ReadOrderGroup orderGroup = pager.startOrderGroup(); PartitionIterator iter = pager.fetchPageInternal(128, orderGroup)) { if (!iter.hasNext()) break; try (RowIterator rowIterator = iter.next()) { while (rowIterator.hasNext()) { Row row = rowIterator.next(); rowSet.addRow(row, false); } } } } //Incase we fetched nothing, avoid re checking on another MV update rowSet.setTombstonedExisting(); } // If the temporal row has been deleted by the deletion info, we generate the corresponding range tombstone // for the view. for (TemporalRow temporalRow : rowSet) { DeletionTime deletionTime = temporalRow.deletionTime(partition); if (!deletionTime.isLive()) { DecoratedKey value = viewPartitionKey(temporalRow, resolver); if (value != null) { PartitionUpdate update = createTombstone(temporalRow, value, Row.Deletion.regular(deletionTime), resolver, temporalRow.nowInSec); if (update != null) mutations.add(new Mutation(update)); } } } } return !mutations.isEmpty() ? mutations : null; } /** * Read and update temporal rows in the set which have corresponding values stored on the local node */ private void readLocalRows(TemporalRow.Set rowSet) { SinglePartitionSliceBuilder builder = new SinglePartitionSliceBuilder(baseCfs, rowSet.dk); for (TemporalRow temporalRow : rowSet) builder.addSlice(temporalRow.baseSlice()); QueryPager pager = builder.build().getPager(null, Server.CURRENT_VERSION); while (!pager.isExhausted()) { try (ReadOrderGroup orderGroup = pager.startOrderGroup(); PartitionIterator iter = pager.fetchPageInternal(128, orderGroup)) { while (iter.hasNext()) { try (RowIterator rows = iter.next()) { while (rows.hasNext()) { rowSet.addRow(rows.next(), false); } } } } } } /** * @return Set of rows which are contained in the partition update {@param partition} */ private TemporalRow.Set separateRows(AbstractBTreePartition partition, Set<ColumnIdentifier> viewPrimaryKeyCols) { TemporalRow.Set rowSet = new TemporalRow.Set(baseCfs, viewPrimaryKeyCols, partition.partitionKey().getKey()); for (Row row : partition) rowSet.addRow(row, true); return rowSet; } /** * Splits the partition update up and adds the existing state to each row. * This data can be reused for multiple MV updates on the same base table * * @param partition the mutation * @param isBuilding If the view is currently being built, we do not query the values which are already stored, * since all of the update will already be present in the base table. * @return The set of temoral rows contained in this update */ public TemporalRow.Set getTemporalRowSet(AbstractBTreePartition partition, TemporalRow.Set existing, boolean isBuilding) { if (!updateAffectsView(partition)) return null; Set<ColumnIdentifier> columns = new HashSet<>(this.columns.primaryKeyDefs.size()); for (ColumnDefinition def : this.columns.primaryKeyDefs) columns.add(def.name); TemporalRow.Set rowSet; if (existing == null) { rowSet = separateRows(partition, columns); // If we are building the view, we do not want to add old values; they will always be the same if (!isBuilding) readLocalRows(rowSet); } else { rowSet = existing.withNewViewPrimaryKey(columns); } return rowSet; } /** * @param isBuilding If the view is currently being built, we do not query the values which are already stored, * since all of the update will already be present in the base table. * @return View mutations which represent the changes necessary as long as previously created mutations for the view * have been applied successfully. This is based solely on the changes that are necessary given the current * state of the base table and the newly applying partition data. */ public Collection<Mutation> createMutations(AbstractBTreePartition partition, TemporalRow.Set rowSet, boolean isBuilding) { if (!updateAffectsView(partition)) return null; Collection<Mutation> mutations = null; for (TemporalRow temporalRow : rowSet) { // If we are building, there is no need to check for partition tombstones; those values will not be present // in the partition data if (!isBuilding) { PartitionUpdate partitionTombstone = createRangeTombstoneForRow(temporalRow); if (partitionTombstone != null) { if (mutations == null) mutations = new LinkedList<>(); mutations.add(new Mutation(partitionTombstone)); } } PartitionUpdate insert = createUpdatesForInserts(temporalRow); if (insert != null) { if (mutations == null) mutations = new LinkedList<>(); mutations.add(new Mutation(insert)); } } if (!isBuilding) { Collection<Mutation> deletion = createForDeletionInfo(rowSet, partition); if (deletion != null && !deletion.isEmpty()) { if (mutations == null) mutations = new LinkedList<>(); mutations.addAll(deletion); } } return mutations; } public synchronized void build() { if (this.builder != null) { this.builder.stop(); this.builder = null; } this.builder = new ViewBuilder(baseCfs, this); CompactionManager.instance.submitViewBuilder(builder); } @Nullable public static CFMetaData findBaseTable(String keyspace, String viewName) { ViewDefinition view = Schema.instance.getView(keyspace, viewName); return (view == null) ? null : Schema.instance.getCFMetaData(view.baseTableId); } public static Iterable<ViewDefinition> findAll(String keyspace, String baseTable) { KeyspaceMetadata ksm = Schema.instance.getKSMetaData(keyspace); final UUID baseId = Schema.instance.getId(keyspace, baseTable); return Iterables.filter(ksm.views, view -> view.baseTableId.equals(baseId)); } }
package com.exikle.java.calculators; import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; /* * Name: Mohammed Rahmati * Student Number: 212912887 * Calculator made with java awt and swing libraries that allow decimal numbers and enables addition, * multiplication, subtraction, and division. */ public class Calculator extends Applet implements ActionListener { // Java Animation Variables // JFrame frame; JPanel bPanel; JPanel opButtons; JPanel textPanel; JTextArea calcView; JScrollPane scroll; // Important Calculator Variables String text; int operator; double firstNum; double secondNum; double answer; boolean firstHalfDone; String numberBuilder; DecimalFormat df = new DecimalFormat("#.##"); // The method that will be automatically called when the applet is started public void init() { // op buttons opButtons = new JPanel(); opButtons.setLayout(new GridLayout(1, 2)); this.add(opButtons, BorderLayout.NORTH); // Clear Last Button JButton clearLast = new JButton("Clear Last"); clearLast.setActionCommand("Clear Last"); clearLast.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (text.charAt(text.length() - 1) == '\n') text = text.substring(0, text.length() - 1); if ((text.charAt(text.length() - 1) == '+') || (text.charAt(text.length() - 1) == '-') || (text.charAt(text.length() - 1) == '*') || (text.charAt(text.length() - 1) == '/')) { text = text.substring(0, text.length() - 1); firstHalfDone = false; numberBuilder = String.valueOf(df.format(firstNum)); operator = 0; } else if (operator == 0 && numberBuilder.equals("")) { text += "\n"; // do nothing after equals } else if (!numberBuilder.equals("")) { text = text.substring(0, text.length() - 1); numberBuilder = numberBuilder.substring(0, numberBuilder.length() - 1); } else { text = text.substring(0, text.length() - 1); } calcView.setText(text); } }); opButtons.add(clearLast); // Clear All Button JButton clearAll = new JButton("Clear All"); clearAll.setActionCommand("Clear All"); clearAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { text = ""; operator = 0; firstNum = 0; secondNum = 0; answer = 0; firstHalfDone = false; numberBuilder = ""; calcView.setText(text); } }); opButtons.add(clearAll); // Text area textPanel = new JPanel(); calcView = new JTextArea(7, 20); calcView.setEditable(false); scroll = new JScrollPane(calcView); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); textPanel.add(scroll, BorderLayout.CENTER); this.add(textPanel); // Setting up the Button Panel bPanel = new JPanel(); bPanel.setLayout(new GridLayout(4, 4)); this.add(bPanel, BorderLayout.SOUTH); // Adding Numbers 7,8,9 addButton(bPanel, String.valueOf(7)); addButton(bPanel, String.valueOf(8)); addButton(bPanel, String.valueOf(9)); // Adding the Addition Button JButton additionButton = new JButton("+"); additionButton.setActionCommand("+"); additionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!(numberBuilder == "")) { if (!firstHalfDone) { operator = 1; FirstHalf("+"); } else if (firstHalfDone) { // && !(operator == 0) if (SecondHalf("+")) { operator = 1; text += "=\n"; text += df.format(firstNum) + "+\n"; calcView.setText(text); } } } else { // operator = 1; // numberBuilder = "0"; // text += "0"; // FirstHalf("+"); SecondHalf("+"); } } }); bPanel.add(additionButton); // Adding Numbers 4,5,6 addButton(bPanel, String.valueOf(4)); addButton(bPanel, String.valueOf(5)); addButton(bPanel, String.valueOf(6)); // Adding the Subtraction Button JButton subtractionButton = new JButton("-"); subtractionButton.setActionCommand("-"); subtractionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!(numberBuilder == "")) { if (!firstHalfDone) { operator = 2; FirstHalf("-"); } else if (firstHalfDone) { if (SecondHalf("-")) { operator = 2; text += "=\n"; text += df.format(firstNum) + "-\n"; calcView.setText(text); } } } else { // operator = 2; // numberBuilder = "0"; // text += "0"; // FirstHalf("-"); SecondHalf("-"); } } }); bPanel.add(subtractionButton); // Adding Buttons 1,2,3 addButton(bPanel, String.valueOf(1)); addButton(bPanel, String.valueOf(2)); addButton(bPanel, String.valueOf(3)); // Adding the Multiplication Button JButton multiplicationButton = new JButton("*"); multiplicationButton.setActionCommand("*"); multiplicationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!(numberBuilder == "")) { if (!firstHalfDone) { operator = 3; FirstHalf("*"); } else if (firstHalfDone) { if (SecondHalf("*")) { operator = 3; text += "=\n"; text += df.format(firstNum) + "*\n"; calcView.setText(text); } } } else { // operator = 3; // numberBuilder = "0"; // text += "0"; // FirstHalf("*"); SecondHalf("*"); } } }); bPanel.add(multiplicationButton); // Adding the Decimal Point Button addButton(bPanel, String.valueOf(0)); JButton decimalPointButton = new JButton("."); decimalPointButton.setActionCommand("."); bPanel.add(decimalPointButton); decimalPointButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!numberBuilder.contains(".")) { numberBuilder += "."; text += "."; calcView.setText(text); } else { text += "\nError: You can't have multiple decimal points in a number!\n" + numberBuilder; calcView.setText(text); } } }); // Adding the Equals Button JButton equalsButton = new JButton("="); equalsButton.setActionCommand("="); equalsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (numberBuilder.equals("") && firstHalfDone) { // if no number // and // operator // has been // entered, // assume // double // operator // (Error) text += "Error: You cannot have operator = displayed right now!\n"; calcView.setText(text); } else if (numberBuilder.equals("")) { // do nothing } else { if (!(operator == 0)) secondNum = Double.parseDouble(numberBuilder); else firstNum = Double.parseDouble(numberBuilder); numberBuilder = ""; if (operator == 0) { answer = firstNum; firstHalfDone = true; } else if (operator == 1) { answer = firstNum + secondNum; firstHalfDone = true; } else if (operator == 2) { answer = firstNum - secondNum; firstHalfDone = true; } else if (operator == 3) { answer = firstNum * secondNum; firstHalfDone = true; } else { if (secondNum == 0) { text += "=\nError: Cannot divide by zero!\n"; calcView.setText(text); firstHalfDone = false; } else { answer = firstNum / secondNum; firstHalfDone = true; } } if (firstHalfDone) { text += "=\n"; text += df.format(answer) + "\n"; calcView.setText(text); numberBuilder = ""; operator = 0; firstNum = 0; secondNum = 0; answer = 0; firstHalfDone = false; } } } }); bPanel.add(equalsButton); // Adding the Division Button JButton divisionButton = new JButton("/"); divisionButton.setActionCommand("/"); divisionButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!(numberBuilder == "")) { if (!firstHalfDone) { operator = 4; FirstHalf("/"); } else if (firstHalfDone) { if (SecondHalf("/")) { operator = 4; text += "=\n"; text += df.format(firstNum) + "/\n"; calcView.setText(text); } } } else { // operator = 4; // numberBuilder = "0"; // text += "0"; // FirstHalf("/"); SecondHalf("/"); } } }); bPanel.add(divisionButton); text = ""; firstNum = 0; secondNum = 0; answer = 0; operator = 0; firstHalfDone = false; numberBuilder = ""; calcView.setText(text); // launching the window and making it visible this.setVisible(true); } // This method gets called when the applet is terminated // That's when the user goes to another page or exits the browser. public void stop() { // no actions needed here now. } // creating private classes to simplify code private void FirstHalf(String strOp) { if (!(numberBuilder.equals(""))) { firstNum = Double.parseDouble(numberBuilder); numberBuilder = ""; text += strOp + "\n"; calcView.setText(text); firstHalfDone = true; } } // Returns true if the operation completed successfully private boolean SecondHalf(String strOp) { if (numberBuilder.equals("")) { // if no number, assume double operator // (Error) text += "Error: You cannot have operator " + strOp + " displayed right now!\n"; calcView.setText(text); return false; } secondNum = Double.parseDouble(numberBuilder); numberBuilder = ""; if (operator == 1) { firstNum = firstNum + secondNum; } else if (operator == 2) { firstNum = firstNum - secondNum; } else if (operator == 3) { firstNum = firstNum * secondNum; } else if (operator == 4) { if (secondNum == 0) { text += "\nError: Cannot divide by zero!\n"; calcView.setText(text); firstHalfDone = false; numberBuilder = ""; firstNum = 0; secondNum = 0; answer = 0; operator = 0; return false; } else { firstNum = firstNum / secondNum; firstHalfDone = true; } } return true; } // method used to reduce code when adding multiple calculator buttons // (numbers, operators, etc) private void addButton(Container contain, String title) { JButton button = new JButton(title); button.setActionCommand(title); button.addActionListener(this); contain.add(button); } // Used to show what the user clicks on the buttons public void actionPerformed(ActionEvent event) { numberBuilder += event.getActionCommand(); text += event.getActionCommand(); calcView.setText(text); } }
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.idp.mgt.ui.client; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.common.model.idp.xsd.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.idp.xsd.IdentityProvider; import org.wso2.carbon.identity.application.common.model.idp.xsd.ProvisioningConnectorConfig; import org.wso2.carbon.idp.mgt.stub.IdentityProviderMgtServiceStub; import org.wso2.carbon.user.mgt.stub.UserAdminStub; import org.wso2.carbon.user.mgt.stub.types.carbon.UserStoreInfo; public class IdentityProviderMgtServiceClient { private static Log log = LogFactory.getLog(IdentityProviderMgtServiceClient.class); private IdentityProviderMgtServiceStub idPMgtStub; private UserAdminStub userAdminStub; /** * @param cookie HttpSession cookie * @param backendServerURL Backend Carbon server URL * @param configCtx Axis2 Configuration Context */ public IdentityProviderMgtServiceClient(String cookie, String backendServerURL, ConfigurationContext configCtx) { String idPMgtServiceURL = backendServerURL + "IdentityProviderMgtService"; String userAdminServiceURL = backendServerURL + "UserAdmin"; try { idPMgtStub = new IdentityProviderMgtServiceStub(configCtx, idPMgtServiceURL); } catch (AxisFault axisFault) { log.error("Error while instantiating IdentityProviderMgtServiceStub", axisFault); } try { userAdminStub = new UserAdminStub(configCtx, userAdminServiceURL); } catch (AxisFault axisFault) { log.error("Error while instantiating UserAdminServiceStub", axisFault); } ServiceClient idPMgtClient = idPMgtStub._getServiceClient(); ServiceClient userAdminClient = userAdminStub._getServiceClient(); Options idPMgtOptions = idPMgtClient.getOptions(); idPMgtOptions.setManageSession(true); idPMgtOptions.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); Options userAdminOptions = userAdminClient.getOptions(); userAdminOptions.setManageSession(true); userAdminOptions.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); } /** * Retrieves Resident Identity provider for a given tenant * * @return <code>FederatedIdentityProvider</code> * @throws Exception Error when getting Resident Identity Providers */ public IdentityProvider getResidentIdP() throws Exception { try { return idPMgtStub.getResidentIdP(); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving list of Identity Providers"); } } /** * Updated Resident Identity provider for a given tenant * * @return <code>FederatedIdentityProvider</code> * @throws Exception Error when getting Resident Identity Providers */ public void updateResidentIdP(IdentityProvider identityProvider) throws Exception { try { idPMgtStub.updateResidentIdP(identityProvider); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving list of Identity Providers"); } } /** * Retrieves registered Identity providers for a given tenant * * @return List of <code>FederatedIdentityProvider</code>. IdP names, primary IdP and home realm * identifiers of each IdP * @throws Exception Error when getting list of Identity Providers */ public List<IdentityProvider> getIdPs() throws Exception { try { IdentityProvider[] identityProviders = idPMgtStub.getAllIdPs(); if (identityProviders != null && identityProviders.length > 0) { return Arrays.asList(identityProviders); } else { return new ArrayList<IdentityProvider>(); } } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving list of Identity Providers"); } } /** * Retrieves Enabled registered Identity providers for a given tenant * * @return List of <code>FederatedIdentityProvider</code>. IdP names, primary IdP and home realm * identifiers of each IdP * @throws Exception Error when getting list of Identity Providers */ public List<IdentityProvider> getEnabledIdPs() throws Exception { try { IdentityProvider[] identityProviders = idPMgtStub.getEnabledAllIdPs(); if (identityProviders != null && identityProviders.length > 0) { return Arrays.asList(identityProviders); } else { return new ArrayList<IdentityProvider>(); } } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception( "Error occurred while retrieving list of Enabled Identity Providers"); } } /** * Retrieves Identity provider information about a given tenant by Identity Provider name * * @param idPName Unique name of the Identity provider of whose information is requested * @return <code>FederatedIdentityProvider</code> Identity Provider information * @throws Exception Error when getting Identity Provider information by IdP name */ public IdentityProvider getIdPByName(String idPName) throws Exception { try { return idPMgtStub.getIdPByName(idPName); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving information about " + idPName); } } /** * Adds an Identity Provider to the given tenant * * @param identityProvider <code><FederatedIdentityProvider/code></code> federated Identity * Provider information * @throws Exception Error when adding Identity Provider information */ public void addIdP(IdentityProvider identityProvider) throws Exception { try { idPMgtStub.addIdP(identityProvider); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while adding Identity Provider " + identityProvider.getIdentityProviderName()); } } /** * Deletes an Identity Provider from a given tenant * * @param idPName Name of the IdP to be deleted * @throws Exception Error when deleting Identity Provider information */ public void deleteIdP(String idPName) throws Exception { try { idPMgtStub.deleteIdP(idPName); } catch (Exception e) { throw e; } } /** * Updates a given Identity Provider information * * @param oldIdPName existing IdP name * @param identityProvider <code>FederatedIdentityProvider</code> new IdP information * @throws Exception Error when updating Identity Provider information */ public void updateIdP(String oldIdPName, IdentityProvider identityProvider) throws Exception { try { idPMgtStub.updateIdP(oldIdPName, identityProvider); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while deleting Identity Provider " + oldIdPName); } } /** * * @return * @throws Exception */ public Map<String, FederatedAuthenticatorConfig> getAllFederatedAuthenticators() throws Exception { Map<String, FederatedAuthenticatorConfig> configMap = new HashMap<String, FederatedAuthenticatorConfig>(); try { FederatedAuthenticatorConfig[] fedAuthConfigs = idPMgtStub .getAllFederatedAuthenticators(); if (fedAuthConfigs != null && fedAuthConfigs.length > 0) { for (FederatedAuthenticatorConfig config : fedAuthConfigs) { if (!(config.getDisplayName().equals("facebook") || config.getDisplayName().equals("openid") || config.getDisplayName().equals("openidconnect") || config.getDisplayName().equals("samlsso") || config.getDisplayName() .equals("passovests"))) configMap.put(config.getName(), config); } } } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving all local claim URIs"); } return configMap; } /** * * @return * @throws Exception */ public Map<String, ProvisioningConnectorConfig> getCustomProvisioningConnectors() throws Exception { Map<String, ProvisioningConnectorConfig> provisioningConnectors = new HashMap<String, ProvisioningConnectorConfig>(); try { ProvisioningConnectorConfig[] provisioningConnectorConfigs = idPMgtStub .getAllProvisioningConnectors(); if (provisioningConnectorConfigs != null && provisioningConnectorConfigs.length > 0 && provisioningConnectorConfigs[0] != null) { for (ProvisioningConnectorConfig config : provisioningConnectorConfigs) { if (!(config.getName().equals("spml") || config.getName().equals("scim") || config.getName().equals("salesforce") || config.getName().equals( "googleapps"))) provisioningConnectors.put(config.getName(), config); } } } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving all Provisioning Connectors"); } return provisioningConnectors; } /** * * @return * @throws Exception */ public String[] getAllLocalClaimUris() throws Exception { try { return idPMgtStub.getAllLocalClaimUris(); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception("Error occurred while retrieving all local claim URIs"); } } /** * * @return * @throws Exception */ public String[] getUserStoreDomains() throws Exception { try { List<String> readWriteDomainNames = new ArrayList<String>(); UserStoreInfo[] storesInfo = userAdminStub.getUserRealmInfo().getUserStoresInfo(); for (UserStoreInfo storeInfo : storesInfo) { if (!storeInfo.getReadOnly()) { readWriteDomainNames.add(storeInfo.getDomainName()); } } return readWriteDomainNames.toArray(new String[readWriteDomainNames.size()]); } catch (Exception e) { log.error(e.getMessage(), e); throw new Exception( "Error occurred while retrieving Read-Write User Store Domain IDs for logged-in user's tenant realm"); } } }
/** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch * <p/> * Copyright (c) 2012 Couchbase, Inc. All rights reserved. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * <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 com.couchbase.lite; import com.couchbase.lite.internal.InterfaceAudience; import com.couchbase.lite.store.ViewStore; import com.couchbase.lite.store.ViewStoreDelegate; import com.couchbase.lite.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a view available in a database. */ public final class View implements ViewStoreDelegate { public enum TDViewCollation { TDViewCollationUnicode, TDViewCollationRaw, TDViewCollationASCII } // Defined in CBLView.h private Database database; private String name; private Mapper mapBlock; private Reducer reduceBlock; private String version; // TODO: iOS version store version information in CBL_Shared. private static ViewCompiler compiler; private ViewStore viewStore; private boolean isDesignDoc = false; /////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////// @InterfaceAudience.Private protected View(Database database, String name, boolean create) throws CouchbaseLiteException { this.database = database; this.name = name; this.viewStore = database.getViewStorage(name, create); if (this.viewStore == null) throw new CouchbaseLiteException(Status.NOT_FOUND); this.viewStore.setDelegate(this); } /////////////////////////////////////////////////////////////////////////// // Implementation of ViewStorageDelegate /////////////////////////////////////////////////////////////////////////// /** * The map function that controls how index rows are created from documents. */ @Override @InterfaceAudience.Public public Mapper getMap() { return mapBlock; } /** * The optional reduce function, which aggregates together multiple rows. */ @Override @InterfaceAudience.Public public Reducer getReduce() { return reduceBlock; } @Override public String getMapVersion() { // TODO: Should be from CBL_Shared return version; } /** * Get document type. */ @Override public String getDocumentType() { return database.getViewDocumentType(name); } /** * Set document type. If the document type is set, only documents whose "type" property * is equal to its value will be passed to the map block and indexed. This can speed up indexing. * Just like the map block, this property is not persistent; it needs to be set at runtime before * the view is queried. And if its value changes, the view's version also needs to change. */ public void setDocumentType(String docType) { database.setViewDocumentType(docType, name); } /////////////////////////////////////////////////////////////////////////// // API (CBLView.h/CBLView.m) /////////////////////////////////////////////////////////////////////////// /** * Get the database that owns this view. */ @InterfaceAudience.Private protected Database getDatabase() { return database; } /** * Get the name of the view. */ @InterfaceAudience.Public public String getName() { return name; } /** * Defines a view's functions. * <p/> * The view's definition is given as a class that conforms to the Mapper or * Reducer interface (or null to delete the view). The body of the block * should call the 'emit' object (passed in as a paramter) for every key/value pair * it wants to write to the view. * <p/> * Since the function itself is obviously not stored in the database (only a unique * string idenfitying it), you must re-define the view on every launch of the app! * If the database needs to rebuild the view but the function hasn't been defined yet, * it will fail and the view will be empty, causing weird problems later on. * <p/> * It is very important that this block be a law-abiding map function! As in other * languages, it must be a "pure" function, with no side effects, that always emits * the same values given the same input document. That means that it should not access * or change any external state; be careful, since callbacks make that so easy that you * might do it inadvertently! The callback may be called on any thread, or on * multiple threads simultaneously. This won't be a problem if the code is "pure" as * described above, since it will as a consequence also be thread-safe. */ @InterfaceAudience.Public public boolean setMapReduce(Mapper mapBlock, Reducer reduceBlock, String version) { assert (mapBlock != null); assert (version != null); boolean changed = (this.version == null || !this.version.equals(version)); this.mapBlock = mapBlock; this.reduceBlock = reduceBlock; this.version = version; viewStore.setVersion(version); // for SQLite return changed; } /** * Defines a view that has no reduce function. * See setMapReduce() for more information. */ @InterfaceAudience.Public public boolean setMap(Mapper mapBlock, String version) { return setMapReduce(mapBlock, null, version); } /** * Is the view's index currently out of date? */ @InterfaceAudience.Public public boolean isStale() { return (viewStore.getLastSequenceIndexed() < database.getLastSequenceNumber()); } /** * Get total number of rows in the view. The view's index will be updated if needed * before returning the value. */ @InterfaceAudience.Public public int getTotalRows() { try { updateIndex(); } catch (CouchbaseLiteException e) { Log.e(Log.TAG_VIEW, "Update index failed when getting the total rows", e); } return getCurrentTotalRows(); } /** * Get the last sequence number indexed so far. */ @InterfaceAudience.Public public long getLastSequenceIndexed() { return viewStore.getLastSequenceIndexed(); } /** * Deletes the view's persistent index. It will be regenerated on the next query. */ @InterfaceAudience.Public public void deleteIndex() { viewStore.deleteIndex(); } /** * Deletes the view, persistently. * <p/> * NOTE: It should be - (void) deleteView; */ @InterfaceAudience.Public public void delete() { if (viewStore != null) viewStore.deleteView(); if (database != null && name != null) database.forgetView(name); close(); } /** * Creates a new query object for this view. The query can be customized and then executed. */ @InterfaceAudience.Public public Query createQuery() { return new Query(database, this); } /** * Utility function to use in reduce blocks. Totals an array of Numbers. */ @InterfaceAudience.Public public static double totalValues(List<Object> values) { double total = 0; for (Object object : values) { if (object instanceof Number) { Number number = (Number) object; total += number.doubleValue(); } else { Log.w(Log.TAG_VIEW, "Warning non-numeric value found in totalValues: %s", object); } } return total; } /** * The registered object, if any, that can compile map/reduce functions from source code. */ @InterfaceAudience.Public public static ViewCompiler getCompiler() { return compiler; } /** * Registers an object that can compile map/reduce functions from source code. */ @InterfaceAudience.Public public static void setCompiler(ViewCompiler compiler) { View.compiler = compiler; } /////////////////////////////////////////////////////////////////////////// // Internal (CBLView+Internal.h) /////////////////////////////////////////////////////////////////////////// @InterfaceAudience.Private public int getCurrentTotalRows() { return viewStore.getTotalRows(); } public void close() { if (viewStore != null) viewStore.close(); viewStore = null; database = null; } @InterfaceAudience.Private public void setCollation(TDViewCollation collation) { viewStore.setCollation(collation); } /** * Updates the view's index (incrementally) if necessary. * Multiple views whose name starts with the same prefix before the slash as the view's * will be indexed together at once. * * @return Status OK if updated or NOT_MODIFIED if already up-to-date. * @throws CouchbaseLiteException */ @InterfaceAudience.Private public Status updateIndex() throws CouchbaseLiteException { return updateIndexes(getViewsInGroup()); } /** * Updates the view's index (incrementally) if necessary. * Only the view's index alone will be updated. * * @return Status OK if updated or NOT_MODIFIED if already up-to-date. * @throws CouchbaseLiteException */ @InterfaceAudience.Private public Status updateIndexAlone() throws CouchbaseLiteException { return updateIndexes(Arrays.asList(this)); } /** * Update multiple view indexes at once. * * @param views a list of views whose index will be updated. * @throws CouchbaseLiteException */ @InterfaceAudience.Private protected Status updateIndexes(List<View> views) throws CouchbaseLiteException { List<ViewStore> storages = new ArrayList<ViewStore>(); for (View view : views) { storages.add(view.viewStore); } return viewStore.updateIndexes(storages); } /** * Get all views that have the same prefix if specified. * The prefix ends with slash '/' character. * * @return An array of all views with the same prefix. */ @InterfaceAudience.Private protected List<View> getViewsInGroup() { List<View> views = new ArrayList<View>(); int slash = name.indexOf('/'); if (slash > 0) { String prefix = name.substring(0, slash + 1); for (View view : database.getAllViews()) { if (view.name.startsWith(prefix)) views.add(view); } } else views.add(this); return views; } /** * Queries the view. Does NOT first update the index. * * @param options The options to use. * @return An array of QueryRow objects. */ @InterfaceAudience.Private public List<QueryRow> query(QueryOptions options) throws CouchbaseLiteException { if (options == null) options = new QueryOptions(); if (groupOrReduce(options)) return viewStore.reducedQuery(options); else return viewStore.regularQuery(options); } /** * Gets whether the view is a design doc view. * @return Whether the view is a design doc view. */ @InterfaceAudience.Private public boolean isDesignDoc() { return isDesignDoc; } /** * Marks the view as a design doc view. * @param designDoc design doc flag. */ @InterfaceAudience.Private public void setDesignDoc(boolean designDoc) { isDesignDoc = designDoc; } /////////////////////////////////////////////////////////////////////////// // Public Static Methods /////////////////////////////////////////////////////////////////////////// /** * Changes a maxKey into one that also extends to any key it matches as a prefix */ @InterfaceAudience.Private public static Object keyForPrefixMatch(Object key, int depth) { if (depth < 1) { return key; } else if (key instanceof String) { // Kludge: prefix match a string by appending max possible character value to it return (String) key + '\uffff'; } else if (key instanceof List) { List<Object> nuKey = new ArrayList<Object>(((List<Object>) key)); if (depth == 1) { nuKey.add(new HashMap<String, Object>()); } else { Object lastObject = keyForPrefixMatch(nuKey.get(nuKey.size() - 1), depth - 1); nuKey.set(nuKey.size() - 1, lastObject); } return nuKey; } else { return key; } } private boolean groupOrReduce(QueryOptions options) { if (options.isGroup() || options.getGroupLevel() > 0) return true; else if (options.isReduceSpecified()) return options.isReduce(); else return this.reduceBlock != null; } /////////////////////////////////////////////////////////////////////////// // For Debugging /////////////////////////////////////////////////////////////////////////// @InterfaceAudience.Private protected List<Map<String, Object>> dump() { return viewStore.dump(); } @Override public String toString() { return "View{" + "name='" + name + '\'' + ", version='" + version + '\'' + '}'; } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.job.entries.ftpput; import java.net.InetAddress; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.Props; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.ftpput.JobEntryFTPPUT; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.LabelTextVar; import org.pentaho.di.ui.core.widget.PasswordTextVar; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; import com.enterprisedt.net.ftp.FTPClient; /** * This dialog allows you to edit the FTP Put job entry settings * * @author Samatar * @since 15-09-2007 */ public class JobEntryFTPPUTDialog extends JobEntryDialog implements JobEntryDialogInterface { private static Class<?> PKG = JobEntryFTPPUT.class; // for i18n purposes, needed by Translator2!! private Label wlName; private Text wName; private FormData fdlName, fdName; private Label wlServerName; private TextVar wServerName; private FormData fdlServerName, fdServerName; private Label wlServerPort; private TextVar wServerPort; private FormData fdlServerPort, fdServerPort; private Label wlUserName; private TextVar wUserName; private FormData fdlUserName, fdUserName; private Label wlPassword; private TextVar wPassword; private FormData fdlPassword, fdPassword; private Label wlLocalDirectory; private TextVar wLocalDirectory; private FormData fdlLocalDirectory, fdLocalDirectory; private Label wlRemoteDirectory; private TextVar wRemoteDirectory; private FormData fdlRemoteDirectory, fdRemoteDirectory; private Label wlWildcard; private TextVar wWildcard; private FormData fdlWildcard, fdWildcard; private Label wlRemove; private Button wRemove; private FormData fdlRemove, fdRemove; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Listener lsCheckRemoteFolder; private JobEntryFTPPUT jobEntry; private Shell shell; private Button wbTestRemoteDirectoryExists; private FormData fdbTestRemoteDirectoryExists; private Button wTest; private FormData fdTest; private Listener lsTest; private SelectionAdapter lsDef; private boolean changed; private Label wlBinaryMode; private Button wBinaryMode; private FormData fdlBinaryMode, fdBinaryMode; private TextVar wTimeout; private Label wlTimeout; private FormData fdTimeout, fdlTimeout; private Label wlOnlyNew; private Button wOnlyNew; private FormData fdlOnlyNew, fdOnlyNew; private Label wlActive; private Button wActive; private FormData fdlActive, fdActive; private Label wlControlEncoding; private Combo wControlEncoding; private FormData fdlControlEncoding, fdControlEncoding; private CTabFolder wTabFolder; private Composite wGeneralComp, wFilesComp, wSocksProxyComp; private CTabItem wGeneralTab, wFilesTab, wSocksProxyTab; private FormData fdGeneralComp, fdFilesComp; private FormData fdTabFolder; private Group wSourceSettings, wTargetSettings; private FormData fdSourceSettings, fdTargetSettings; private Group wServerSettings; private FormData fdServerSettings; private Group wAdvancedSettings; private FormData fdAdvancedSettings; private FormData fdProxyHost; private LabelTextVar wProxyPort; private FormData fdProxyPort; private LabelTextVar wProxyUsername; private FormData fdProxyUsername; private LabelTextVar wProxyPassword; private FormData fdProxyPasswd; private LabelTextVar wProxyHost; private Group wSocksProxy; private LabelTextVar wSocksProxyHost, wSocksProxyPort, wSocksProxyUsername, wSocksProxyPassword; private FormData fdSocksProxyHost; private FormData fdSocksProxyPort; private FormData fdSocksProxyUsername; private FormData fdSocksProxyPassword; private FormData fdSocksProxyComp; // These should not be translated, they are required to exist on all // platforms according to the documentation of "Charset". private static String[] encodings = { "US-ASCII", "ISO-8859-1", "UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16" }; private Button wbLocalDirectory; private FormData fdbLocalDirectory; private FTPClient ftpclient = null; private String pwdFolder = null; public JobEntryFTPPUTDialog( Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta ) { super( parent, jobEntryInt, rep, jobMeta ); jobEntry = (JobEntryFTPPUT) jobEntryInt; if ( this.jobEntry.getName() == null ) { this.jobEntry.setName( BaseMessages.getString( PKG, "JobFTPPUT.Name.Default" ) ); } } public JobEntryInterface open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, props.getJobsDialogStyle() ); props.setLook( shell ); JobDialog.setShellImage( shell, jobEntry ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { ftpclient = null; pwdFolder = null; jobEntry.setChanged(); } }; changed = jobEntry.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "JobFTPPUT.Title" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Filename line wlName = new Label( shell, SWT.RIGHT ); wlName.setText( BaseMessages.getString( PKG, "JobFTPPUT.Name.Label" ) ); props.setLook( wlName ); fdlName = new FormData(); fdlName.left = new FormAttachment( 0, 0 ); fdlName.right = new FormAttachment( middle, -margin ); fdlName.top = new FormAttachment( 0, margin ); wlName.setLayoutData( fdlName ); wName = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wName ); wName.addModifyListener( lsMod ); fdName = new FormData(); fdName.left = new FormAttachment( middle, 0 ); fdName.top = new FormAttachment( 0, margin ); fdName.right = new FormAttachment( 100, 0 ); wName.setLayoutData( fdName ); wTabFolder = new CTabFolder( shell, SWT.BORDER ); props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB ); // //////////////////////// // START OF GENERAL TAB /// // //////////////////////// wGeneralTab = new CTabItem( wTabFolder, SWT.NONE ); wGeneralTab.setText( BaseMessages.getString( PKG, "JobFTPPUT.Tab.General.Label" ) ); wGeneralComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wGeneralComp ); FormLayout generalLayout = new FormLayout(); generalLayout.marginWidth = 3; generalLayout.marginHeight = 3; wGeneralComp.setLayout( generalLayout ); // //////////////////////// // START OF SERVER SETTINGS GROUP/// // / wServerSettings = new Group( wGeneralComp, SWT.SHADOW_NONE ); props.setLook( wServerSettings ); wServerSettings.setText( BaseMessages.getString( PKG, "JobFTPPUT.ServerSettings.Group.Label" ) ); FormLayout ServerSettingsgroupLayout = new FormLayout(); ServerSettingsgroupLayout.marginWidth = 10; ServerSettingsgroupLayout.marginHeight = 10; wServerSettings.setLayout( ServerSettingsgroupLayout ); // ServerName line wlServerName = new Label( wServerSettings, SWT.RIGHT ); wlServerName.setText( BaseMessages.getString( PKG, "JobFTPPUT.Server.Label" ) ); props.setLook( wlServerName ); fdlServerName = new FormData(); fdlServerName.left = new FormAttachment( 0, 0 ); fdlServerName.top = new FormAttachment( wName, margin ); fdlServerName.right = new FormAttachment( middle, 0 ); wlServerName.setLayoutData( fdlServerName ); wServerName = new TextVar( jobMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wServerName ); wServerName.addModifyListener( lsMod ); fdServerName = new FormData(); fdServerName.left = new FormAttachment( middle, margin ); fdServerName.top = new FormAttachment( wName, margin ); fdServerName.right = new FormAttachment( 100, 0 ); wServerName.setLayoutData( fdServerName ); // ServerPort line wlServerPort = new Label( wServerSettings, SWT.RIGHT ); wlServerPort.setText( BaseMessages.getString( PKG, "JobFTPPUT.Port.Label" ) ); props.setLook( wlServerPort ); fdlServerPort = new FormData(); fdlServerPort.left = new FormAttachment( 0, 0 ); fdlServerPort.top = new FormAttachment( wServerName, margin ); fdlServerPort.right = new FormAttachment( middle, 0 ); wlServerPort.setLayoutData( fdlServerPort ); wServerPort = new TextVar( jobMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wServerPort ); wServerPort.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.Port.Tooltip" ) ); wServerPort.addModifyListener( lsMod ); fdServerPort = new FormData(); fdServerPort.left = new FormAttachment( middle, margin ); fdServerPort.top = new FormAttachment( wServerName, margin ); fdServerPort.right = new FormAttachment( 100, 0 ); wServerPort.setLayoutData( fdServerPort ); // UserName line wlUserName = new Label( wServerSettings, SWT.RIGHT ); wlUserName.setText( BaseMessages.getString( PKG, "JobFTPPUT.Username.Label" ) ); props.setLook( wlUserName ); fdlUserName = new FormData(); fdlUserName.left = new FormAttachment( 0, 0 ); fdlUserName.top = new FormAttachment( wServerPort, margin ); fdlUserName.right = new FormAttachment( middle, 0 ); wlUserName.setLayoutData( fdlUserName ); wUserName = new TextVar( jobMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wUserName ); wUserName.addModifyListener( lsMod ); fdUserName = new FormData(); fdUserName.left = new FormAttachment( middle, margin ); fdUserName.top = new FormAttachment( wServerPort, margin ); fdUserName.right = new FormAttachment( 100, 0 ); wUserName.setLayoutData( fdUserName ); // Password line wlPassword = new Label( wServerSettings, SWT.RIGHT ); wlPassword.setText( BaseMessages.getString( PKG, "JobFTPPUT.Password.Label" ) ); props.setLook( wlPassword ); fdlPassword = new FormData(); fdlPassword.left = new FormAttachment( 0, 0 ); fdlPassword.top = new FormAttachment( wUserName, margin ); fdlPassword.right = new FormAttachment( middle, 0 ); wlPassword.setLayoutData( fdlPassword ); wPassword = new PasswordTextVar( jobMeta, wServerSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wPassword ); wPassword.addModifyListener( lsMod ); fdPassword = new FormData(); fdPassword.left = new FormAttachment( middle, margin ); fdPassword.top = new FormAttachment( wUserName, margin ); fdPassword.right = new FormAttachment( 100, 0 ); wPassword.setLayoutData( fdPassword ); // Proxy host line wProxyHost = new LabelTextVar( jobMeta, wServerSettings, BaseMessages.getString( PKG, "JobFTPPUT.ProxyHost.Label" ), BaseMessages .getString( PKG, "JobFTPPUT.ProxyHost.Tooltip" ) ); props.setLook( wProxyHost ); wProxyHost.addModifyListener( lsMod ); fdProxyHost = new FormData(); fdProxyHost.left = new FormAttachment( 0, 0 ); fdProxyHost.top = new FormAttachment( wPassword, 2 * margin ); fdProxyHost.right = new FormAttachment( 100, 0 ); wProxyHost.setLayoutData( fdProxyHost ); // Proxy port line wProxyPort = new LabelTextVar( jobMeta, wServerSettings, BaseMessages.getString( PKG, "JobFTPPUT.ProxyPort.Label" ), BaseMessages .getString( PKG, "JobFTPPUT.ProxyPort.Tooltip" ) ); props.setLook( wProxyPort ); wProxyPort.addModifyListener( lsMod ); fdProxyPort = new FormData(); fdProxyPort.left = new FormAttachment( 0, 0 ); fdProxyPort.top = new FormAttachment( wProxyHost, margin ); fdProxyPort.right = new FormAttachment( 100, 0 ); wProxyPort.setLayoutData( fdProxyPort ); // Proxy username line wProxyUsername = new LabelTextVar( jobMeta, wServerSettings, BaseMessages.getString( PKG, "JobFTPPUT.ProxyUsername.Label" ), BaseMessages .getString( PKG, "JobFTPPUT.ProxyUsername.Tooltip" ) ); props.setLook( wProxyUsername ); wProxyUsername.addModifyListener( lsMod ); fdProxyUsername = new FormData(); fdProxyUsername.left = new FormAttachment( 0, 0 ); fdProxyUsername.top = new FormAttachment( wProxyPort, margin ); fdProxyUsername.right = new FormAttachment( 100, 0 ); wProxyUsername.setLayoutData( fdProxyUsername ); // Proxy password line wProxyPassword = new LabelTextVar( jobMeta, wServerSettings, BaseMessages.getString( PKG, "JobFTPPUT.ProxyPassword.Label" ), BaseMessages .getString( PKG, "JobFTPPUT.ProxyPassword.Tooltip" ), true ); props.setLook( wProxyPassword ); wProxyPassword.addModifyListener( lsMod ); fdProxyPasswd = new FormData(); fdProxyPasswd.left = new FormAttachment( 0, 0 ); fdProxyPasswd.top = new FormAttachment( wProxyUsername, margin ); fdProxyPasswd.right = new FormAttachment( 100, 0 ); wProxyPassword.setLayoutData( fdProxyPasswd ); // Test connection button wTest = new Button( wServerSettings, SWT.PUSH ); wTest.setText( BaseMessages.getString( PKG, "JobFTPPUT.TestConnection.Label" ) ); props.setLook( wTest ); fdTest = new FormData(); wTest.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.TestConnection.Tooltip" ) ); fdTest.top = new FormAttachment( wProxyPassword, margin ); fdTest.right = new FormAttachment( 100, 0 ); wTest.setLayoutData( fdTest ); fdServerSettings = new FormData(); fdServerSettings.left = new FormAttachment( 0, margin ); fdServerSettings.top = new FormAttachment( wName, margin ); fdServerSettings.right = new FormAttachment( 100, -margin ); wServerSettings.setLayoutData( fdServerSettings ); // /////////////////////////////////////////////////////////// // / END OF SERVER SETTINGS GROUP // /////////////////////////////////////////////////////////// // //////////////////////// // START OF Advanced SETTINGS GROUP/// // / wAdvancedSettings = new Group( wGeneralComp, SWT.SHADOW_NONE ); props.setLook( wAdvancedSettings ); wAdvancedSettings.setText( BaseMessages.getString( PKG, "JobFTPPUT.AdvancedSettings.Group.Label" ) ); FormLayout AdvancedSettingsgroupLayout = new FormLayout(); AdvancedSettingsgroupLayout.marginWidth = 10; AdvancedSettingsgroupLayout.marginHeight = 10; wAdvancedSettings.setLayout( AdvancedSettingsgroupLayout ); // Binary mode selection... wlBinaryMode = new Label( wAdvancedSettings, SWT.RIGHT ); wlBinaryMode.setText( BaseMessages.getString( PKG, "JobFTPPUT.BinaryMode.Label" ) ); props.setLook( wlBinaryMode ); fdlBinaryMode = new FormData(); fdlBinaryMode.left = new FormAttachment( 0, 0 ); fdlBinaryMode.top = new FormAttachment( wServerSettings, margin ); fdlBinaryMode.right = new FormAttachment( middle, 0 ); wlBinaryMode.setLayoutData( fdlBinaryMode ); wBinaryMode = new Button( wAdvancedSettings, SWT.CHECK ); props.setLook( wBinaryMode ); wBinaryMode.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.BinaryMode.Tooltip" ) ); fdBinaryMode = new FormData(); fdBinaryMode.left = new FormAttachment( middle, 0 ); fdBinaryMode.top = new FormAttachment( wServerSettings, margin ); fdBinaryMode.right = new FormAttachment( 100, 0 ); wBinaryMode.setLayoutData( fdBinaryMode ); // TimeOut... wlTimeout = new Label( wAdvancedSettings, SWT.RIGHT ); wlTimeout.setText( BaseMessages.getString( PKG, "JobFTPPUT.Timeout.Label" ) ); props.setLook( wlTimeout ); fdlTimeout = new FormData(); fdlTimeout.left = new FormAttachment( 0, 0 ); fdlTimeout.top = new FormAttachment( wBinaryMode, margin ); fdlTimeout.right = new FormAttachment( middle, 0 ); wlTimeout.setLayoutData( fdlTimeout ); wTimeout = new TextVar( jobMeta, wAdvancedSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString( PKG, "JobFTPPUT.Timeout.Tooltip" ) ); props.setLook( wTimeout ); wTimeout.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.Timeout.Tooltip" ) ); fdTimeout = new FormData(); fdTimeout.left = new FormAttachment( middle, 0 ); fdTimeout.top = new FormAttachment( wBinaryMode, margin ); fdTimeout.right = new FormAttachment( 100, 0 ); wTimeout.setLayoutData( fdTimeout ); // active connection? wlActive = new Label( wAdvancedSettings, SWT.RIGHT ); wlActive.setText( BaseMessages.getString( PKG, "JobFTPPUT.ActiveConns.Label" ) ); props.setLook( wlActive ); fdlActive = new FormData(); fdlActive.left = new FormAttachment( 0, 0 ); fdlActive.top = new FormAttachment( wTimeout, margin ); fdlActive.right = new FormAttachment( middle, 0 ); wlActive.setLayoutData( fdlActive ); wActive = new Button( wAdvancedSettings, SWT.CHECK ); wActive.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.ActiveConns.Tooltip" ) ); props.setLook( wActive ); fdActive = new FormData(); fdActive.left = new FormAttachment( middle, 0 ); fdActive.top = new FormAttachment( wTimeout, margin ); fdActive.right = new FormAttachment( 100, 0 ); wActive.setLayoutData( fdActive ); // Control encoding line // // The drop down is editable as it may happen an encoding may not be present // on one machine, but you may want to use it on your execution server // wlControlEncoding = new Label( wAdvancedSettings, SWT.RIGHT ); wlControlEncoding.setText( BaseMessages.getString( PKG, "JobFTPPUT.ControlEncoding.Label" ) ); props.setLook( wlControlEncoding ); fdlControlEncoding = new FormData(); fdlControlEncoding.left = new FormAttachment( 0, 0 ); fdlControlEncoding.top = new FormAttachment( wActive, margin ); fdlControlEncoding.right = new FormAttachment( middle, 0 ); wlControlEncoding.setLayoutData( fdlControlEncoding ); wControlEncoding = new Combo( wAdvancedSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wControlEncoding.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.ControlEncoding.Tooltip" ) ); wControlEncoding.setItems( encodings ); props.setLook( wControlEncoding ); fdControlEncoding = new FormData(); fdControlEncoding.left = new FormAttachment( middle, 0 ); fdControlEncoding.top = new FormAttachment( wActive, margin ); fdControlEncoding.right = new FormAttachment( 100, 0 ); wControlEncoding.setLayoutData( fdControlEncoding ); fdAdvancedSettings = new FormData(); fdAdvancedSettings.left = new FormAttachment( 0, margin ); fdAdvancedSettings.top = new FormAttachment( wServerSettings, margin ); fdAdvancedSettings.right = new FormAttachment( 100, -margin ); wAdvancedSettings.setLayoutData( fdAdvancedSettings ); // /////////////////////////////////////////////////////////// // / END OF Advanced SETTINGS GROUP // /////////////////////////////////////////////////////////// fdGeneralComp = new FormData(); fdGeneralComp.left = new FormAttachment( 0, 0 ); fdGeneralComp.top = new FormAttachment( 0, 0 ); fdGeneralComp.right = new FormAttachment( 100, 0 ); fdGeneralComp.bottom = new FormAttachment( 100, 0 ); wGeneralComp.setLayoutData( fdGeneralComp ); wGeneralComp.layout(); wGeneralTab.setControl( wGeneralComp ); props.setLook( wGeneralComp ); // /////////////////////////////////////////////////////////// // / END OF GENERAL TAB // /////////////////////////////////////////////////////////// // //////////////////////// // START OF Files TAB /// // //////////////////////// wFilesTab = new CTabItem( wTabFolder, SWT.NONE ); wFilesTab.setText( BaseMessages.getString( PKG, "JobFTPPUT.Tab.Files.Label" ) ); wFilesComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wFilesComp ); FormLayout FilesLayout = new FormLayout(); FilesLayout.marginWidth = 3; FilesLayout.marginHeight = 3; wFilesComp.setLayout( FilesLayout ); // //////////////////////// // START OF Source SETTINGS GROUP/// // / wSourceSettings = new Group( wFilesComp, SWT.SHADOW_NONE ); props.setLook( wSourceSettings ); wSourceSettings.setText( BaseMessages.getString( PKG, "JobFTPPUT.SourceSettings.Group.Label" ) ); FormLayout SourceSettinsgroupLayout = new FormLayout(); SourceSettinsgroupLayout.marginWidth = 10; SourceSettinsgroupLayout.marginHeight = 10; wSourceSettings.setLayout( SourceSettinsgroupLayout ); // Local (source) directory line wlLocalDirectory = new Label( wSourceSettings, SWT.RIGHT ); wlLocalDirectory.setText( BaseMessages.getString( PKG, "JobFTPPUT.LocalDir.Label" ) ); props.setLook( wlLocalDirectory ); fdlLocalDirectory = new FormData(); fdlLocalDirectory.left = new FormAttachment( 0, 0 ); fdlLocalDirectory.top = new FormAttachment( 0, margin ); fdlLocalDirectory.right = new FormAttachment( middle, -margin ); wlLocalDirectory.setLayoutData( fdlLocalDirectory ); // Browse folders button ... wbLocalDirectory = new Button( wSourceSettings, SWT.PUSH | SWT.CENTER ); props.setLook( wbLocalDirectory ); wbLocalDirectory.setText( BaseMessages.getString( PKG, "JobFTPPUT.BrowseFolders.Label" ) ); fdbLocalDirectory = new FormData(); fdbLocalDirectory.right = new FormAttachment( 100, 0 ); fdbLocalDirectory.top = new FormAttachment( 0, margin ); wbLocalDirectory.setLayoutData( fdbLocalDirectory ); wLocalDirectory = new TextVar( jobMeta, wSourceSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString( PKG, "JobFTPPUT.LocalDir.Tooltip" ) ); props.setLook( wLocalDirectory ); wLocalDirectory.addModifyListener( lsMod ); fdLocalDirectory = new FormData(); fdLocalDirectory.left = new FormAttachment( middle, 0 ); fdLocalDirectory.top = new FormAttachment( 0, margin ); fdLocalDirectory.right = new FormAttachment( wbLocalDirectory, -margin ); wLocalDirectory.setLayoutData( fdLocalDirectory ); // Wildcard line wlWildcard = new Label( wSourceSettings, SWT.RIGHT ); wlWildcard.setText( BaseMessages.getString( PKG, "JobFTPPUT.Wildcard.Label" ) ); props.setLook( wlWildcard ); fdlWildcard = new FormData(); fdlWildcard.left = new FormAttachment( 0, 0 ); fdlWildcard.top = new FormAttachment( wLocalDirectory, margin ); fdlWildcard.right = new FormAttachment( middle, -margin ); wlWildcard.setLayoutData( fdlWildcard ); wWildcard = new TextVar( jobMeta, wSourceSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString( PKG, "JobFTPPUT.Wildcard.Tooltip" ) ); props.setLook( wWildcard ); wWildcard.addModifyListener( lsMod ); fdWildcard = new FormData(); fdWildcard.left = new FormAttachment( middle, 0 ); fdWildcard.top = new FormAttachment( wLocalDirectory, margin ); fdWildcard.right = new FormAttachment( 100, 0 ); wWildcard.setLayoutData( fdWildcard ); // Remove files after retrieval... wlRemove = new Label( wSourceSettings, SWT.RIGHT ); wlRemove.setText( BaseMessages.getString( PKG, "JobFTPPUT.RemoveFiles.Label" ) ); props.setLook( wlRemove ); fdlRemove = new FormData(); fdlRemove.left = new FormAttachment( 0, 0 ); fdlRemove.top = new FormAttachment( wWildcard, 2 * margin ); fdlRemove.right = new FormAttachment( middle, -margin ); wlRemove.setLayoutData( fdlRemove ); wRemove = new Button( wSourceSettings, SWT.CHECK ); props.setLook( wRemove ); wRemove.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.RemoveFiles.Tooltip" ) ); fdRemove = new FormData(); fdRemove.left = new FormAttachment( middle, 0 ); fdRemove.top = new FormAttachment( wWildcard, 2 * margin ); fdRemove.right = new FormAttachment( 100, 0 ); wRemove.setLayoutData( fdRemove ); // OnlyNew files after retrieval... wlOnlyNew = new Label( wSourceSettings, SWT.RIGHT ); wlOnlyNew.setText( BaseMessages.getString( PKG, "JobFTPPUT.DontOverwrite.Label" ) ); props.setLook( wlOnlyNew ); fdlOnlyNew = new FormData(); fdlOnlyNew.left = new FormAttachment( 0, 0 ); fdlOnlyNew.top = new FormAttachment( wRemove, margin ); fdlOnlyNew.right = new FormAttachment( middle, 0 ); wlOnlyNew.setLayoutData( fdlOnlyNew ); wOnlyNew = new Button( wSourceSettings, SWT.CHECK ); wOnlyNew.setToolTipText( BaseMessages.getString( PKG, "JobFTPPUT.DontOverwrite.Tooltip" ) ); props.setLook( wOnlyNew ); fdOnlyNew = new FormData(); fdOnlyNew.left = new FormAttachment( middle, 0 ); fdOnlyNew.top = new FormAttachment( wRemove, margin ); fdOnlyNew.right = new FormAttachment( 100, 0 ); wOnlyNew.setLayoutData( fdOnlyNew ); fdSourceSettings = new FormData(); fdSourceSettings.left = new FormAttachment( 0, margin ); fdSourceSettings.top = new FormAttachment( 0, 2 * margin ); fdSourceSettings.right = new FormAttachment( 100, -margin ); wSourceSettings.setLayoutData( fdSourceSettings ); // /////////////////////////////////////////////////////////// // / END OF Source SETTINGSGROUP // /////////////////////////////////////////////////////////// // //////////////////////// // START OF Target SETTINGS GROUP/// // / wTargetSettings = new Group( wFilesComp, SWT.SHADOW_NONE ); props.setLook( wTargetSettings ); wTargetSettings.setText( BaseMessages.getString( PKG, "JobFTPPUT.TargetSettings.Group.Label" ) ); FormLayout TargetSettinsgroupLayout = new FormLayout(); TargetSettinsgroupLayout.marginWidth = 10; TargetSettinsgroupLayout.marginHeight = 10; wTargetSettings.setLayout( TargetSettinsgroupLayout ); // Remote Directory line wlRemoteDirectory = new Label( wTargetSettings, SWT.RIGHT ); wlRemoteDirectory.setText( BaseMessages.getString( PKG, "JobFTPPUT.RemoteDir.Label" ) ); props.setLook( wlRemoteDirectory ); fdlRemoteDirectory = new FormData(); fdlRemoteDirectory.left = new FormAttachment( 0, 0 ); fdlRemoteDirectory.top = new FormAttachment( wSourceSettings, margin ); fdlRemoteDirectory.right = new FormAttachment( middle, -margin ); wlRemoteDirectory.setLayoutData( fdlRemoteDirectory ); // Test remote folder button ... wbTestRemoteDirectoryExists = new Button( wTargetSettings, SWT.PUSH | SWT.CENTER ); props.setLook( wbTestRemoteDirectoryExists ); wbTestRemoteDirectoryExists.setText( BaseMessages.getString( PKG, "JobFTPPUT.TestFolderExists.Label" ) ); fdbTestRemoteDirectoryExists = new FormData(); fdbTestRemoteDirectoryExists.right = new FormAttachment( 100, 0 ); fdbTestRemoteDirectoryExists.top = new FormAttachment( wSourceSettings, margin ); wbTestRemoteDirectoryExists.setLayoutData( fdbTestRemoteDirectoryExists ); wRemoteDirectory = new TextVar( jobMeta, wTargetSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString( PKG, "JobFTPPUT.RemoteDir.Tooltip" ) ); props.setLook( wRemoteDirectory ); wRemoteDirectory.addModifyListener( lsMod ); fdRemoteDirectory = new FormData(); fdRemoteDirectory.left = new FormAttachment( middle, 0 ); fdRemoteDirectory.top = new FormAttachment( wSourceSettings, margin ); fdRemoteDirectory.right = new FormAttachment( wbTestRemoteDirectoryExists, -margin ); wRemoteDirectory.setLayoutData( fdRemoteDirectory ); fdTargetSettings = new FormData(); fdTargetSettings.left = new FormAttachment( 0, margin ); fdTargetSettings.top = new FormAttachment( wSourceSettings, margin ); fdTargetSettings.right = new FormAttachment( 100, -margin ); wTargetSettings.setLayoutData( fdTargetSettings ); // /////////////////////////////////////////////////////////// // / END OF Target SETTINGSGROUP // /////////////////////////////////////////////////////////// fdFilesComp = new FormData(); fdFilesComp.left = new FormAttachment( 0, 0 ); fdFilesComp.top = new FormAttachment( 0, 0 ); fdFilesComp.right = new FormAttachment( 100, 0 ); fdFilesComp.bottom = new FormAttachment( 100, 0 ); wFilesComp.setLayoutData( fdFilesComp ); wFilesComp.layout(); wFilesTab.setControl( wFilesComp ); props.setLook( wFilesComp ); // /////////////////////////////////////////////////////////// // / END OF Files TAB // /////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////// // Start of Socks Proxy Tab // /////////////////////////////////////////////////////////// wSocksProxyTab = new CTabItem( wTabFolder, SWT.NONE ); wSocksProxyTab.setText( BaseMessages.getString( PKG, "JobFTPPUT.Tab.Socks.Label" ) ); wSocksProxyComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wSocksProxyComp ); FormLayout SoxProxyLayout = new FormLayout(); SoxProxyLayout.marginWidth = 3; SoxProxyLayout.marginHeight = 3; wSocksProxyComp.setLayout( SoxProxyLayout ); // //////////////////////////////////////////////////////// // Start of Proxy Group // //////////////////////////////////////////////////////// wSocksProxy = new Group( wSocksProxyComp, SWT.SHADOW_NONE ); props.setLook( wSocksProxy ); wSocksProxy.setText( BaseMessages.getString( PKG, "JobFTPPUT.SocksProxy.Group.Label" ) ); FormLayout SocksProxyGroupLayout = new FormLayout(); SocksProxyGroupLayout.marginWidth = 10; SocksProxyGroupLayout.marginHeight = 10; wSocksProxy.setLayout( SocksProxyGroupLayout ); // host line wSocksProxyHost = new LabelTextVar( jobMeta, wSocksProxy, BaseMessages.getString( PKG, "JobFTPPUT.SocksProxyHost.Label" ), BaseMessages .getString( PKG, "JobFTPPUT.SocksProxyHost.Tooltip" ) ); props.setLook( wSocksProxyHost ); wSocksProxyHost.addModifyListener( lsMod ); fdSocksProxyHost = new FormData(); fdSocksProxyHost.left = new FormAttachment( 0, 0 ); fdSocksProxyHost.top = new FormAttachment( wName, margin ); fdSocksProxyHost.right = new FormAttachment( 100, margin ); wSocksProxyHost.setLayoutData( fdSocksProxyHost ); // port line wSocksProxyPort = new LabelTextVar( jobMeta, wSocksProxy, BaseMessages.getString( PKG, "JobFTPPUT.SocksProxyPort.Label" ), BaseMessages .getString( PKG, "JobFTPPUT.SocksProxyPort.Tooltip" ) ); props.setLook( wSocksProxyPort ); wSocksProxyPort.addModifyListener( lsMod ); fdSocksProxyPort = new FormData(); fdSocksProxyPort.left = new FormAttachment( 0, 0 ); fdSocksProxyPort.top = new FormAttachment( wSocksProxyHost, margin ); fdSocksProxyPort.right = new FormAttachment( 100, margin ); wSocksProxyPort.setLayoutData( fdSocksProxyPort ); // username line wSocksProxyUsername = new LabelTextVar( jobMeta, wSocksProxy, BaseMessages.getString( PKG, "JobFTPPUT.SocksProxyUsername.Label" ), BaseMessages.getString( PKG, "JobFTPPUT.SocksProxyPassword.Tooltip" ) ); props.setLook( wSocksProxyUsername ); wSocksProxyUsername.addModifyListener( lsMod ); fdSocksProxyUsername = new FormData(); fdSocksProxyUsername.left = new FormAttachment( 0, 0 ); fdSocksProxyUsername.top = new FormAttachment( wSocksProxyPort, margin ); fdSocksProxyUsername.right = new FormAttachment( 100, margin ); wSocksProxyUsername.setLayoutData( fdSocksProxyUsername ); // password line wSocksProxyPassword = new LabelTextVar( jobMeta, wSocksProxy, BaseMessages.getString( PKG, "JobFTPPUT.SocksProxyPassword.Label" ), BaseMessages.getString( PKG, "JobFTPPUT.SocksProxyPassword.Tooltip" ), true ); props.setLook( wSocksProxyPort ); wSocksProxyPassword.addModifyListener( lsMod ); fdSocksProxyPassword = new FormData(); fdSocksProxyPassword.left = new FormAttachment( 0, 0 ); fdSocksProxyPassword.top = new FormAttachment( wSocksProxyUsername, margin ); fdSocksProxyPassword.right = new FormAttachment( 100, margin ); wSocksProxyPassword.setLayoutData( fdSocksProxyPassword ); // /////////////////////////////////////////////////////////////// // End of socks proxy group // /////////////////////////////////////////////////////////////// fdSocksProxyComp = new FormData(); fdSocksProxyComp.left = new FormAttachment( 0, margin ); fdSocksProxyComp.top = new FormAttachment( 0, margin ); fdSocksProxyComp.right = new FormAttachment( 100, -margin ); wSocksProxy.setLayoutData( fdSocksProxyComp ); wSocksProxyComp.layout(); wSocksProxyTab.setControl( wSocksProxyComp ); props.setLook( wSocksProxyComp ); // //////////////////////////////////////////////////////// // End of Socks Proxy Tab // //////////////////////////////////////////////////////// fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment( 0, 0 ); fdTabFolder.top = new FormAttachment( wName, margin ); fdTabFolder.right = new FormAttachment( 100, 0 ); fdTabFolder.bottom = new FormAttachment( 100, -50 ); wTabFolder.setLayoutData( fdTabFolder ); wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, margin, wTabFolder ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; lsTest = new Listener() { public void handleEvent( Event e ) { test(); } }; lsCheckRemoteFolder = new Listener() { public void handleEvent( Event e ) { checkRemoteFolder( jobMeta.environmentSubstitute( wRemoteDirectory.getText() ) ); } }; wbLocalDirectory.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { DirectoryDialog ddialog = new DirectoryDialog( shell, SWT.OPEN ); if ( wLocalDirectory.getText() != null ) { ddialog.setFilterPath( jobMeta.environmentSubstitute( wLocalDirectory.getText() ) ); } // Calling open() will open and run the dialog. // It will return the selected directory, or // null if user cancels String dir = ddialog.open(); if ( dir != null ) { // Set the text box to the new selection wLocalDirectory.setText( dir ); } } } ); wCancel.addListener( SWT.Selection, lsCancel ); wOK.addListener( SWT.Selection, lsOK ); wbTestRemoteDirectoryExists.addListener( SWT.Selection, lsCheckRemoteFolder ); wTest.addListener( SWT.Selection, lsTest ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wName.addSelectionListener( lsDef ); wServerName.addSelectionListener( lsDef ); wUserName.addSelectionListener( lsDef ); wPassword.addSelectionListener( lsDef ); wRemoteDirectory.addSelectionListener( lsDef ); wLocalDirectory.addSelectionListener( lsDef ); wWildcard.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); getData(); wTabFolder.setSelection( 0 ); BaseStepDialog.setSize( shell ); shell.open(); props.setDialogSize( shell, "JobSFTPDialogSize" ); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return jobEntry; } private void closeFTPConnection() { // Close FTP connection if necessary if ( ftpclient != null && ftpclient.connected() ) { try { ftpclient.quit(); ftpclient = null; } catch ( Exception e ) { // Ignore errors } } } private void test() { if ( connectToFTP( false, null ) ) { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION ); mb.setMessage( BaseMessages.getString( PKG, "JobFTPPUT.Connected.OK", wServerName.getText() ) + Const.CR ); mb.setText( BaseMessages.getString( PKG, "JobFTPPUT.Connected.Title.Ok" ) ); mb.open(); } } private void checkRemoteFolder( String remoteFoldername ) { if ( !Utils.isEmpty( remoteFoldername ) ) { if ( connectToFTP( true, remoteFoldername ) ) { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION ); mb.setMessage( BaseMessages.getString( PKG, "JobFTPPUT.FolderExists.OK", remoteFoldername ) + Const.CR ); mb.setText( BaseMessages.getString( PKG, "JobFTPPUT.FolderExists.Title.Ok" ) ); mb.open(); } } } private boolean connectToFTP( boolean checkfolder, String remoteFoldername ) { boolean retval = false; String realServername = null; try { if ( ftpclient == null || !ftpclient.connected() ) { // Create ftp client to host:port ... ftpclient = new FTPClient(); realServername = jobMeta.environmentSubstitute( wServerName.getText() ); int realPort = Const.toInt( jobMeta.environmentSubstitute( wServerPort.getText() ), 21 ); ftpclient.setRemoteAddr( InetAddress.getByName( realServername ) ); ftpclient.setRemotePort( realPort ); if ( !Utils.isEmpty( wProxyHost.getText() ) ) { String realProxy_host = jobMeta.environmentSubstitute( wProxyHost.getText() ); ftpclient.setRemoteAddr( InetAddress.getByName( realProxy_host ) ); int port = Const.toInt( jobMeta.environmentSubstitute( wProxyPort.getText() ), 21 ); if ( port != 0 ) { ftpclient.setRemotePort( port ); } } // login to ftp host ... ftpclient.connect(); String realUsername = jobMeta.environmentSubstitute( wUserName.getText() ) + ( !Utils.isEmpty( wProxyHost.getText() ) ? "@" + realServername : "" ) + ( !Utils.isEmpty( wProxyUsername.getText() ) ? " " + jobMeta.environmentSubstitute( wProxyUsername.getText() ) : "" ); String realPassword = jobMeta.environmentSubstitute( wPassword.getText() ) + ( !Utils.isEmpty( wProxyPassword.getText() ) ? " " + jobMeta.environmentSubstitute( wProxyPassword.getText() ) : "" ); // login now ... ftpclient.login( realUsername, realPassword ); pwdFolder = ftpclient.pwd(); } if ( checkfolder ) { if ( pwdFolder != null ) { ftpclient.chdir( pwdFolder ); } // move to spool dir ... if ( !Utils.isEmpty( remoteFoldername ) ) { String realFtpDirectory = jobMeta.environmentSubstitute( remoteFoldername ); ftpclient.chdir( realFtpDirectory ); } } retval = true; } catch ( Exception e ) { if ( ftpclient != null ) { try { ftpclient.quit(); } catch ( Exception ignored ) { // We've tried quitting the FTP Client exception // nothing else can be done if the FTP Client was already disconnected } ftpclient = null; } MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage( BaseMessages.getString( PKG, "JobFTPPUT.ErrorConnect.NOK", realServername, e.getMessage() ) + Const.CR ); mb.setText( BaseMessages.getString( PKG, "JobFTPPUT.ErrorConnect.Title.Bad" ) ); mb.open(); } return retval; } public void dispose() { closeFTPConnection(); WindowProperty winprop = new WindowProperty( shell ); props.setScreen( winprop ); shell.dispose(); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if ( jobEntry.getName() != null ) { wName.setText( jobEntry.getName() ); } wServerName.setText( Const.NVL( jobEntry.getServerName(), "" ) ); wServerPort.setText( Const.NVL( jobEntry.getServerPort(), "" ) ); wUserName.setText( Const.NVL( jobEntry.getUserName(), "" ) ); wPassword.setText( Const.NVL( jobEntry.getPassword(), "" ) ); wRemoteDirectory.setText( Const.NVL( jobEntry.getRemoteDirectory(), "" ) ); wLocalDirectory.setText( Const.NVL( jobEntry.getLocalDirectory(), "" ) ); wWildcard.setText( Const.NVL( jobEntry.getWildcard(), "" ) ); wRemove.setSelection( jobEntry.getRemove() ); wBinaryMode.setSelection( jobEntry.isBinaryMode() ); wTimeout.setText( "" + jobEntry.getTimeout() ); wOnlyNew.setSelection( jobEntry.isOnlyPuttingNewFiles() ); wActive.setSelection( jobEntry.isActiveConnection() ); wControlEncoding.setText( jobEntry.getControlEncoding() ); wProxyHost.setText( Const.NVL( jobEntry.getProxyHost(), "" ) ); wProxyPort.setText( Const.NVL( jobEntry.getProxyPort(), "" ) ); wProxyUsername.setText( Const.NVL( jobEntry.getProxyUsername(), "" ) ); wProxyPassword.setText( Const.NVL( jobEntry.getProxyPassword(), "" ) ); wSocksProxyHost.setText( Const.NVL( jobEntry.getSocksProxyHost(), "" ) ); wSocksProxyPort.setText( Const.NVL( jobEntry.getSocksProxyPort(), "1080" ) ); wSocksProxyUsername.setText( Const.NVL( jobEntry.getSocksProxyUsername(), "" ) ); wSocksProxyPassword.setText( Const.NVL( jobEntry.getSocksProxyPassword(), "" ) ); wName.selectAll(); wName.setFocus(); } private void cancel() { jobEntry.setChanged( changed ); jobEntry = null; dispose(); } private void ok() { if ( Utils.isEmpty( wName.getText() ) ) { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setText( BaseMessages.getString( PKG, "System.StepJobEntryNameMissing.Title" ) ); mb.setMessage( BaseMessages.getString( PKG, "System.JobEntryNameMissing.Msg" ) ); mb.open(); return; } jobEntry.setName( wName.getText() ); jobEntry.setServerName( wServerName.getText() ); jobEntry.setServerPort( wServerPort.getText() ); jobEntry.setUserName( wUserName.getText() ); jobEntry.setPassword( wPassword.getText() ); jobEntry.setRemoteDirectory( wRemoteDirectory.getText() ); jobEntry.setLocalDirectory( wLocalDirectory.getText() ); jobEntry.setWildcard( wWildcard.getText() ); jobEntry.setRemove( wRemove.getSelection() ); jobEntry.setBinaryMode( wBinaryMode.getSelection() ); jobEntry.setTimeout( Const.toInt( wTimeout.getText(), 10000 ) ); jobEntry.setOnlyPuttingNewFiles( wOnlyNew.getSelection() ); jobEntry.setActiveConnection( wActive.getSelection() ); jobEntry.setControlEncoding( wControlEncoding.getText() ); jobEntry.setProxyHost( wProxyHost.getText() ); jobEntry.setProxyPort( wProxyPort.getText() ); jobEntry.setProxyUsername( wProxyUsername.getText() ); jobEntry.setProxyPassword( wProxyPassword.getText() ); jobEntry.setSocksProxyHost( wSocksProxyHost.getText() ); jobEntry.setSocksProxyPort( wSocksProxyPort.getText() ); jobEntry.setSocksProxyUsername( wSocksProxyUsername.getText() ); jobEntry.setSocksProxyPassword( wSocksProxyPassword.getText() ); dispose(); } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.upstream.cache; import static com.google.android.exoplayer2.util.Assertions.checkArgument; import static com.google.android.exoplayer2.util.Assertions.checkNotNull; import static com.google.android.exoplayer2.util.Assertions.checkState; import static java.lang.Math.max; import static java.lang.Math.min; import androidx.annotation.Nullable; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.util.Log; import java.io.File; import java.util.ArrayList; import java.util.TreeSet; /** Defines the cached content for a single resource. */ /* package */ final class CachedContent { private static final String TAG = "CachedContent"; /** The cache id that uniquely identifies the resource. */ public final int id; /** The cache key that uniquely identifies the resource. */ public final String key; /** The cached spans of this content. */ private final TreeSet<SimpleCacheSpan> cachedSpans; /** Currently locked ranges. */ private final ArrayList<Range> lockedRanges; /** Metadata values. */ private DefaultContentMetadata metadata; /** * Creates a CachedContent. * * @param id The cache id of the resource. * @param key The cache key of the resource. */ public CachedContent(int id, String key) { this(id, key, DefaultContentMetadata.EMPTY); } public CachedContent(int id, String key, DefaultContentMetadata metadata) { this.id = id; this.key = key; this.metadata = metadata; cachedSpans = new TreeSet<>(); lockedRanges = new ArrayList<>(); } /** Returns the metadata. */ public DefaultContentMetadata getMetadata() { return metadata; } /** * Applies {@code mutations} to the metadata. * * @return Whether {@code mutations} changed any metadata. */ public boolean applyMetadataMutations(ContentMetadataMutations mutations) { DefaultContentMetadata oldMetadata = metadata; metadata = metadata.copyWithMutationsApplied(mutations); return !metadata.equals(oldMetadata); } /** Returns whether the entire resource is fully unlocked. */ public boolean isFullyUnlocked() { return lockedRanges.isEmpty(); } /** * Returns whether the specified range of the resource is fully locked by a single lock. * * @param position The position of the range. * @param length The length of the range, or {@link C#LENGTH_UNSET} if unbounded. * @return Whether the range is fully locked by a single lock. */ public boolean isFullyLocked(long position, long length) { for (int i = 0; i < lockedRanges.size(); i++) { if (lockedRanges.get(i).contains(position, length)) { return true; } } return false; } /** * Attempts to lock the specified range of the resource. * * @param position The position of the range. * @param length The length of the range, or {@link C#LENGTH_UNSET} if unbounded. * @return Whether the range was successfully locked. */ public boolean lockRange(long position, long length) { for (int i = 0; i < lockedRanges.size(); i++) { if (lockedRanges.get(i).intersects(position, length)) { return false; } } lockedRanges.add(new Range(position, length)); return true; } /** * Unlocks the currently locked range starting at the specified position. * * @param position The starting position of the locked range. * @throws IllegalStateException If there was no locked range starting at the specified position. */ public void unlockRange(long position) { for (int i = 0; i < lockedRanges.size(); i++) { if (lockedRanges.get(i).position == position) { lockedRanges.remove(i); return; } } throw new IllegalStateException(); } /** Adds the given {@link SimpleCacheSpan} which contains a part of the content. */ public void addSpan(SimpleCacheSpan span) { cachedSpans.add(span); } /** Returns a set of all {@link SimpleCacheSpan}s. */ public TreeSet<SimpleCacheSpan> getSpans() { return cachedSpans; } /** * Returns the cache span corresponding to the provided range. See {@link * Cache#startReadWrite(String, long, long)} for detailed descriptions of the returned spans. * * @param position The position of the span being requested. * @param length The length of the span, or {@link C#LENGTH_UNSET} if unbounded. * @return The corresponding cache {@link SimpleCacheSpan}. */ public SimpleCacheSpan getSpan(long position, long length) { SimpleCacheSpan lookupSpan = SimpleCacheSpan.createLookup(key, position); SimpleCacheSpan floorSpan = cachedSpans.floor(lookupSpan); if (floorSpan != null && floorSpan.position + floorSpan.length > position) { return floorSpan; } SimpleCacheSpan ceilSpan = cachedSpans.ceiling(lookupSpan); if (ceilSpan != null) { long holeLength = ceilSpan.position - position; length = length == C.LENGTH_UNSET ? holeLength : min(holeLength, length); } return SimpleCacheSpan.createHole(key, position, length); } /** * Returns the length of continuously cached data starting from {@code position}, up to a maximum * of {@code maxLength}. If {@code position} isn't cached, then {@code -holeLength} is returned, * where {@code holeLength} is the length of continuously un-cached data starting from {@code * position}, up to a maximum of {@code maxLength}. * * @param position The starting position of the data. * @param length The maximum length of the data or hole to be returned. * @return The length of continuously cached data, or {@code -holeLength} if {@code position} * isn't cached. */ public long getCachedBytesLength(long position, long length) { checkArgument(position >= 0); checkArgument(length >= 0); SimpleCacheSpan span = getSpan(position, length); if (span.isHoleSpan()) { // We don't have a span covering the start of the queried region. return -min(span.isOpenEnded() ? Long.MAX_VALUE : span.length, length); } long queryEndPosition = position + length; if (queryEndPosition < 0) { // The calculation rolled over (length is probably Long.MAX_VALUE). queryEndPosition = Long.MAX_VALUE; } long currentEndPosition = span.position + span.length; if (currentEndPosition < queryEndPosition) { for (SimpleCacheSpan next : cachedSpans.tailSet(span, false)) { if (next.position > currentEndPosition) { // There's a hole in the cache within the queried region. break; } // We expect currentEndPosition to always equal (next.position + next.length), but // perform a max check anyway to guard against the existence of overlapping spans. currentEndPosition = max(currentEndPosition, next.position + next.length); if (currentEndPosition >= queryEndPosition) { // We've found spans covering the queried region. break; } } } return min(currentEndPosition - position, length); } /** * Sets the given span's last touch timestamp. The passed span becomes invalid after this call. * * @param cacheSpan Span to be copied and updated. * @param lastTouchTimestamp The new last touch timestamp. * @param updateFile Whether the span file should be renamed to have its timestamp match the new * last touch time. * @return A span with the updated last touch timestamp. */ public SimpleCacheSpan setLastTouchTimestamp( SimpleCacheSpan cacheSpan, long lastTouchTimestamp, boolean updateFile) { checkState(cachedSpans.remove(cacheSpan)); File file = checkNotNull(cacheSpan.file); if (updateFile) { File directory = checkNotNull(file.getParentFile()); long position = cacheSpan.position; File newFile = SimpleCacheSpan.getCacheFile(directory, id, position, lastTouchTimestamp); if (file.renameTo(newFile)) { file = newFile; } else { Log.w(TAG, "Failed to rename " + file + " to " + newFile); } } SimpleCacheSpan newCacheSpan = cacheSpan.copyWithFileAndLastTouchTimestamp(file, lastTouchTimestamp); cachedSpans.add(newCacheSpan); return newCacheSpan; } /** Returns whether there are any spans cached. */ public boolean isEmpty() { return cachedSpans.isEmpty(); } /** Removes the given span from cache. */ public boolean removeSpan(CacheSpan span) { if (cachedSpans.remove(span)) { if (span.file != null) { span.file.delete(); } return true; } return false; } @Override public int hashCode() { int result = id; result = 31 * result + key.hashCode(); result = 31 * result + metadata.hashCode(); return result; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CachedContent that = (CachedContent) o; return id == that.id && key.equals(that.key) && cachedSpans.equals(that.cachedSpans) && metadata.equals(that.metadata); } private static final class Range { /** The starting position of the range. */ public final long position; /** The length of the range, or {@link C#LENGTH_UNSET} if unbounded. */ public final long length; public Range(long position, long length) { this.position = position; this.length = length; } /** * Returns whether this range fully contains the range specified by {@code otherPosition} and * {@code otherLength}. * * @param otherPosition The position of the range to check. * @param otherLength The length of the range to check, or {@link C#LENGTH_UNSET} if unbounded. * @return Whether this range fully contains the specified range. */ public boolean contains(long otherPosition, long otherLength) { if (length == C.LENGTH_UNSET) { return otherPosition >= position; } else if (otherLength == C.LENGTH_UNSET) { return false; } else { return position <= otherPosition && (otherPosition + otherLength) <= (position + length); } } /** * Returns whether this range intersects with the range specified by {@code otherPosition} and * {@code otherLength}. * * @param otherPosition The position of the range to check. * @param otherLength The length of the range to check, or {@link C#LENGTH_UNSET} if unbounded. * @return Whether this range intersects with the specified range. */ public boolean intersects(long otherPosition, long otherLength) { if (position <= otherPosition) { return length == C.LENGTH_UNSET || position + length > otherPosition; } else { return otherLength == C.LENGTH_UNSET || otherPosition + otherLength > position; } } } }
package com.brein.activity; import com.brein.api.BreinActivity; import com.brein.api.Breinify; import com.brein.api.ICallback; import com.brein.domain.BreinActivityType; import com.brein.domain.BreinConfig; import com.brein.domain.BreinResult; import com.brein.domain.BreinUser; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.util.Properties; import static junit.framework.Assert.assertTrue; /** * This test cases shows how to use the activity */ @Ignore public class TestActivity { /** * This has to be a valid api key & secret */ private static final String VALID_API_KEY = "CA8A-8D28-3408-45A8-8E20-8474-06C0-8548"; private static final String VALID_SECRET = "lmcoj4k27hbbszzyiqamhg=="; /** * Contains the Breinify User */ private final BreinUser breinUser = new BreinUser("[email protected]"); /** * Contains the Category */ private final String breinCategory = "services"; /** * The Activity itself */ private final BreinActivity breinActivity = new BreinActivity(); class RestResult implements ICallback<BreinResult> { @Override public void callback(BreinResult data) { assertTrue(data != null); System.out.println("within RestResult"); System.out.println("Data is: " + data.toString()); } } private final ICallback<BreinResult> restCallback = new RestResult(); /** * Init part */ @BeforeClass public static void init() { // set logging on final Properties props = System.getProperties(); props.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "DEBUG"); } /** * Preparation of test case */ @Before public void setUp() { final BreinConfig breinConfig = new BreinConfig(VALID_API_KEY, VALID_SECRET); Breinify.setConfig(breinConfig); } /** * Housekeeping... */ @AfterClass public static void tearDown() { try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * */ @After public void wait4FiveSeconds() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * testcase how to use the activity api */ @Test public void testLogin() { breinUser.setFirstName("Toni"); breinUser.setLastName("Maroni"); breinActivity.setUser(breinUser); breinActivity.setActivityType(BreinActivityType.LOGIN); breinActivity.setCategory(breinCategory); breinActivity.setDescription("Bla"); breinActivity.execute(restCallback); } /** * Invoke a test call with 20 logins */ @Test public void testWith20Logins() { final int maxLogin = 20; for (int index = 0; index < maxLogin; index++) { testLogin(); } } /** * test case how to invoke logout activity */ @Test public void testLogout() { final String description = "Logout-Description"; breinUser.setDateOfBirth(12, 31, 2008); breinActivity.activity(breinUser, BreinActivityType.LOGOUT, breinCategory, description, restCallback); } /** * test case how to invoke search activity */ @Test public void testSearch() { final String description = "Search-Description"; breinActivity.activity(breinUser, BreinActivityType.SEARCH, breinCategory, description, restCallback); } /** * test case how to invoke add-to-cart activity */ @Test public void testAddToCart() { final String description = "AddToCart-Description"; breinActivity.activity(breinUser, BreinActivityType.ADD_TO_CART, breinCategory, description, restCallback); } /** * test case how to invoke remove-from-cart activity */ @Test public void testRemoveFromCart() { final String description = "RemoveFromCart-Description"; breinActivity.activity(breinUser, BreinActivityType.REMOVE_FROM_CART, breinCategory, description, restCallback); } /** * test case how to invoke select product */ @Test public void testSelectProduct() { final String description = "Select-Product-Description"; breinActivity.activity(breinUser, BreinActivityType.SELECT_PRODUCT, breinCategory, description, restCallback); } /** * test case how to invoke other */ @Test public void testOther() { final String description = "Other-Description"; breinActivity.activity(breinUser, BreinActivityType.OTHER, breinCategory, description, restCallback); } }
package org.wso2.carbon.identity.application.common.model.test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import javax.xml.stream.XMLStreamException; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.wso2.carbon.identity.application.common.model.ApplicationPermission; import org.wso2.carbon.identity.application.common.model.AuthenticationStep; import org.wso2.carbon.identity.application.common.model.Claim; import org.wso2.carbon.identity.application.common.model.ClaimConfig; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig; import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig; import org.wso2.carbon.identity.application.common.model.InboundProvisioningConfig; import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig; import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.LocalRole; import org.wso2.carbon.identity.application.common.model.OutboundProvisioningConfig; import org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig; import org.wso2.carbon.identity.application.common.model.Property; import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.RoleMapping; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.model.User; public class ServiceProviderBuild { public static void main(String args[]) throws XMLStreamException, IOException{ @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(new FileReader("/Users/prabath/svn/wso2/carbon/branches/platform/turing/components/identity/org.wso2.carbon.identity.application.common/4.2.0/src/test/java/org/wso2/carbon/identity/application/common/model/test/sp.xml")); String identityProviderString = ""; String line = null; while ((line = reader.readLine()) != null) { identityProviderString += line.trim(); } OMElement documentElementOM = AXIOMUtil.stringToOM(identityProviderString); ServiceProvider serviceProvider = ServiceProvider.build(documentElementOM); System.out.println("applicationID: " + serviceProvider.getApplicationID()); System.out.println("applicationName: " + serviceProvider.getApplicationName()); System.out.println("description: " + serviceProvider.getDescription()); System.out.println("inboundAuthenticationConfig: "); InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig(); System.out.println("\tinboundAuthenticationRequestConfigs: "); InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = inboundAuthenticationConfig.getInboundAuthenticationRequestConfigs(); for(int i=0; i<inboundAuthenticationRequestConfigs.length; i++){ System.out.println("\t\tinboundAuthKey: " + inboundAuthenticationRequestConfigs[i].getInboundAuthKey()); System.out.println("\t\tinboundAuthType: " + inboundAuthenticationRequestConfigs[i].getInboundAuthType()); System.out.println("\t\tproperties: "); Property[] properties = inboundAuthenticationRequestConfigs[i].getProperties(); for(int j=0; j<properties.length; j++){ System.out.println("\t\t\tname: " + properties[j].getName()); System.out.println("\t\t\tvalue: " + properties[j].getValue()); System.out.println("\t\t\tdefaultValue: " + properties[j].getDefaultValue()); System.out.println("\t\t\tdescription: " + properties[j].getDescription()); System.out.println("\t\t\tdisplayName" + properties[j].getDisplayName()); System.out.println(); } } System.out.println("localAndOutBoundAuthenticationConfig: "); LocalAndOutboundAuthenticationConfig localAndOutBoundAuthenticationConfig = serviceProvider.getLocalAndOutBoundAuthenticationConfig(); System.out.println("\tauthenticationType: " + localAndOutBoundAuthenticationConfig.getAuthenticationType()); System.out.println("\tauthenticationStepForSubject: "); AuthenticationStep authenticationStepForSubject = localAndOutBoundAuthenticationConfig.getAuthenticationStepForSubject(); System.out.println("\t\tstepOrder: " + authenticationStepForSubject.getStepOrder()); System.out.println("\t\tlocalAuthenticatorConfigs: "); LocalAuthenticatorConfig[] localAuthenticatorConfigs = authenticationStepForSubject.getLocalAuthenticatorConfigs(); for(int i=0; i<localAuthenticatorConfigs.length; i++){ System.out.println("\t\t\tname: " + localAuthenticatorConfigs[i].getName()); System.out.println("\t\t\tdisplayName: " + localAuthenticatorConfigs[i].getDisplayName()); System.out.println("\t\t\tproperties: "); Property[] properties = localAuthenticatorConfigs[i].getProperties(); for(int j=0; j<properties.length; j++){ System.out.println("\t\t\t\tname: " + properties[j].getName()); System.out.println("\t\t\t\tvalue: " + properties[j].getValue()); System.out.println("\t\t\t\tdefaultValue: " + properties[j].getDefaultValue()); System.out.println("\t\t\t\tdescription: " + properties[j].getDescription()); System.out.println("\t\t\t\tdisplayName" + properties[j].getDisplayName()); System.out.println(); } } System.out.println("\tauthenticationStepForAttributes: "); AuthenticationStep authenticationStepForAttributes = localAndOutBoundAuthenticationConfig.getAuthenticationStepForAttributes(); System.out.println("\t\tstepOrder: " + authenticationStepForAttributes.getStepOrder()); System.out.println("\t\tlocalAuthenticatorConfigs: "); localAuthenticatorConfigs = authenticationStepForAttributes.getLocalAuthenticatorConfigs(); for(int i=0; i<localAuthenticatorConfigs.length; i++){ System.out.println("\t\t\tname: " + localAuthenticatorConfigs[i].getName()); System.out.println("\t\t\tdisplayName: " + localAuthenticatorConfigs[i].getDisplayName()); System.out.println("\t\t\tproperties: "); Property[] properties = localAuthenticatorConfigs[i].getProperties(); for(int j=0; j<properties.length; j++){ System.out.println("\t\t\t\tname: " + properties[j].getName()); System.out.println("\t\t\t\tvalue: " + properties[j].getValue()); System.out.println("\t\t\t\tdefaultValue: " + properties[j].getDefaultValue()); System.out.println("\t\t\t\tdescription: " + properties[j].getDescription()); System.out.println("\t\t\t\tdisplayName" + properties[j].getDisplayName()); System.out.println(); } } System.out.println("\tauthenticationSteps: "); AuthenticationStep[] authenticationSteps = localAndOutBoundAuthenticationConfig.getAuthenticationSteps(); for(int k=0; k<authenticationSteps.length; k++){ System.out.println("\t\tstepOrder: " + authenticationSteps[k].getStepOrder()); System.out.println("\t\tlocalAuthenticatorConfigs: "); localAuthenticatorConfigs = authenticationSteps[k].getLocalAuthenticatorConfigs(); for(int i=0; i<localAuthenticatorConfigs.length; i++){ System.out.println("\t\t\tname: " + localAuthenticatorConfigs[i].getName()); System.out.println("\t\t\tdisplayName: " + localAuthenticatorConfigs[i].getDisplayName()); System.out.println("\t\t\tproperties: "); Property[] properties = localAuthenticatorConfigs[i].getProperties(); for(int j=0; j<properties.length; j++){ System.out.println("\t\t\t\tname: " + properties[j].getName()); System.out.println("\t\t\t\tvalue: " + properties[j].getValue()); System.out.println("\t\t\t\tdefaultValue: " + properties[j].getDefaultValue()); System.out.println("\t\t\t\tdescription: " + properties[j].getDescription()); System.out.println("\t\t\t\tdisplayName" + properties[j].getDisplayName()); System.out.println(); } } } System.out.println(); System.out.println("requestPathAuthenticatorConfigs: "); RequestPathAuthenticatorConfig[] requestPathAuthenticatorConfigs = serviceProvider.getRequestPathAuthenticatorConfigs(); for(int i=0; i<requestPathAuthenticatorConfigs.length;i++){ System.out.println("\tdisplayName: "+requestPathAuthenticatorConfigs[i].getDisplayName()); System.out.println("\tname: "+requestPathAuthenticatorConfigs[i].getName()); System.out.println("\t\tproperties: "); Property[] properties = localAuthenticatorConfigs[i].getProperties(); for(int j=0; j<properties.length; j++){ System.out.println("\t\t\tname: " + properties[j].getName()); System.out.println("\t\t\tvalue: " + properties[j].getValue()); System.out.println("\t\t\tdefaultValue: " + properties[j].getDefaultValue()); System.out.println("\t\t\tdescription: " + properties[j].getDescription()); System.out.println("\t\t\tdisplayName" + properties[j].getDisplayName()); System.out.println(); } } System.out.println("inboundProvisioningConfig: "); InboundProvisioningConfig inboundProvisioningConfig = serviceProvider.getInboundProvisioningConfig(); System.out.println("\tprovisioningUserStore"+inboundProvisioningConfig.getProvisioningUserStore()); System.out.println("\tprovisioningEnabled"+inboundProvisioningConfig.isProvisioningEnabled()); System.out.println("outboundProvisioningConfig: "); OutboundProvisioningConfig outboundProvisioningConfig = serviceProvider.getOutboundProvisioningConfig(); System.out.println("\tprovisioningIdentityProviders: "); System.out.println("\tprovisionByRoleList: "); String[] provisionByRoleList = outboundProvisioningConfig.getProvisionByRoleList(); for(int i=0; i<provisionByRoleList.length; i++){ System.out.println("\t\t"+provisionByRoleList[i]); } System.out.println("claimConfig: "); ClaimConfig claimConfig = serviceProvider.getClaimConfig(); System.out.println("\t"+ claimConfig.getRoleClaimURI()); System.out.println("\t"+ claimConfig.getUserClaimURI()); ClaimMapping[] claimMapping = claimConfig.getClaimMappings(); System.out.println("\tclaimMapping: "); for(int i=0; i<claimMapping.length; i++){ System.out.println("\t\tdefaultValue: "+ claimMapping[i].getDefaultValue()); Claim localClaim = claimMapping[i].getLocalClaim(); System.out.println("\t\tlocalClaim: "); System.out.println("\t\t\tclaimId: "+localClaim.getClaimId()); System.out.println("\t\t\tclaimUri: "+localClaim.getClaimUri()); Claim remoteClaim = claimMapping[i].getRemoteClaim(); System.out.println("\t\tremoteClaim: "); System.out.println("\t\t\tclaimId: "+remoteClaim.getClaimId()); System.out.println("\t\t\tclaimUri: "+remoteClaim.getClaimUri()); } System.out.println("permissionAndRoleConfig: "); PermissionsAndRoleConfig permissionsAndRoleConfig = serviceProvider.getPermissionAndRoleConfig(); System.out.println("\tpermissions:"); ApplicationPermission[] permissions = permissionsAndRoleConfig.getPermissions(); for(int i=0; i<permissions.length; i++){ System.out.println("\t\t"+permissions[i].getValue()); } System.out.println("\tideRoles:"); String[] idepRoles = permissionsAndRoleConfig.getIdpRoles(); for(int i=0; i<idepRoles.length; i++){ System.out.println("\t\t"+idepRoles[i]); } RoleMapping[] roleMappings = permissionsAndRoleConfig.getRoleMappings(); for(int i=0; i<roleMappings.length; i++){ LocalRole localRole = roleMappings[i].getLocalRole(); System.out.println("\t\tlocalRole: "); System.out.println("\t\t\tlocalRoleName: " + localRole.getLocalRoleName()); System.out.println("\t\t\tuserStoreId: " + localRole.getUserStoreId()); } } }
/* * Copyright 2016 Marvin Ramin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mtramin.reactiveawareness2; import android.content.Context; import android.location.Location; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.annotation.RequiresPermission; import com.google.android.gms.awareness.state.BeaconState; import com.google.android.gms.awareness.state.Weather; import com.google.android.gms.location.ActivityRecognitionResult; import com.google.android.gms.location.DetectedActivity; import com.google.android.gms.location.places.PlaceLikelihood; import com.google.android.gms.maps.model.LatLng; import java.util.ArrayList; import java.util.Collection; import java.util.List; import io.reactivex.Single; import static com.mtramin.reactiveawareness2.ApiKeyGuard.API_KEY_AWARENESS_API; import static com.mtramin.reactiveawareness2.ApiKeyGuard.API_KEY_BEACON_API; import static com.mtramin.reactiveawareness2.ApiKeyGuard.API_KEY_PLACES_API; import static com.mtramin.reactiveawareness2.ApiKeyGuard.guardWithApiKey; /** * Accessor class for Reactive Context values. All methods exposed query the Snapshot API to give * you more information about the users current context. * <p> * All context events are provided as {@link Single}s which will provide you with exactly the * current context state. */ public class ReactiveSnapshot { private final Context context; private ReactiveSnapshot(Context context) { this.context = context; } /** * Creates a new instance of ReactiveSnapshot to give you access to all Snapshot API calls. * @param context context to use, will default to your application context * @return instance of ReactiveSnapshot */ public static ReactiveSnapshot create(Context context) { return new ReactiveSnapshot(context.getApplicationContext()); } /** * Returns the current weather information at the devices current location * * @return Single event of weather information */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Weather> getWeather() { guardWithApiKey(context, API_KEY_AWARENESS_API); return WeatherSingle.create(context); } /** * Provides the current temperature at the devices current location * * @param temperatureUnit temperature unit to use * @return Single event of the current temperature */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Float> getTemperature(final int temperatureUnit) { return getWeather() .map(weather -> weather.getTemperature(temperatureUnit)); } /** * Provides the current feels-like temperature at the devices current location * * @param temperatureUnit temperature unit to use * @return Single event of the current feels-like temperature */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Float> getFeelsLikeTemperature(final int temperatureUnit) { return getWeather() .map(weather -> weather.getFeelsLikeTemperature(temperatureUnit)); } /** * Provides the current dew point at the devices current location * * @param temperatureUnit temperature unit to use * @return Single event of the current dew point */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Float> getDewPoint(final int temperatureUnit) { return getWeather() .map(weather -> weather.getDewPoint(temperatureUnit)); } /** * Provides the current humidity at the devices current location * * @return Single event of the current humidity */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Integer> getHumidity() { return getWeather() .map(Weather::getHumidity); } /** * Provides the current weather conditions at the devices current location * * @return Single event of the current weather conditions */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<List<Integer>> getWeatherConditions() { return getWeather() .map(Weather::getConditions) .map(conditions -> { List<Integer> list = new ArrayList<>(conditions.length); for (int condition : conditions) { list.add(condition); } return list; }); } /** * Provides the current location of the device * * @return Single event of the current location */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Location> getLocation() { guardWithApiKey(context, API_KEY_AWARENESS_API); return LocationSingle.create(context); } /** * Provides the current latitude/longitude of the device * * @return Single event of the current latitude/longitude */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<LatLng> getLatLng() { return getLocation() .map(location -> new LatLng(location.getLatitude(), location.getLongitude())); } /** * Provides the current speed of the device * * @return Single event of the current speed */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<Float> getSpeed() { return getLocation() .map(Location::getSpeed); } /** * Provides the current {@link ActivityRecognitionResult} of the device * * @return Single event of the current devices activity */ @RequiresPermission("com.google.android.gms.permission.ACTIVITY_RECOGNITION") public Single<ActivityRecognitionResult> getActivity() { guardWithApiKey(context, API_KEY_AWARENESS_API); return ActivitySingle.create(context); } /** * Provides the current most probable {@link DetectedActivity} of the device * * @return Single event of the most probable activity */ @RequiresPermission("com.google.android.gms.permission.ACTIVITY_RECOGNITION") public Single<DetectedActivity> getMostProbableActivity() { return getActivity() .map(ActivityRecognitionResult::getMostProbableActivity); } /** * Provides the current most probable {@link DetectedActivity} of the device which has at least * the given probability. Should no activity reach this minimum probability, {@code null} will * be emitted. * <p> * <b>Be sure to check the result for null!</b> * * @return Single event of the most probable activity */ @RequiresPermission("com.google.android.gms.permission.ACTIVITY_RECOGNITION") public Single<DetectedActivity> getMostProbableActivity(int minimumProbability) { return getActivity() .map(activity -> { DetectedActivity mostProbableActivity = activity.getMostProbableActivity(); if (activity.getActivityConfidence(mostProbableActivity.getType()) < minimumProbability) { return null; } return mostProbableActivity; }); } /** * Provides the current probable {@link DetectedActivity}s of the device * * @return Single event of the most probable activities */ @RequiresPermission("com.google.android.gms.permission.ACTIVITY_RECOGNITION") public Single<List<DetectedActivity>> getProbableActivities() { return getActivity() .map(ActivityRecognitionResult::getProbableActivities); } /** * Provides the current probable {@link DetectedActivity}s of the device which have at least * the given probability. Should no activity reach this minimum probability, the resulting list * will be empty. * * @param minimumProbability minimum probabilities of the activities * @return Single event of the most probable activities */ @RequiresPermission("com.google.android.gms.permission.ACTIVITY_RECOGNITION") public Single<List<DetectedActivity>> getProbableActivities(int minimumProbability) { return getActivity() .map(activity -> { List<DetectedActivity> probableActivities = activity.getProbableActivities(); List<DetectedActivity> matchingActivities = new ArrayList<>(probableActivities.size()); for (DetectedActivity probableActivity : probableActivities) { if (activity.getActivityConfidence(probableActivity.getType()) >= minimumProbability) { matchingActivities.add(probableActivity); } } return matchingActivities; }); } /** * Provides the current state of the headphones. * * @return Single event of {@code true} if the headphones are currently plugged in */ public Single<Boolean> headphonesPluggedIn() { guardWithApiKey(context, API_KEY_AWARENESS_API); return HeadphoneSingle.create(context); } /** * Provides the currently nearby places to the current device location. * * @return Single event of the currently nearby places */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") public Single<List<PlaceLikelihood>> getNearbyPlaces() { guardWithApiKey(context, API_KEY_AWARENESS_API); guardWithApiKey(context, API_KEY_PLACES_API); return NearbySingle.create(context); } /** * Provides the currently nearby beacons to the current device locations. * * @param typeFilters Beacon TypeFilters to filter for * @return Single event of matching nearby beacons */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public Single<List<BeaconState.BeaconInfo>> getBeacons(BeaconState.TypeFilter... typeFilters) { guardWithApiKey(context, API_KEY_AWARENESS_API); guardWithApiKey(context, API_KEY_BEACON_API); return BeaconSingle.create(context, typeFilters); } /** * Provides the currently nearby beacons to the current device locations. * * @param typeFilters Beacon TypeFilters to filter for * @return Single event of matching nearby beacons */ @RequiresPermission("android.permission.ACCESS_FINE_LOCATION") @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public Single<List<BeaconState.BeaconInfo>> getBeacons(Collection<BeaconState.TypeFilter> typeFilters) { guardWithApiKey(context, API_KEY_AWARENESS_API); guardWithApiKey(context, API_KEY_BEACON_API); return BeaconSingle.create(context, typeFilters); } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.dmn.engine.test.deployment; import static org.assertj.core.api.Assertions.assertThat; import java.io.InputStream; import java.util.List; import org.flowable.dmn.api.DecisionExecutionAuditContainer; import org.flowable.dmn.api.DecisionTypes; import org.flowable.dmn.api.DmnDecision; import org.flowable.dmn.engine.impl.persistence.entity.DecisionEntity; import org.flowable.dmn.engine.impl.persistence.entity.DmnDeploymentEntity; import org.flowable.dmn.engine.test.AbstractFlowableDmnTest; import org.flowable.dmn.engine.test.DmnDeployment; import org.h2.util.IOUtils; import org.junit.Test; public class DeploymentTest extends AbstractFlowableDmnTest { @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") public void deploySingleDecision() { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); assertThat(decision.getDecisionType()).isEqualTo(DecisionTypes.DECISION_TABLE); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") public void deploySingleDecisionTableDecision() { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .decisionType(DecisionTypes.DECISION_TABLE) .singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") public void deploySingleDecisionTableDecisionQueryWrongType() { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .decisionTypeLike("%service") .singleResult(); assertThat(decision).isNull(); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_conclusions_DMN12.dmn") public void deploySingleDecisionDMN12() { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") public void deploySingleDecisionAndValidateCache() { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision.getId())).isTrue(); dmnEngineConfiguration.getDeploymentManager().getDecisionCache().clear(); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision.getId())).isFalse(); decision = repositoryService.getDecision(decision.getId()); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); assertThat(decision.getDecisionType()).isEqualTo(DecisionTypes.DECISION_TABLE); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") public void deploySingleDecisionAndValidateVersioning() { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .singleResult(); assertThat(decision.getVersion()).isEqualTo(1); repositoryService.createDeployment().name("secondDeployment") .addClasspathResource("org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") .deploy(); decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .singleResult(); assertThat(decision.getVersion()).isEqualTo(2); } @Test public void deploySingleDecisionInTenantAndValidateCache() throws Exception { repositoryService.createDeployment().name("secondDeployment") .addClasspathResource("org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") .tenantId("testTenant") .deploy(); DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .decisionTenantId("testTenant") .singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); assertThat(decision.getTenantId()).isEqualTo("testTenant"); assertThat(decision.getVersion()).isEqualTo(1); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision.getId())).isTrue(); dmnEngineConfiguration.getDeploymentManager().getDecisionCache().clear(); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision.getId())).isFalse(); decision = repositoryService.getDecision(decision.getId()); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); deleteDeployments(); } @Test public void deploySingleDecisionInTenantAndValidateVersioning() throws Exception { repositoryService.createDeployment().name("secondDeployment") .addClasspathResource("org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") .tenantId("testTenant") .deploy(); DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .decisionTenantId("testTenant") .singleResult(); assertThat(decision.getVersion()).isEqualTo(1); repositoryService.createDeployment().name("secondDeployment") .addClasspathResource("org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") .tenantId("testTenant") .deploy(); decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .decisionTenantId("testTenant") .singleResult(); assertThat(decision.getVersion()).isEqualTo(2); deleteDeployments(); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/multiple_decisions.dmn") public void deployMultipleDecisions() throws Exception { DmnDecision decision = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision") .singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision.getId())).isTrue(); dmnEngineConfiguration.getDeploymentManager().getDecisionCache().clear(); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision.getId())).isFalse(); decision = repositoryService.getDecision(decision.getId()); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); DmnDecision decision2 = repositoryService.createDecisionQuery() .latestVersion() .decisionKey("decision2") .singleResult(); assertThat(decision2).isNotNull(); assertThat(decision2.getKey()).isEqualTo("decision2"); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision2.getId())).isTrue(); dmnEngineConfiguration.getDeploymentManager().getDecisionCache().clear(); assertThat(dmnEngineConfiguration.getDeploymentManager().getDecisionCache().contains(decision2.getId())).isFalse(); decision2 = repositoryService.getDecision(decision2.getId()); assertThat(decision2).isNotNull(); assertThat(decision2.getKey()).isEqualTo("decision2"); } @Test public void deployWithCategory() throws Exception { repositoryService.createDeployment().name("secondDeployment") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .tenantId("testTenant") .category("TEST_DEPLOYMENT_CATEGORY") .deploy(); org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery().deploymentCategory("TEST_DEPLOYMENT_CATEGORY").singleResult(); assertThat(deployment).isNotNull(); DmnDecision decisionTable = repositoryService.createDecisionQuery().decisionKey("decision").singleResult(); assertThat(decisionTable).isNotNull(); repositoryService.setDecisionCategory(decisionTable.getId(), "TEST_DECISION_TABLE_CATEGORY"); DmnDecision decisionWithCategory = repositoryService.createDecisionQuery().decisionCategory("TEST_DECISION_TABLE_CATEGORY").singleResult(); assertThat(decisionWithCategory).isNotNull(); deleteDeployments(); } @Test public void multipleSameDeployments() throws Exception { repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .enableDuplicateFiltering() .deploy(); org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .singleResult(); assertThat(deployment).isNotNull(); List<DmnDecision> decisions = repositoryService.createDecisionQuery() .decisionKey("decision") .list(); assertThat(decisions).hasSize(1); repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .enableDuplicateFiltering() .deploy(); List<org.flowable.dmn.api.DmnDeployment> deployments = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .list(); assertThat(deployments).hasSize(1); decisions = repositoryService.createDecisionQuery() .decisionKey("decision") .list(); assertThat(decisions).hasSize(1); deleteDeployments(); } @Test public void multipleDeployments() throws Exception { repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .enableDuplicateFiltering() .deploy(); org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .singleResult(); assertThat(deployment).isNotNull(); List<DmnDecision> decisions = repositoryService.createDecisionQuery() .decisionKey("decision") .list(); assertThat(decisions).hasSize(1); repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple2.dmn") .enableDuplicateFiltering() .deploy(); List<org.flowable.dmn.api.DmnDeployment> deployments = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .list(); assertThat(deployments).hasSize(2); decisions = repositoryService.createDecisionQuery() .decisionKey("anotherDecision") .list(); assertThat(decisions).hasSize(1); repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple2.dmn") .enableDuplicateFiltering() .deploy(); deployments = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .list(); assertThat(deployments).hasSize(2); decisions = repositoryService.createDecisionQuery() .decisionKey("anotherDecision") .list(); assertThat(decisions).hasSize(1); deleteDeployments(); } @Test public void multipleSameDeploymentsInTenant() throws Exception { repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .tenantId("myTenant") .enableDuplicateFiltering() .deploy(); org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .deploymentTenantId("myTenant") .singleResult(); assertThat(deployment).isNotNull(); List<DmnDecision> decisions = repositoryService.createDecisionQuery() .decisionKey("decision") .decisionTenantId("myTenant") .list(); assertThat(decisions).hasSize(1); repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .tenantId("myTenant") .enableDuplicateFiltering() .deploy(); List<org.flowable.dmn.api.DmnDeployment> deployments = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .deploymentTenantId("myTenant") .list(); assertThat(deployments).hasSize(1); decisions = repositoryService.createDecisionQuery() .decisionKey("decision") .decisionTenantId("myTenant") .list(); assertThat(decisions).hasSize(1); deleteDeployments(); } @Test public void multipleDeploymentsInTenant() throws Exception { repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .tenantId("myTenant") .enableDuplicateFiltering() .deploy(); org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .deploymentTenantId("myTenant") .singleResult(); assertThat(deployment).isNotNull(); List<DmnDecision> decisions = repositoryService.createDecisionQuery() .decisionKey("decision") .decisionTenantId("myTenant") .list(); assertThat(decisions).hasSize(1); repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple2.dmn") .tenantId("myTenant") .enableDuplicateFiltering() .deploy(); List<org.flowable.dmn.api.DmnDeployment> deployments = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .deploymentTenantId("myTenant") .list(); assertThat(deployments).hasSize(2); decisions = repositoryService.createDecisionQuery() .decisionKey("anotherDecision") .decisionTenantId("myTenant") .list(); assertThat(decisions).hasSize(1); repositoryService.createDeployment() .name("deploymentA") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple2.dmn") .tenantId("myTenant") .enableDuplicateFiltering() .deploy(); deployments = repositoryService.createDeploymentQuery() .deploymentName("deploymentA") .deploymentTenantId("myTenant") .list(); assertThat(deployments).hasSize(2); decisions = repositoryService.createDecisionQuery() .decisionKey("anotherDecision") .decisionTenantId("myTenant") .list(); assertThat(decisions).hasSize(1); deleteDeployments(); } @Test public void deploySingleDecisionWithParentDeploymentId() { org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeployment() .addClasspathResource("org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") .parentDeploymentId("someDeploymentId") .deploy(); org.flowable.dmn.api.DmnDeployment newDeployment = repositoryService.createDeployment() .addClasspathResource("org/flowable/dmn/engine/test/deployment/multiple_conclusions.dmn") .deploy(); try { DmnDecision decision = repositoryService.createDecisionQuery().deploymentId(deployment.getId()).singleResult(); assertThat(decision).isNotNull(); assertThat(decision.getKey()).isEqualTo("decision"); assertThat(decision.getVersion()).isEqualTo(1); DmnDecision newDecision = repositoryService.createDecisionQuery().deploymentId(newDeployment.getId()).singleResult(); assertThat(newDecision).isNotNull(); assertThat(newDecision.getKey()).isEqualTo("decision"); assertThat(newDecision.getVersion()).isEqualTo(2); DecisionExecutionAuditContainer auditContainer = ruleService.createExecuteDecisionBuilder() .decisionKey("decision") .parentDeploymentId("someDeploymentId") .executeWithAuditTrail(); assertThat(auditContainer.getDecisionKey()).isEqualTo("decision"); assertThat(auditContainer.getDecisionVersion()).isEqualTo(1); dmnEngineConfiguration.setAlwaysLookupLatestDefinitionVersion(true); auditContainer = ruleService.createExecuteDecisionBuilder().decisionKey("decision").executeWithAuditTrail(); assertThat(auditContainer.getDecisionKey()).isEqualTo("decision"); assertThat(auditContainer.getDecisionVersion()).isEqualTo(2); } finally { dmnEngineConfiguration.setAlwaysLookupLatestDefinitionVersion(false); repositoryService.deleteDeployment(deployment.getId()); repositoryService.deleteDeployment(newDeployment.getId()); } } @Test @DmnDeployment public void testNativeQuery() { org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery().singleResult(); assertThat(deployment).isNotNull(); long count = repositoryService.createNativeDeploymentQuery() .sql("SELECT count(*) FROM " + managementService.getTableName(DmnDeploymentEntity.class) + " D1, " + managementService.getTableName(DecisionEntity.class) + " D2 " + "WHERE D1.ID_ = D2.DEPLOYMENT_ID_ " + "AND D1.ID_ = #{deploymentId}") .parameter("deploymentId", deployment.getId()) .count(); assertThat(count).isEqualTo(2); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/chapter11.dmn") public void testDecisionServicesDeployment() { org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery().singleResult(); assertThat(deployment).isNotNull(); List<DmnDecision> decisionServices = repositoryService.createDecisionQuery().deploymentId(deployment.getId()).list(); assertThat(decisionServices).hasSize(2); assertThat(decisionServices) .extracting(DmnDecision::getDecisionType) .containsExactly("decision_service", "decision_service"); List<DmnDecision> decisionServices2 = repositoryService.createDecisionQuery().decisionType(DecisionTypes.DECISION_SERVICE).list(); assertThat(decisionServices2).hasSize(2); List<DmnDecision> decisionTables = repositoryService.createDecisionQuery().decisionType(DecisionTypes.DECISION_TABLE).list(); assertThat(decisionTables).isEmpty(); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/chapter11_dmn13.dmn") public void testDecisionServicesDeploymentDMN13() { org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery().singleResult(); assertThat(deployment).isNotNull(); List<String> resourceNames = repositoryService.getDeploymentResourceNames(deployment.getId()); // no diagram image because of missing DI info for some decision services assertThat(resourceNames).hasSize(1); List<DmnDecision> decisionServices = repositoryService.createDecisionQuery().deploymentId(deployment.getId()).list(); assertThat(decisionServices).hasSize(10); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/decision_service_1.dmn") public void testDecisionServicesDI() { org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery().singleResult(); assertThat(deployment).isNotNull(); List<String> resourceNames = repositoryService.getDeploymentResourceNames(deployment.getId()); assertThat(resourceNames).hasSize(2); String resourceName = "org/flowable/dmn/engine/test/deployment/decision_service_1.dmn"; String diagramResourceName = "org/flowable/dmn/engine/test/deployment/decision_service_1.decisionServiceOne.png"; assertThat(resourceNames).contains(resourceName, diagramResourceName); InputStream inputStream = repositoryService.getResourceAsStream(deployment.getId(), resourceName); assertThat(inputStream).isNotNull(); IOUtils.closeSilently(inputStream); InputStream diagramInputStream = repositoryService.getResourceAsStream(deployment.getId(), diagramResourceName); assertThat(diagramInputStream).isNotNull(); IOUtils.closeSilently(diagramInputStream); DmnDecision decision = repositoryService.createDecisionQuery().deploymentId(deployment.getId()).singleResult(); InputStream caseDiagramInputStream = repositoryService.getDecisionRequirementsDiagram(decision.getId()); assertThat(caseDiagramInputStream).isNotNull(); IOUtils.closeSilently(caseDiagramInputStream); } @Test @DmnDeployment(resources = "org/flowable/dmn/engine/test/runtime/decisionServiceMultipleOutputDecisions.dmn") public void testExportedDecisionServicesDeployment() { org.flowable.dmn.api.DmnDeployment deployment = repositoryService.createDeploymentQuery().singleResult(); assertThat(deployment).isNotNull(); List<DmnDecision> decisionServices = repositoryService.createDecisionQuery().deploymentId(deployment.getId()).list(); assertThat(decisionServices).hasSize(1); assertThat(decisionServices.get(0).getDecisionType()).isEqualTo(DecisionTypes.DECISION_SERVICE); } @Test @DmnDeployment public void testDeployWithXmlSuffix() { assertThat(repositoryService.createDeploymentQuery().count()).isEqualTo(1); } @Test public void testMixedDeployment() throws Exception { repositoryService.createDeployment().name("mixedDeployment") .addClasspathResource("org/flowable/dmn/engine/test/deployment/simple.dmn") .addClasspathResource("org/flowable/dmn/engine/test/deployment/chapter11.dmn") .tenantId("testTenant") .deploy(); DmnDecision decisionTable = repositoryService.createDecisionQuery().decisionType(DecisionTypes.DECISION_TABLE).singleResult(); List<DmnDecision> decisionService = repositoryService.createDecisionQuery().decisionType(DecisionTypes.DECISION_SERVICE).list(); assertThat(decisionTable.getKey()).isEqualTo("decision"); assertThat(decisionService).extracting(DmnDecision::getKey) .containsExactly("_7befd964-eefa-4d8f-908d-8f6ad8d22c67", "_4d91e3a5-acec-4254-81e4-8535a1d336ee"); deleteDeployments(); } protected void deleteDeployments() { List<org.flowable.dmn.api.DmnDeployment> deployments = repositoryService.createDeploymentQuery().list(); for (org.flowable.dmn.api.DmnDeployment deployment : deployments) { repositoryService.deleteDeployment(deployment.getId()); } } }
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.dmn.feel.util; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.Period; import java.time.ZonedDateTime; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.kie.dmn.feel.runtime.Range; public final class TypeUtil { private static final long SECONDS_IN_A_MINUTE = 60; private static final long SECONDS_IN_AN_HOUR = 60 * SECONDS_IN_A_MINUTE; private static final long SECONDS_IN_A_DAY = 24 * SECONDS_IN_AN_HOUR; private static final long NANOSECONDS_PER_SECOND = 1000000000; public static boolean isCollectionTypeHomogenous(final Collection collection) { if (collection.isEmpty()) { return true; } else { return isCollectionTypeHomogenous(collection, collection.iterator().next().getClass()); } } public static boolean isCollectionTypeHomogenous(final Collection collection, final Class expectedType) { for (final Object object : collection) { if (object == null) { continue; } else if (!expectedType.isAssignableFrom(object.getClass())) { return false; } } return true; } public static String formatValue(final Object val, final boolean wrapForCodeUsage) { if (val instanceof String) { return formatString(val.toString(), wrapForCodeUsage); } else if (val instanceof LocalDate) { return formatDate((LocalDate) val, wrapForCodeUsage); } else if (val instanceof LocalTime || val instanceof OffsetTime) { return formatTimeString(val.toString(), wrapForCodeUsage); } else if (val instanceof LocalDateTime || val instanceof OffsetDateTime || val instanceof ZonedDateTime) { return formatDateTimeString(val.toString(), wrapForCodeUsage); } else if (val instanceof Duration) { return formatDuration((Duration) val, wrapForCodeUsage); } else if (val instanceof Period) { return formatPeriod((Period) val, wrapForCodeUsage); } else if (val instanceof List) { return formatList((List) val, wrapForCodeUsage); } else if (val instanceof Range) { return formatRange((Range) val, wrapForCodeUsage); } else if (val instanceof Map) { return formatContext((Map) val, wrapForCodeUsage); } else { return String.valueOf(val); } } public static String formatDateTimeString(final String dateTimeString, final boolean wrapForCodeUsage) { if (wrapForCodeUsage) { return "date and time( \"" + dateTimeString + "\" )"; } else { return dateTimeString; } } public static String formatTimeString(final String timeString, final boolean wrapForCodeUsage) { if (wrapForCodeUsage) { return "time( \"" + timeString + "\" )"; } else { return timeString; } } public static String formatDate(final LocalDate date, final boolean wrapForCodeUsage) { if (wrapForCodeUsage) { return "date( \"" + date.toString() + "\" )"; } else { return date.toString(); } } public static String formatString(final String value, final boolean wrapForCodeUsage) { if (wrapForCodeUsage) { return "\"" + value + "\""; } else { return value; } } public static String formatList(final List list, final boolean wrapDateTimeValuesInFunctions) { final StringBuilder sb = new StringBuilder(); sb.append("[ "); int count = 0; for (final Object val : list) { if (count > 0) { sb.append(", "); } sb.append(formatValue(val, wrapDateTimeValuesInFunctions)); count++; } if (!list.isEmpty()) { sb.append(" "); } sb.append("]"); return sb.toString(); } public static String formatContext(final Map context, final boolean wrapDateTimeValuesInFunctions) { final StringBuilder sb = new StringBuilder(); sb.append("{ "); int count = 0; for (final Map.Entry<Object, Object> val : (Set<Map.Entry<Object, Object>>) context.entrySet()) { if (count > 0) { sb.append(", "); } // keys should always be strings, so do not call recursivelly to avoid the " sb.append(val.getKey()); sb.append(" : "); sb.append(formatValue(val.getValue(), wrapDateTimeValuesInFunctions)); count++; } if (!context.isEmpty()) { sb.append(" "); } sb.append("}"); return sb.toString(); } public static String formatRange(final Range val, final boolean wrapDateTimeValuesInFunctions) { final StringBuilder sb = new StringBuilder(); sb.append(val.getLowBoundary() == Range.RangeBoundary.OPEN ? "( " : "[ "); sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); sb.append(" .. "); sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); sb.append(val.getHighBoundary() == Range.RangeBoundary.OPEN ? " )" : " ]"); return sb.toString(); } public static String formatPeriod(final Period period, final boolean wrapInDurationFunction) { final long totalMonths = period.toTotalMonths(); if (totalMonths == 0) { if (wrapInDurationFunction) { return "duration( \"P0M\" )"; } else { return "P0M"; } } final StringBuilder sb = new StringBuilder(); if (wrapInDurationFunction) { sb.append("duration( \""); } if (totalMonths < 0) { sb.append("-P"); } else { sb.append('P'); } final long years = Math.abs(totalMonths / 12); if (years != 0) { sb.append(years).append('Y'); } final long months = Math.abs(totalMonths % 12); if (months != 0) { sb.append(months).append('M'); } if (wrapInDurationFunction) { sb.append("\" )"); } return sb.toString(); } public static String formatDuration(final Duration duration, final boolean wrapInDurationFunction) { if (duration.getSeconds() == 0 && duration.getNano() == 0) { if (wrapInDurationFunction) { return "duration( \"PT0S\" )"; } else { return "PT0S"; } } final long days = duration.getSeconds() / SECONDS_IN_A_DAY; final long hours = (duration.getSeconds() % SECONDS_IN_A_DAY) / SECONDS_IN_AN_HOUR; final long minutes = (duration.getSeconds() % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE; final long seconds = duration.getSeconds() % SECONDS_IN_A_MINUTE; final StringBuilder sb = new StringBuilder(); if (wrapInDurationFunction) { sb.append("duration( \""); } if (duration.isNegative()) { sb.append("-"); } sb.append("P"); if (days != 0) { appendToDurationString(sb, days, "D"); } if (hours != 0 || minutes != 0 || seconds != 0 || duration.getNano() != 0) { sb.append("T"); if (hours != 0) { appendToDurationString(sb, hours, "H"); } if (minutes != 0) { appendToDurationString(sb, minutes, "M"); } if (seconds != 0 || duration.getNano() != 0) { appendSecondsToDurationString(sb, seconds, duration.getNano()); } } if (wrapInDurationFunction) { sb.append("\" )"); } return sb.toString(); } private static void appendToDurationString(final StringBuilder sb, final long days, final String timeSegmentChar) { sb.append(Math.abs(days)); sb.append(timeSegmentChar); } private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds, final long nanoseconds) { if (seconds < 0 && nanoseconds > 0) { if (seconds == -1) { sb.append("0"); } else { sb.append(Math.abs(seconds + 1)); } } else { sb.append(Math.abs(seconds)); } if (nanoseconds > 0) { final int pos = sb.length(); if (seconds < 0) { sb.append(2 * NANOSECONDS_PER_SECOND - nanoseconds); } else { sb.append(nanoseconds + NANOSECONDS_PER_SECOND); } eliminateTrailingZeros(sb); sb.setCharAt(pos, '.'); } sb.append('S'); } private static void eliminateTrailingZeros(final StringBuilder sb) { while (sb.charAt(sb.length() - 1) == '0') { // eliminates trailing zeros in the nanoseconds sb.setLength(sb.length() - 1); } } private TypeUtil() { // Not allowed for util classes. } }
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.instruction; import proguard.classfile.*; import proguard.classfile.attribute.CodeAttribute; import proguard.classfile.instruction.visitor.InstructionVisitor; /** * This Instruction represents an instruction that refers to a variable on the * local variable stack. * * @author Eric Lafortune */ public class VariableInstruction extends Instruction { public boolean wide; public int variableIndex; public int constant; /** * Creates an uninitialized VariableInstruction. */ public VariableInstruction() {} public VariableInstruction(boolean wide) { this.wide = wide; } public VariableInstruction(byte opcode) { this(opcode, embeddedVariable(opcode), 0); } public VariableInstruction(byte opcode, int variableIndex) { this(opcode, variableIndex, 0); } public VariableInstruction(byte opcode, int variableIndex, int constant) { this.opcode = opcode; this.variableIndex = variableIndex; this.constant = constant; this.wide = requiredVariableIndexSize() > 1 || requiredConstantSize() > 1; } /** * Copies the given instruction into this instruction. * @param variableInstruction the instruction to be copied. * @return this instruction. */ public VariableInstruction copy(VariableInstruction variableInstruction) { this.opcode = variableInstruction.opcode; this.variableIndex = variableInstruction.variableIndex; this.constant = variableInstruction.constant; this.wide = variableInstruction.wide; return this; } /** * Return the embedded variable of the given opcode, or 0 if the opcode * doesn't have one. */ private static int embeddedVariable(byte opcode) { switch (opcode) { case InstructionConstants.OP_ILOAD_1: case InstructionConstants.OP_LLOAD_1: case InstructionConstants.OP_FLOAD_1: case InstructionConstants.OP_DLOAD_1: case InstructionConstants.OP_ALOAD_1: case InstructionConstants.OP_ISTORE_1: case InstructionConstants.OP_LSTORE_1: case InstructionConstants.OP_FSTORE_1: case InstructionConstants.OP_DSTORE_1: case InstructionConstants.OP_ASTORE_1: return 1; case InstructionConstants.OP_ILOAD_2: case InstructionConstants.OP_LLOAD_2: case InstructionConstants.OP_FLOAD_2: case InstructionConstants.OP_DLOAD_2: case InstructionConstants.OP_ALOAD_2: case InstructionConstants.OP_ISTORE_2: case InstructionConstants.OP_LSTORE_2: case InstructionConstants.OP_FSTORE_2: case InstructionConstants.OP_DSTORE_2: case InstructionConstants.OP_ASTORE_2: return 2; case InstructionConstants.OP_ILOAD_3: case InstructionConstants.OP_LLOAD_3: case InstructionConstants.OP_FLOAD_3: case InstructionConstants.OP_DLOAD_3: case InstructionConstants.OP_ALOAD_3: case InstructionConstants.OP_ISTORE_3: case InstructionConstants.OP_LSTORE_3: case InstructionConstants.OP_FSTORE_3: case InstructionConstants.OP_DSTORE_3: case InstructionConstants.OP_ASTORE_3: return 3; default: return 0; } } /** * Returns whether this instruction stores the value of a variable. * The value is false for the ret instruction, but true for the iinc * instruction. */ public boolean isStore() { // A store instruction can be recognized as follows. Note that this // excludes the ret instruction, which has a negative opcode. return opcode >= InstructionConstants.OP_ISTORE || opcode == InstructionConstants.OP_IINC; } /** * Returns whether this instruction loads the value of a variable. * The value is true for the ret instruction and for the iinc * instruction. */ public boolean isLoad() { // A load instruction can be recognized as follows. Note that this // includes the ret instruction, which has a negative opcode. return opcode < InstructionConstants.OP_ISTORE; } // Implementations for Instruction. public byte canonicalOpcode() { // Remove the _0, _1, _2, _3 extension, if any. switch (opcode) { case InstructionConstants.OP_ILOAD_0: case InstructionConstants.OP_ILOAD_1: case InstructionConstants.OP_ILOAD_2: case InstructionConstants.OP_ILOAD_3: return InstructionConstants.OP_ILOAD; case InstructionConstants.OP_LLOAD_0: case InstructionConstants.OP_LLOAD_1: case InstructionConstants.OP_LLOAD_2: case InstructionConstants.OP_LLOAD_3: return InstructionConstants.OP_LLOAD; case InstructionConstants.OP_FLOAD_0: case InstructionConstants.OP_FLOAD_1: case InstructionConstants.OP_FLOAD_2: case InstructionConstants.OP_FLOAD_3: return InstructionConstants.OP_FLOAD; case InstructionConstants.OP_DLOAD_0: case InstructionConstants.OP_DLOAD_1: case InstructionConstants.OP_DLOAD_2: case InstructionConstants.OP_DLOAD_3: return InstructionConstants.OP_DLOAD; case InstructionConstants.OP_ALOAD_0: case InstructionConstants.OP_ALOAD_1: case InstructionConstants.OP_ALOAD_2: case InstructionConstants.OP_ALOAD_3: return InstructionConstants.OP_ALOAD; case InstructionConstants.OP_ISTORE_0: case InstructionConstants.OP_ISTORE_1: case InstructionConstants.OP_ISTORE_2: case InstructionConstants.OP_ISTORE_3: return InstructionConstants.OP_ISTORE; case InstructionConstants.OP_LSTORE_0: case InstructionConstants.OP_LSTORE_1: case InstructionConstants.OP_LSTORE_2: case InstructionConstants.OP_LSTORE_3: return InstructionConstants.OP_LSTORE; case InstructionConstants.OP_FSTORE_0: case InstructionConstants.OP_FSTORE_1: case InstructionConstants.OP_FSTORE_2: case InstructionConstants.OP_FSTORE_3: return InstructionConstants.OP_FSTORE; case InstructionConstants.OP_DSTORE_0: case InstructionConstants.OP_DSTORE_1: case InstructionConstants.OP_DSTORE_2: case InstructionConstants.OP_DSTORE_3: return InstructionConstants.OP_DSTORE; case InstructionConstants.OP_ASTORE_0: case InstructionConstants.OP_ASTORE_1: case InstructionConstants.OP_ASTORE_2: case InstructionConstants.OP_ASTORE_3: return InstructionConstants.OP_ASTORE; default: return opcode; } } public Instruction shrink() { opcode = canonicalOpcode(); // Is this instruction pointing to a variable with index from 0 to 3? if (variableIndex <= 3) { switch (opcode) { case InstructionConstants.OP_ILOAD: opcode = (byte)(InstructionConstants.OP_ILOAD_0 + variableIndex); break; case InstructionConstants.OP_LLOAD: opcode = (byte)(InstructionConstants.OP_LLOAD_0 + variableIndex); break; case InstructionConstants.OP_FLOAD: opcode = (byte)(InstructionConstants.OP_FLOAD_0 + variableIndex); break; case InstructionConstants.OP_DLOAD: opcode = (byte)(InstructionConstants.OP_DLOAD_0 + variableIndex); break; case InstructionConstants.OP_ALOAD: opcode = (byte)(InstructionConstants.OP_ALOAD_0 + variableIndex); break; case InstructionConstants.OP_ISTORE: opcode = (byte)(InstructionConstants.OP_ISTORE_0 + variableIndex); break; case InstructionConstants.OP_LSTORE: opcode = (byte)(InstructionConstants.OP_LSTORE_0 + variableIndex); break; case InstructionConstants.OP_FSTORE: opcode = (byte)(InstructionConstants.OP_FSTORE_0 + variableIndex); break; case InstructionConstants.OP_DSTORE: opcode = (byte)(InstructionConstants.OP_DSTORE_0 + variableIndex); break; case InstructionConstants.OP_ASTORE: opcode = (byte)(InstructionConstants.OP_ASTORE_0 + variableIndex); break; } } // Only make the instruction wide if necessary. wide = requiredVariableIndexSize() > 1 || requiredConstantSize() > 1; return this; } protected boolean isWide() { return wide; } protected void readInfo(byte[] code, int offset) { int variableIndexSize = variableIndexSize(); int constantSize = constantSize(); // Also initialize embedded variable indexes. if (variableIndexSize == 0) { // An embedded variable index can be decoded as follows. variableIndex = opcode < InstructionConstants.OP_ISTORE_0 ? (opcode - InstructionConstants.OP_ILOAD_0 ) & 3 : (opcode - InstructionConstants.OP_ISTORE_0) & 3; } else { variableIndex = readValue(code, offset, variableIndexSize); offset += variableIndexSize; } constant = readSignedValue(code, offset, constantSize); } protected void writeInfo(byte[] code, int offset) { int variableIndexSize = variableIndexSize(); int constantSize = constantSize(); if (requiredVariableIndexSize() > variableIndexSize) { throw new IllegalArgumentException("Instruction has invalid variable index size ("+this.toString(offset)+")"); } if (requiredConstantSize() > constantSize) { throw new IllegalArgumentException("Instruction has invalid constant size ("+this.toString(offset)+")"); } writeValue(code, offset, variableIndex, variableIndexSize); offset += variableIndexSize; writeSignedValue(code, offset, constant, constantSize); } public int length(int offset) { return (wide ? 2 : 1) + variableIndexSize() + constantSize(); } public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, InstructionVisitor instructionVisitor) { instructionVisitor.visitVariableInstruction(clazz, method, codeAttribute, offset, this); } // Implementations for Object. public String toString() { return getName() + (wide ? "_w" : "") + " v"+variableIndex + (constantSize() > 0 ? ", "+constant : ""); } // Small utility methods. /** * Returns the variable index size for this instruction. */ private int variableIndexSize() { return (opcode >= InstructionConstants.OP_ILOAD_0 && opcode <= InstructionConstants.OP_ALOAD_3) || (opcode >= InstructionConstants.OP_ISTORE_0 && opcode <= InstructionConstants.OP_ASTORE_3) ? 0 : wide ? 2 : 1; } /** * Computes the required variable index size for this instruction's variable * index. */ private int requiredVariableIndexSize() { return (variableIndex & 0x3) == variableIndex ? 0 : (variableIndex & 0xff) == variableIndex ? 1 : (variableIndex & 0xffff) == variableIndex ? 2 : 4; } /** * Returns the constant size for this instruction. */ private int constantSize() { return opcode != InstructionConstants.OP_IINC ? 0 : wide ? 2 : 1; } /** * Computes the required constant size for this instruction's constant. */ private int requiredConstantSize() { return opcode != InstructionConstants.OP_IINC ? 0 : (byte)constant == constant ? 1 : (short)constant == constant ? 2 : 4; } }
package org.ovirt.engine.core.common.businessentities; import java.util.ArrayList; import java.util.Date; import org.codehaus.jackson.annotate.JsonIgnore; import org.ovirt.engine.core.common.utils.ObjectUtils; import org.ovirt.engine.core.common.utils.SizeConverter; import org.ovirt.engine.core.compat.Guid; public class DiskImage extends DiskImageBase implements IImage { private static final long serialVersionUID = 3185087852755356847L; private Date lastModifiedDate; private ArrayList<String> storagesNames; private long actualSizeInBytes; private int readRateFromDiskImageDynamic; private int writeRateFromDiskImageDynamic; // Latency fields from DiskImageDynamic which are measured in seconds. private Double readLatency; private Double writeLatency; private Double flushLatency; private String appList; // TODO from storage_domain_static private Guid storagePoolId; // TODO from storage_domain_static private ArrayList<String> storagePath; private int readRateKbPerSec; private int writeRateKbPerSec; private ArrayList<DiskImage> snapshots; private double actualDiskWithSnapthotsSize; private ArrayList<Guid> quotaIds; private ArrayList<String> quotaNames; private String vmSnapshotDescription; public DiskImage() { setParentId(Guid.Empty); setCreationDate(new Date()); setLastModifiedDate(getCreationDate()); snapshots = new ArrayList<DiskImage>(); } public Guid getImageId() { return getImage().getId(); } public void setImageId(Guid id) { getImage().setId(id); } private VmEntityType vmEntityType; @Override public VmEntityType getVmEntityType() { return vmEntityType; } @Override public void setVmEntityType(VmEntityType vmEntityType) { this.vmEntityType = vmEntityType; } public Boolean getActive() { return getImage().isActive(); } @Override @JsonIgnore public boolean isDiskSnapshot() { return !getActive(); } public void setDiskSnapshot(boolean diskSnapshot) { setActive(!diskSnapshot); } @JsonIgnore public Guid getSnapshotId() { return isDiskSnapshot() ? getVmSnapshotId() : null; } public void setActive(boolean active) { getImage().setActive(active); } @Override public Date getCreationDate() { return getImage().getCreationDate(); } @Override public void setCreationDate(Date creationDate) { getImage().setCreationDate(creationDate); } public Date getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Date lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public long getActualSizeInBytes() { return actualSizeInBytes; } public void setActualSizeInBytes(long size) { actualSizeInBytes = size; setActualSize(getActualSizeInBytes() * 1.0 / (1024 * 1024 * 1024)); } public int getReadRate() { return readRateFromDiskImageDynamic; } public void setReadRate(int readRateFromDiskImageDynamic) { this.readRateFromDiskImageDynamic = readRateFromDiskImageDynamic; } public int getWriteRate() { return writeRateFromDiskImageDynamic; } public void setWriteRate(int writeRateFromDiskImageDynamic) { this.writeRateFromDiskImageDynamic = writeRateFromDiskImageDynamic; } public Double getReadLatency() { return readLatency; } public void setReadLatency(Double readLatency) { this.readLatency = readLatency; } public Double getWriteLatency() { return writeLatency; } public void setWriteLatency(Double writeLatency) { this.writeLatency = writeLatency; } public Double getFlushLatency() { return flushLatency; } public void setFlushLatency(Double flushLatency) { this.flushLatency = flushLatency; } private String description; @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } public String getAppList() { return appList; } public void setAppList(String appList) { this.appList = appList; } @Override public Guid getImageTemplateId() { return getImage().getTemplateImageId(); } @Override public void setImageTemplateId(Guid guid) { getImage().setTemplateImageId(guid); } public Guid getParentId() { return getImage().getParentId(); } public void setParentId(Guid parentId) { getImage().setParentId(parentId); } public ImageStatus getImageStatus() { return getImage().getStatus(); } public void setImageStatus(ImageStatus imageStatus) { getImage().setStatus(imageStatus); } public Date getLastModified() { return getImage().getLastModified(); } public void setLastModified(Date lastModified) { getImage().setLastModified(lastModified); } private ArrayList<Guid> storageIds; private ArrayList<StorageType> storageTypes; public ArrayList<Guid> getStorageIds() { return storageIds; } public void setStorageIds(ArrayList<Guid> storageIds) { this.storageIds = storageIds; } public ArrayList<StorageType> getStorageTypes() { return storageTypes; } public void setStorageTypes(ArrayList<StorageType> storageTypes) { this.storageTypes = storageTypes; } public Guid getVmSnapshotId() { return getImage().getSnapshotId(); } public void setVmSnapshotId(Guid snapshotId) { getImage().setSnapshotId(snapshotId); } public String getVmSnapshotDescription() { return vmSnapshotDescription; } public void setVmSnapshotDescription(String vmSnapshotDescription) { this.vmSnapshotDescription = vmSnapshotDescription; } public ArrayList<String> getStoragePath() { return storagePath; } public void setStoragePath(ArrayList<String> storagePath) { this.storagePath = storagePath; } public ArrayList<String> getStoragesNames() { return storagesNames; } public void setStoragesNames(ArrayList<String> storagesNames) { this.storagesNames = storagesNames; } @Deprecated public Guid getimage_group_id() { return getId(); } @Deprecated public void setimage_group_id(Guid value) { setId(value); } public Guid getStoragePoolId() { return storagePoolId; } public void setStoragePoolId(Guid storagePoolId) { this.storagePoolId = storagePoolId; } private double actualSize; /** * Get the actual Size of the DiskImage in GB. * The actual size is the size the DiskImage actually occupies on storage. * @return - Actual size used by this DiskImage in GB */ public double getActualSize() { return actualSize; } public void setActualSize(double size) { actualSize = size; } public double getActualDiskWithSnapshotsSize() { if (actualDiskWithSnapthotsSize == 0 && snapshots != null) { for (DiskImage disk : snapshots) { actualDiskWithSnapthotsSize += disk.getActualSize(); } } return actualDiskWithSnapthotsSize; } @JsonIgnore public double getActualDiskWithSnapshotsSizeInBytes() { return getActualDiskWithSnapshotsSize() * SizeConverter.BYTES_IN_GB; } /** * This method is created for SOAP serialization of primitives that are read only but sent by the client. The setter * implementation is empty and the field is not being changed. * @param value */ @Deprecated public void setActualDiskWithSnapshotsSize(double value) { } @Override public int getReadRateKbPerSec() { return readRateKbPerSec; } @Override public void setReadRateKbPerSec(int readRate) { readRateKbPerSec = readRate; } @Override public int getWriteRateKbPerSec() { return writeRateKbPerSec; } @Override public void setWriteRateKbPerSec(int writeRate) { writeRateKbPerSec = writeRate; } @Override public Object getQueryableId() { return getImageId(); } public ArrayList<DiskImage> getSnapshots() { return snapshots; } public ArrayList<Guid> getQuotaIds() { return quotaIds; } public void setQuotaIds(ArrayList<Guid> quotaIds) { this.quotaIds = quotaIds; } public Guid getQuotaId() { if (quotaIds == null || quotaIds.isEmpty()) { return null; } return quotaIds.get(0); } public void setQuotaId(Guid quotaId) { quotaIds = new ArrayList<Guid>(); quotaIds.add(quotaId); } public ArrayList<String> getQuotaNames() { return quotaNames; } public void setQuotaNames(ArrayList<String> quotaNames) { this.quotaNames = quotaNames; } public String getQuotaName() { if (quotaNames == null || quotaNames.isEmpty()) { return null; } return quotaNames.get(0); } public static DiskImage copyOf(DiskImage diskImage) { DiskImage di = new DiskImage(); // set all private fields (imitate clone - deep copy) di.setVolumeType(diskImage.getVolumeType()); di.setvolumeFormat(diskImage.getVolumeFormat()); di.setSize(diskImage.getSize()); di.setBoot(diskImage.isBoot()); if (diskImage.getQuotaIds() != null) { di.setQuotaIds(new ArrayList<Guid>(diskImage.getQuotaIds())); } if (diskImage.getQuotaNames() != null) { di.setQuotaNames(new ArrayList<String>(diskImage.getQuotaNames())); } di.setQuotaEnforcementType(diskImage.getQuotaEnforcementType()); di.setActive(diskImage.getActive()); di.setCreationDate(new Date(diskImage.getCreationDate().getTime())); di.setLastModifiedDate(new Date(diskImage.getLastModifiedDate().getTime())); di.actualSizeInBytes = diskImage.actualSizeInBytes; di.readRateFromDiskImageDynamic = diskImage.readRateFromDiskImageDynamic; di.writeRateFromDiskImageDynamic = diskImage.writeRateFromDiskImageDynamic; di.readLatency = diskImage.readLatency; di.writeLatency = diskImage.writeLatency; di.flushLatency = diskImage.flushLatency; // string is immutable, so no need to deep copy it di.description = diskImage.description; di.setImageId(diskImage.getImageId()); di.appList = diskImage.appList; di.setImageTemplateId(diskImage.getImageTemplateId()); di.setParentId(diskImage.getParentId()); di.setImageStatus(diskImage.getImageStatus()); di.setLastModified(new Date(diskImage.getLastModified().getTime())); di.storageIds = new ArrayList<Guid>(diskImage.storageIds); di.setVmSnapshotId(diskImage.getVmSnapshotId()); di.storagePath = diskImage.storagePath; di.setId(diskImage.getId()); di.setNumberOfVms(diskImage.getNumberOfVms()); di.setDiskInterface(diskImage.getDiskInterface()); di.setWipeAfterDelete(diskImage.isWipeAfterDelete()); di.setPropagateErrors(diskImage.getPropagateErrors()); di.setDiskAlias(diskImage.getDiskAlias()); di.setDiskDescription(diskImage.getDiskDescription()); di.setShareable(diskImage.isShareable()); di.storagePoolId = diskImage.storagePoolId; di.actualSize = diskImage.actualSize; di.readRateKbPerSec = diskImage.readRateKbPerSec; di.writeRateKbPerSec = diskImage.writeRateKbPerSec; // TODO: is it ok to use shallow copy here?! di.snapshots = new ArrayList<DiskImage>(diskImage.snapshots); di.actualDiskWithSnapthotsSize = diskImage.actualDiskWithSnapthotsSize; di.setCreationDate(new Date()); di.setLastModified(new Date()); di.setActive(true); di.setImageStatus(ImageStatus.LOCKED); return di; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((getImage() == null) ? 0 : getImage().hashCode()); result = prime * result + ((snapshots == null) ? 0 : snapshots.hashCode()); result = prime * result + (int) (actualSizeInBytes ^ (actualSizeInBytes >>> 32)); result = prime * result + ((appList == null) ? 0 : appList.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + readRateKbPerSec; result = prime * result + writeRateKbPerSec; result = prime * result + ((storagePath == null) ? 0 : storagePath.hashCode()); result = prime * result + readRateFromDiskImageDynamic; result = prime * result + ((storageIds == null) ? 0 : storageIds.hashCode()); result = prime * result + ((storagePoolId == null) ? 0 : storagePoolId.hashCode()); result = prime * result + ((storagesNames == null) ? 0 : storagesNames.hashCode()); result = prime * result + writeRateFromDiskImageDynamic; result = prime * result + ((readLatency == null) ? 0 : readLatency.hashCode()); result = prime * result + ((writeLatency == null) ? 0 : writeLatency.hashCode()); result = prime * result + ((flushLatency == null) ? 0 : flushLatency.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } DiskImage other = (DiskImage) obj; return (ObjectUtils.objectsEqual(getImage(), other.getImage()) && ObjectUtils.objectsEqual(snapshots, other.snapshots) && actualSizeInBytes == other.actualSizeInBytes && ObjectUtils.objectsEqual(appList, other.appList) && ObjectUtils.objectsEqual(description, other.description) && readRateKbPerSec == other.readRateKbPerSec && writeRateKbPerSec == other.writeRateKbPerSec && ObjectUtils.objectsEqual(storagePath, other.storagePath) && readRateFromDiskImageDynamic == other.readRateFromDiskImageDynamic && ObjectUtils.objectsEqual(storageIds, other.storageIds) && ObjectUtils.objectsEqual(storagePoolId, other.storagePoolId) && ObjectUtils.objectsEqual(storagesNames, other.storagesNames) && writeRateFromDiskImageDynamic == other.writeRateFromDiskImageDynamic && ObjectUtils.objectsEqual(readLatency, other.readLatency) && ObjectUtils.objectsEqual(writeLatency, other.writeLatency) && ObjectUtils.objectsEqual(flushLatency, other.flushLatency)); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.client.web.method.annotation; import org.junit.Before; import org.junit.Test; import org.springframework.core.MethodParameter; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; import org.springframework.security.oauth2.client.annotation.OAuth2Client; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Method; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2ClientArgumentResolver}. * * @author Joe Grandja */ public class OAuth2ClientArgumentResolverTests { private ClientRegistrationRepository clientRegistrationRepository; private OAuth2AuthorizedClientService authorizedClientService; private OAuth2ClientArgumentResolver argumentResolver; private ClientRegistration clientRegistration; private OAuth2AuthorizedClient authorizedClient; private OAuth2AccessToken accessToken; @Before public void setUp() { this.clientRegistrationRepository = mock(ClientRegistrationRepository.class); this.authorizedClientService = mock(OAuth2AuthorizedClientService.class); this.argumentResolver = new OAuth2ClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientService); this.clientRegistration = ClientRegistration.withRegistrationId("client1") .clientId("client-id") .clientSecret("secret") .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/client1") .scope("scope1", "scope2") .authorizationUri("https://provider.com/oauth2/auth") .tokenUri("https://provider.com/oauth2/token") .clientName("Client 1") .build(); when(this.clientRegistrationRepository.findByRegistrationId(anyString())).thenReturn(this.clientRegistration); this.authorizedClient = mock(OAuth2AuthorizedClient.class); when(this.authorizedClientService.loadAuthorizedClient(anyString(), any())).thenReturn(this.authorizedClient); this.accessToken = mock(OAuth2AccessToken.class); when(this.authorizedClient.getAccessToken()).thenReturn(this.accessToken); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(mock(Authentication.class)); SecurityContextHolder.setContext(securityContext); } @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { assertThatThrownBy(() -> new OAuth2ClientArgumentResolver(null, this.authorizedClientService)) .isInstanceOf(IllegalArgumentException.class); } @Test public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { assertThatThrownBy(() -> new OAuth2ClientArgumentResolver(this.clientRegistrationRepository, null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void supportsParameterWhenParameterTypeOAuth2AccessTokenThenTrue() { MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessToken", OAuth2AccessToken.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isTrue(); } @Test public void supportsParameterWhenParameterTypeOAuth2AccessTokenWithoutAnnotationThenFalse() { MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessTokenWithoutAnnotation", OAuth2AccessToken.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse(); } @Test public void supportsParameterWhenParameterTypeOAuth2AuthorizedClientThenTrue() { MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isTrue(); } @Test public void supportsParameterWhenParameterTypeOAuth2AuthorizedClientWithoutAnnotationThenFalse() { MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClientWithoutAnnotation", OAuth2AuthorizedClient.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse(); } @Test public void supportsParameterWhenParameterTypeClientRegistrationThenTrue() { MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistration", ClientRegistration.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isTrue(); } @Test public void supportsParameterWhenParameterTypeClientRegistrationWithoutAnnotationThenFalse() { MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistrationWithoutAnnotation", ClientRegistration.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse(); } @Test public void supportsParameterWhenParameterTypeUnsupportedThenFalse() { MethodParameter methodParameter = this.getMethodParameter("paramTypeUnsupported", String.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse(); } @Test public void supportsParameterWhenParameterTypeUnsupportedWithoutAnnotationThenFalse() { MethodParameter methodParameter = this.getMethodParameter("paramTypeUnsupportedWithoutAnnotation", String.class); assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse(); } @Test public void resolveArgumentWhenRegistrationIdEmptyAndNotOAuth2AuthenticationThenThrowIllegalArgumentException() throws Exception { MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AccessToken.class); assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to resolve the Client Registration Identifier. It must be provided via @OAuth2Client(\"client1\") or @OAuth2Client(registrationId = \"client1\")."); } @Test public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() throws Exception { OAuth2AuthenticationToken authentication = mock(OAuth2AuthenticationToken.class); when(authentication.getAuthorizedClientRegistrationId()).thenReturn("client1"); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); SecurityContextHolder.setContext(securityContext); MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AccessToken.class); this.argumentResolver.resolveArgument(methodParameter, null, null, null); } @Test public void resolveArgumentWhenClientRegistrationFoundThenResolves() throws Exception { MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistration", ClientRegistration.class); assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.clientRegistration); } @Test public void resolveArgumentWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() throws Exception { when(this.clientRegistrationRepository.findByRegistrationId(anyString())).thenReturn(null); MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistration", ClientRegistration.class); assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to find ClientRegistration with registration identifier \"client1\"."); } @Test public void resolveArgumentWhenParameterTypeOAuth2AuthorizedClientAndCurrentAuthenticationNullThenThrowIllegalStateException() throws Exception { SecurityContextHolder.clearContext(); MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessage("Unable to resolve the Authorized Client with registration identifier \"client1\". " + "An \"authenticated\" or \"unauthenticated\" session is required. " + "To allow for unauthenticated access, ensure HttpSecurity.anonymous() is configured."); } @Test public void resolveArgumentWhenOAuth2AuthorizedClientFoundThenResolves() throws Exception { MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.authorizedClient); } @Test public void resolveArgumentWhenOAuth2AuthorizedClientNotFoundThenThrowClientAuthorizationRequiredException() throws Exception { when(this.authorizedClientService.loadAuthorizedClient(anyString(), any())).thenReturn(null); MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) .isInstanceOf(ClientAuthorizationRequiredException.class); } @Test public void resolveArgumentWhenOAuth2AccessTokenAndOAuth2AuthorizedClientFoundThenResolves() throws Exception { MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessToken", OAuth2AccessToken.class); assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.authorizedClient.getAccessToken()); } @Test public void resolveArgumentWhenOAuth2AccessTokenAndOAuth2AuthorizedClientNotFoundThenThrowClientAuthorizationRequiredException() throws Exception { when(this.authorizedClientService.loadAuthorizedClient(anyString(), any())).thenReturn(null); MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessToken", OAuth2AccessToken.class); assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) .isInstanceOf(ClientAuthorizationRequiredException.class); } @Test public void resolveArgumentWhenOAuth2AccessTokenAndAnnotationRegistrationIdSetThenResolves() throws Exception { MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessTokenAnnotationRegistrationId", OAuth2AccessToken.class); assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.authorizedClient.getAccessToken()); } private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) { Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes); return new MethodParameter(method, 0); } static class TestController { void paramTypeAccessToken(@OAuth2Client("client1") OAuth2AccessToken accessToken) { } void paramTypeAccessTokenWithoutAnnotation(OAuth2AccessToken accessToken) { } void paramTypeAuthorizedClient(@OAuth2Client("client1") OAuth2AuthorizedClient authorizedClient) { } void paramTypeAuthorizedClientWithoutAnnotation(OAuth2AuthorizedClient authorizedClient) { } void paramTypeClientRegistration(@OAuth2Client("client1") ClientRegistration clientRegistration) { } void paramTypeClientRegistrationWithoutAnnotation(ClientRegistration clientRegistration) { } void paramTypeUnsupported(@OAuth2Client("client1") String param) { } void paramTypeUnsupportedWithoutAnnotation(String param) { } void registrationIdEmpty(@OAuth2Client OAuth2AccessToken accessToken) { } void paramTypeAccessTokenAnnotationRegistrationId(@OAuth2Client(registrationId = "client1") OAuth2AccessToken accessToken) { } } }
package com.jetbrains.python.refactoring.move; import com.intellij.openapi.util.Condition; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.psi.util.QualifiedName; import com.intellij.usageView.UsageInfo; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.python.PyNames; import com.jetbrains.python.codeInsight.PyDunderAllReference; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.resolve.QualifiedNameFinder; import com.jetbrains.python.refactoring.classes.PyClassRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static com.jetbrains.python.psi.impl.PyImportStatementNavigator.getImportStatementByElement; /** * @author Mikhail Golubev */ public class PyMoveSymbolProcessor { private final PsiNamedElement myMovedElement; private final PyFile myDestinationFile; private final List<UsageInfo> myUsages; private final PsiElement[] myAllMovedElements; private final List<PsiFile> myOptimizeImportTargets = new ArrayList<PsiFile>(); private final Set<ScopeOwner> myScopeOwnersWithGlobal = new HashSet<ScopeOwner>(); public PyMoveSymbolProcessor(@NotNull final PsiNamedElement element, @NotNull PyFile destination, @NotNull Collection<UsageInfo> usages, @NotNull PsiElement[] otherElements) { myMovedElement = element; myDestinationFile = destination; myAllMovedElements = otherElements; myUsages = ContainerUtil.sorted(usages, new Comparator<UsageInfo>() { @Override public int compare(UsageInfo u1, UsageInfo u2) { return PsiUtilCore.compareElementsByPosition(u1.getElement(), u2.getElement()); } }); } public final void moveElement() { final PsiElement oldElementBody = PyMoveModuleMembersHelper.expandNamedElementBody(myMovedElement); final PsiFile sourceFile = myMovedElement.getContainingFile(); if (oldElementBody != null) { PyClassRefactoringUtil.rememberNamedReferences(oldElementBody); final PsiElement newElementBody = addElementToFile(oldElementBody); final PsiNamedElement newElement = PyMoveModuleMembersHelper.extractNamedElement(newElementBody); assert newElement != null; for (UsageInfo usage : myUsages) { final PsiElement usageElement = usage.getElement(); if (usageElement != null) { updateSingleUsage(usageElement, newElement); } } PyClassRefactoringUtil.restoreNamedReferences(newElementBody, myMovedElement, myAllMovedElements); deleteElement(); optimizeImports(sourceFile); } } private void deleteElement() { final PsiElement elementBody = PyMoveModuleMembersHelper.expandNamedElementBody(myMovedElement); assert elementBody != null; elementBody.delete(); } private void optimizeImports(@Nullable PsiFile originalFile) { for (PsiFile usageFile : myOptimizeImportTargets) { PyClassRefactoringUtil.optimizeImports(usageFile); } if (originalFile != null) { PyClassRefactoringUtil.optimizeImports(originalFile); } } @NotNull private PsiElement addElementToFile(@NotNull PsiElement element) { final PsiElement firstUsage = findFirstTopLevelWithUsageAtDestination(); if (firstUsage != null) { return myDestinationFile.addBefore(element, firstUsage); } else { return myDestinationFile.add(element); } } @Nullable private PsiElement findFirstTopLevelWithUsageAtDestination() { final List<PsiElement> topLevelAtDestination = ContainerUtil.mapNotNull(myUsages, new Function<UsageInfo, PsiElement>() { @Override public PsiElement fun(UsageInfo usage) { final PsiElement element = usage.getElement(); if (element != null && ScopeUtil.getScopeOwner(element) == myDestinationFile && getImportStatementByElement(element) == null) { return findTopLevelParent(element); } return null; } }); if (topLevelAtDestination.isEmpty()) { return null; } return Collections.min(topLevelAtDestination, new Comparator<PsiElement>() { @Override public int compare(PsiElement e1, PsiElement e2) { return PsiUtilCore.compareElementsByPosition(e1, e2); } }); } @Nullable private PsiElement findTopLevelParent(@NotNull PsiElement element) { return PsiTreeUtil.findFirstParent(element, new Condition<PsiElement>() { @Override public boolean value(PsiElement element) { return element.getParent() == myDestinationFile; } }); } private void updateSingleUsage(@NotNull PsiElement usage, @NotNull PsiNamedElement newElement) { final PsiFile usageFile = usage.getContainingFile(); if (belongsToSomeMovedElement(usage)) { return; } if (usage instanceof PyQualifiedExpression) { final PyQualifiedExpression qualifiedExpr = (PyQualifiedExpression)usage; if (myMovedElement instanceof PyClass && PyNames.INIT.equals(qualifiedExpr.getName())) { return; } else if (qualifiedExpr.isQualified()) { insertQualifiedImportAndReplaceReference(newElement, qualifiedExpr); } else if (usageFile == myMovedElement.getContainingFile()) { if (usage.getParent() instanceof PyGlobalStatement) { myScopeOwnersWithGlobal.add(ScopeUtil.getScopeOwner(usage)); if (((PyGlobalStatement)usage.getParent()).getGlobals().length == 1) { usage.getParent().delete(); } else { usage.delete(); } } else if (myScopeOwnersWithGlobal.contains(ScopeUtil.getScopeOwner(usage))) { insertQualifiedImportAndReplaceReference(newElement, qualifiedExpr); } else { insertImportFromAndReplaceReference(newElement, qualifiedExpr); } } else { final PyImportStatementBase importStmt = getImportStatementByElement(usage); if (importStmt != null) { PyClassRefactoringUtil.updateUnqualifiedImportOfElement(importStmt, newElement); } } if (resolvesToLocalStarImport(usage)) { PyClassRefactoringUtil.insertImport(usage, newElement); myOptimizeImportTargets.add(usageFile); } } else if (usage instanceof PyStringLiteralExpression) { for (PsiReference ref : usage.getReferences()) { if (ref instanceof PyDunderAllReference) { usage.delete(); } else { if (ref.isReferenceTo(myMovedElement)) { ref.bindToElement(newElement); } } } } } private boolean belongsToSomeMovedElement(@NotNull final PsiElement element) { return ContainerUtil.exists(myAllMovedElements, new Condition<PsiElement>() { @Override public boolean value(PsiElement movedElement) { final PsiElement movedElementBody = PyMoveModuleMembersHelper.expandNamedElementBody((PsiNamedElement)movedElement); return PsiTreeUtil.isAncestor(movedElementBody, element, false); } }); } /** * <pre><code> * print(foo.bar) * </code></pre> * is transformed to * <pre><code> * from new import bar * print(bar) * </code></pre> */ private static void insertImportFromAndReplaceReference(@NotNull PsiNamedElement targetElement, @NotNull PyQualifiedExpression expression) { PyClassRefactoringUtil.insertImport(expression, targetElement, null, true); final PyElementGenerator generator = PyElementGenerator.getInstance(expression.getProject()); final PyExpression generated = generator.createExpressionFromText(LanguageLevel.forElement(expression), expression.getReferencedName()); expression.replace(generated); } /** * <pre><code> * print(foo.bar) * </code></pre> * is transformed to * <pre><code> * import new * print(new.bar) * </code></pre> */ private static void insertQualifiedImportAndReplaceReference(@NotNull PsiNamedElement targetElement, @NotNull PyQualifiedExpression expression) { final PsiFile file = targetElement.getContainingFile(); final QualifiedName qualifier = QualifiedNameFinder.findCanonicalImportPath(file, expression); PyClassRefactoringUtil.insertImport(expression, file, null, false); final PyElementGenerator generator = PyElementGenerator.getInstance(expression.getProject()); final PyExpression generated = generator.createExpressionFromText(LanguageLevel.forElement(expression), qualifier + "." + expression.getReferencedName()); expression.replace(generated); } private static boolean resolvesToLocalStarImport(@NotNull PsiElement element) { final PsiReference ref = element.getReference(); final List<PsiElement> resolvedElements = new ArrayList<PsiElement>(); if (ref instanceof PsiPolyVariantReference) { for (ResolveResult result : ((PsiPolyVariantReference)ref).multiResolve(false)) { resolvedElements.add(result.getElement()); } } else if (ref != null) { resolvedElements.add(ref.resolve()); } final PsiFile containingFile = element.getContainingFile(); if (containingFile != null) { for (PsiElement resolved : resolvedElements) { if (resolved instanceof PyStarImportElement && resolved.getContainingFile() == containingFile) { return true; } } } return false; } }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES 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.openqa.selenium.htmlunit; import java.util.List; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.NoSuchFrameException; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.WindowType; import org.openqa.selenium.WrapsElement; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebWindow; import com.gargoylesoftware.htmlunit.WebWindowNotFoundException; import com.gargoylesoftware.htmlunit.html.BaseFrameElement; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.FrameWindow; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlHtml; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** * HtmlUnit target locator */ public class HtmlUnitTargetLocator implements WebDriver.TargetLocator { protected final HtmlUnitDriver driver; public HtmlUnitTargetLocator(HtmlUnitDriver driver) { this.driver = driver; } @Override public WebDriver newWindow(WindowType typeHint) { return null; } @Override public WebDriver frame(int index) { Page page = driver.getWindowManager().lastPage(); if (page instanceof HtmlPage) { try { driver.setCurrentWindow(((HtmlPage) page).getFrames().get(index)); } catch (IndexOutOfBoundsException ignored) { throw new NoSuchFrameException("Cannot find frame: " + index); } } return driver; } @Override public WebDriver frame(final String nameOrId) { Page page = driver.getWindowManager().lastPage(); if (page instanceof HtmlPage) { // First check for a frame with the matching name. for (final FrameWindow frameWindow : ((HtmlPage) page).getFrames()) { if (frameWindow.getName().equals(nameOrId)) { driver.setCurrentWindow(frameWindow); return driver; } } } // Next, check for a frame with a matching ID. For simplicity, assume the ID is unique. // Users can still switch to frames with non-unique IDs using a WebElement switch: // WebElement frameElement = driver.findElement(By.xpath("//frame[@id=\"foo\"]")); // driver.switchTo().frame(frameElement); try { HtmlUnitWebElement element = (HtmlUnitWebElement) driver.findElement(By.id(nameOrId)); DomElement domElement = element.getElement(); if (domElement instanceof BaseFrameElement) { driver.setCurrentWindow(((BaseFrameElement) domElement).getEnclosedWindow()); return driver; } } catch (NoSuchElementException ignored) { } throw new NoSuchFrameException("Unable to locate frame with name or ID: " + nameOrId); } @Override public WebDriver frame(WebElement frameElement) { while (frameElement instanceof WrapsElement) { frameElement = ((WrapsElement) frameElement).getWrappedElement(); } HtmlUnitWebElement webElement = (HtmlUnitWebElement) frameElement; webElement.assertElementNotStale(); DomElement domElement = webElement.getElement(); if (!(domElement instanceof BaseFrameElement)) { throw new NoSuchFrameException(webElement.getTagName() + " is not a frame element."); } driver.setCurrentWindow(((BaseFrameElement) domElement).getEnclosedWindow()); return driver; } @Override public WebDriver parentFrame() { driver.setCurrentWindow(driver.getCurrentWindow().getParentWindow()); return driver; } @Override public WebDriver window(String windowId) { try { WebWindow window = driver.getWebClient().getWebWindowByName(windowId); return finishSelecting(window); } catch (WebWindowNotFoundException e) { List<WebWindow> allWindows = driver.getWebClient().getWebWindows(); for (WebWindow current : allWindows) { WebWindow top = current.getTopWindow(); if (String.valueOf(System.identityHashCode(top)).equals(windowId)) { return finishSelecting(top); } } throw new NoSuchWindowException("Cannot find window: " + windowId); } } private WebDriver finishSelecting(WebWindow window) { driver.getWebClient().setCurrentWindow(window); driver.setCurrentWindow(window); driver.getAlert().setAutoAccept(false); return driver; } @Override public WebDriver defaultContent() { driver.getWindowManager().switchToDefaultContentOfWindow(driver.getCurrentWindow().getTopWindow()); return driver; } @Override public WebElement activeElement() { Page page = driver.getWindowManager().lastPage(); if (page instanceof HtmlPage) { DomElement element = ((HtmlPage) page).getFocusedElement(); if (element == null || element instanceof HtmlHtml) { List<? extends HtmlElement> allBodies = ((HtmlPage) page).getDocumentElement().getElementsByTagName("body"); if (!allBodies.isEmpty()) { return driver.toWebElement(allBodies.get(0)); } } else { return driver.toWebElement(element); } } throw new NoSuchElementException("Unable to locate element with focus or body tag"); } @Override public Alert alert() { final HtmlUnitAlert alert = driver.getAlert(); if (!alert.isLocked()) { for (int i = 0; i < 5; i++) { if (!alert.isLocked()) { try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } } } if (!alert.isLocked()) { driver.getCurrentWindow(); throw new NoAlertPresentException(); } } final WebWindow alertWindow = alert.getWebWindow(); final WebWindow currentWindow = driver.getCurrentWindow(); if (alertWindow != currentWindow && !isChild(currentWindow, alertWindow) && !isChild(alertWindow, currentWindow)) { throw new TimeoutException(); } return alert; } private static boolean isChild(WebWindow parent, WebWindow potentialChild) { for (WebWindow child = potentialChild; child != null; child = child.getParentWindow()) { if (child == parent) { return true; } if (child == child.getTopWindow()) { break; } } return false; } }
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import java.io.IOException; import java.io.Writer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.jivesoftware.smack.packet.Packet; /** * Writes packets to a XMPP server. Packets are sent using a dedicated thread. Packet interceptors * can be registered to dynamically modify packets before they're actually sent. Packet listeners * can be registered to listen for all outgoing packets. * @see Connection#addPacketInterceptor * @see Connection#addPacketSendingListener * @author Matt Tucker */ class PacketWriter { private Thread writerThread; private Thread keepAliveThread; private Writer writer; private XMPPConnection connection; private final BlockingQueue<Packet> queue; private boolean done; /** * Timestamp when the last stanza was sent to the server. This information is used by the keep * alive process to only send heartbeats when the connection has been idle. */ private long lastActive = System.currentTimeMillis(); /** * Creates a new packet writer with the specified connection. * @param connection the connection. */ protected PacketWriter(XMPPConnection connection) { this.queue = new ArrayBlockingQueue<Packet>(500, true); this.connection = connection; init(); } /** * Initializes the writer in order to be used. It is called at the first connection and also is * invoked if the connection is disconnected by an error. */ protected void init() { this.writer = connection.writer; done = false; writerThread = new Thread() { @Override public void run() { writePackets(this); } }; writerThread.setName("Smack Packet Writer (" + connection.connectionCounterValue + ")"); writerThread.setDaemon(true); } /** * Sends the specified packet to the server. * @param packet the packet to send. */ public void sendPacket(Packet packet) { // Log.i("XXX", "............."); // Log.i("XXX", packet.toXML()); // Log.i("XXX", "............."); if (!done) { // Invoke interceptors for the new packet that is about to be sent. // Interceptors // may modify the content of the packet. connection.firePacketInterceptors(packet); try { queue.put(packet); } catch (InterruptedException ie) { ie.printStackTrace(); return; } synchronized (queue) { queue.notifyAll(); } // Process packet writer listeners. Note that we're using the // sending // thread so it's expected that listeners are fast. connection.firePacketSendingListeners(packet); } } /** * Starts the packet writer thread and opens a connection to the server. The packet writer will * continue writing packets until {@link #shutdown} or an error occurs. */ public void startup() { writerThread.start(); } /** * Starts the keep alive process. A white space (aka heartbeat) is going to be sent to the * server every 30 seconds (by default) since the last stanza was sent to the server. */ void startKeepAliveProcess() { // Schedule a keep-alive task to run if the feature is enabled. will // write // out a space character each time it runs to keep the TCP/IP connection // open. int keepAliveInterval = SmackConfiguration.getKeepAliveInterval(); if (keepAliveInterval > 0) { KeepAliveTask task = new KeepAliveTask(keepAliveInterval); keepAliveThread = new Thread(task); task.setThread(keepAliveThread); keepAliveThread.setDaemon(true); keepAliveThread.setName("Smack Keep Alive (" + connection.connectionCounterValue + ")"); keepAliveThread.start(); } } void setWriter(Writer writer) { this.writer = writer; } /** * Shuts down the packet writer. Once this method has been called, no further packets will be * written to the server. */ public void shutdown() { done = true; synchronized (queue) { queue.notifyAll(); } // Interrupt the keep alive thread if one was created if (keepAliveThread != null) keepAliveThread.interrupt(); } /** * Cleans up all resources used by the packet writer. */ void cleanup() { connection.interceptors.clear(); connection.sendListeners.clear(); } /** * Returns the next available packet from the queue for writing. * @return the next packet for writing. */ private Packet nextPacket() { Packet packet = null; // Wait until there's a packet or we're done. while (!done && (packet = queue.poll()) == null) { try { synchronized (queue) { queue.wait(); } } catch (InterruptedException ie) { // Do nothing } } return packet; } private void writePackets(Thread thisThread) { try { // Open the stream. openStream(); // Write out packets from the queue. while (!done && (writerThread == thisThread)) { Packet packet = nextPacket(); if (packet != null) { synchronized (writer) { writer.write(packet.toXML()); writer.flush(); // Keep track of the last time a stanza was sent to the // server lastActive = System.currentTimeMillis(); } } } // Flush out the rest of the queue. If the queue is extremely large, // it's possible // we won't have time to entirely flush it before the socket is // forced closed // by the shutdown process. try { synchronized (writer) { while (!queue.isEmpty()) { Packet packet = queue.remove(); writer.write(packet.toXML()); } writer.flush(); } } catch (Exception e) { e.printStackTrace(); } // Delete the queue contents (hopefully nothing is left). queue.clear(); // Close the stream. try { writer.write("</stream:stream>"); writer.flush(); } catch (Exception e) { // Do nothing } finally { try { writer.close(); } catch (Exception e) { // Do nothing } } } catch (IOException ioe) { if (!done && !connection.isSocketClosed()) { done = true; // packetReader could be set to null by an concurrent // disconnect() call. // Therefore Prevent NPE exceptions by checking packetReader. if (connection.packetReader != null) { connection.packetReader.notifyConnectionError(ioe); } } } } /** * Sends to the server a new stream element. This operation may be requested several times so we * need to encapsulate the logic in one place. This message will be sent while doing TLS, SASL * and resource binding. * @throws IOException If an error occurs while sending the stanza to the server. */ void openStream() throws IOException { StringBuilder stream = new StringBuilder(); stream.append("<stream:stream"); stream.append(" to=\"").append(connection.getServiceName()) .append("\""); stream.append(" xmlns=\"jabber:client\""); stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\""); stream.append(" version=\"1.0\">"); writer.write(stream.toString()); writer.flush(); } /** * A TimerTask that keeps connections to the server alive by sending a space character on an * interval. */ private class KeepAliveTask implements Runnable { private int delay; private Thread thread; // private int sendCount; // private int sendCount; public KeepAliveTask(int delay) { this.delay = delay; } protected void setThread(Thread thread) { this.thread = thread; } @Override public void run() { /*try { // Sleep a minimum of 15 seconds plus delay before sending first // heartbeat. This // will give time to // properly finish TLS negotiation and then start sending // heartbeats. Thread.sleep(15000 + delay); } catch (InterruptedException ie) { // Do nothing ie.printStackTrace(); }*/ while (!done && keepAliveThread == thread/* && sendCount <= 3*/) { synchronized (writer) { // Send heartbeat if no packet has been sent to the server // for a given time if (System.currentTimeMillis() - lastActive >= delay) { try { // LogUtils.v("Xmpp#send the heartbeat"); writer.write(" "); writer.flush(); lastActive = System.currentTimeMillis(); // sendCount ++; } catch (IOException ioe) { if (!done && !connection.isSocketClosed()) { done = true; // packetReader could be set to null by an concurrent // disconnect() call. // Therefore Prevent NPE exceptions by checking packetReader. if (connection.packetReader != null) { connection.packetReader.notifyConnectionError(ioe); } } } catch (Exception e) { // Do nothing e.printStackTrace(); } } } try { long waitTime = delay; long start = System.currentTimeMillis(); long now; // Sleep until we should write the next keep-alive. do { Thread.sleep(waitTime); now = System.currentTimeMillis(); waitTime -= now - start; start = now; } while (waitTime > 0); } catch (InterruptedException ie) { // Do nothing ie.printStackTrace(); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.ignite.internal.client.impl.connection; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.failure.FailureType; import org.apache.ignite.internal.client.GridClientClosedException; import org.apache.ignite.internal.client.GridClientConfiguration; import org.apache.ignite.internal.client.GridClientException; import org.apache.ignite.internal.client.GridClientHandshakeException; import org.apache.ignite.internal.client.GridClientNode; import org.apache.ignite.internal.client.GridClientProtocol; import org.apache.ignite.internal.client.GridServerUnreachableException; import org.apache.ignite.internal.client.impl.GridClientFutureAdapter; import org.apache.ignite.internal.client.impl.GridClientThreadFactory; import org.apache.ignite.internal.client.marshaller.GridClientMarshaller; import org.apache.ignite.internal.client.marshaller.optimized.GridClientZipOptimizedMarshaller; import org.apache.ignite.internal.client.util.GridClientStripedLock; import org.apache.ignite.internal.client.util.GridClientUtils; import org.apache.ignite.internal.processors.rest.client.message.GridClientHandshakeResponse; import org.apache.ignite.internal.processors.rest.client.message.GridClientMessage; import org.apache.ignite.internal.processors.rest.client.message.GridClientNodeStateBeforeStartRequest; import org.apache.ignite.internal.processors.rest.client.message.GridClientPingPacket; import org.apache.ignite.internal.processors.rest.protocols.tcp.GridTcpRestParser; import org.apache.ignite.internal.util.nio.GridNioCodecFilter; import org.apache.ignite.internal.util.nio.GridNioFilter; import org.apache.ignite.internal.util.nio.GridNioServer; import org.apache.ignite.internal.util.nio.GridNioServerListener; import org.apache.ignite.internal.util.nio.GridNioSession; import org.apache.ignite.internal.util.nio.ssl.GridNioSslFilter; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.logger.java.JavaLogger; import org.apache.ignite.plugin.security.SecurityCredentials; import org.jetbrains.annotations.Nullable; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.logging.Level.INFO; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS; import static org.apache.ignite.internal.client.impl.connection.GridClientConnectionCloseReason.CLIENT_CLOSED; import static org.apache.ignite.internal.client.impl.connection.GridClientConnectionCloseReason.FAILED; /** * Cached connections manager. */ public abstract class GridClientConnectionManagerAdapter implements GridClientConnectionManager { /** Count of reconnect retries before init considered failed. */ private static final int INIT_RETRY_CNT = 3; /** Initialization retry interval. */ private static final int INIT_RETRY_INTERVAL = 1000; /** Class logger. */ private final Logger log; /** All local enabled MACs. */ private final Collection<String> macs; /** NIO server. */ private GridNioServer srv; /** Active connections. */ private final ConcurrentMap<InetSocketAddress, GridClientConnection> conns = new ConcurrentHashMap<>(); /** Active connections of nodes. */ private final ConcurrentMap<UUID, GridClientConnection> nodeConns = new ConcurrentHashMap<>(); /** SSL context. */ private final SSLContext sslCtx; /** Client configuration. */ protected final GridClientConfiguration cfg; /** Topology. */ private final GridClientTopology top; /** Client id. */ private final UUID clientId; /** Router endpoints to use instead of topology info. */ private final Collection<InetSocketAddress> routers; /** Closed flag. */ private volatile boolean closed; /** Shared executor service. */ private final ExecutorService executor; /** Endpoint striped lock. */ private final GridClientStripedLock endpointStripedLock = new GridClientStripedLock(16); /** Service for ping requests, {@code null} if HTTP protocol is used. */ private final ScheduledExecutorService pingExecutor; /** Marshaller ID. */ private final Byte marshId; /** Connecting to a node before starting it without getting/updating topology. */ private final boolean beforeNodeStart; /** * @param clientId Client ID. * @param sslCtx SSL context to enable secured connection or {@code null} to use unsecured one. * @param cfg Client configuration. * @param routers Routers or empty collection to use endpoints from topology info. * @param top Topology. * @param marshId Marshaller ID. * @param beforeNodeStart Connecting to a node before starting it without getting/updating topology. * @throws GridClientException In case of error. */ @SuppressWarnings("unchecked") protected GridClientConnectionManagerAdapter(UUID clientId, SSLContext sslCtx, GridClientConfiguration cfg, Collection<InetSocketAddress> routers, GridClientTopology top, @Nullable Byte marshId, boolean routerClient, boolean beforeNodeStart ) throws GridClientException { assert clientId != null : "clientId != null"; assert cfg != null : "cfg != null"; assert routers != null : "routers != null"; assert top != null : "top != null"; this.clientId = clientId; this.sslCtx = sslCtx; this.cfg = cfg; this.routers = new ArrayList<>(routers); this.top = top; this.beforeNodeStart = beforeNodeStart; log = Logger.getLogger(getClass().getName()); executor = cfg.getExecutorService() != null ? cfg.getExecutorService() : Executors.newCachedThreadPool(new GridClientThreadFactory("exec", true)); pingExecutor = cfg.getProtocol() == GridClientProtocol.TCP ? Executors.newScheduledThreadPool( Runtime.getRuntime().availableProcessors(), new GridClientThreadFactory("exec", true)) : null; this.marshId = marshId; if (marshId == null && cfg.getMarshaller() == null) throw new GridClientException("Failed to start client (marshaller is not configured)."); macs = U.allLocalMACs(); if (cfg.getProtocol() == GridClientProtocol.TCP) { try { IgniteLogger gridLog = new JavaLogger(false); GridNioFilter[] filters; GridNioFilter codecFilter = new GridNioCodecFilter(new GridTcpRestParser(routerClient), gridLog, false); if (sslCtx != null) { GridNioSslFilter sslFilter = new GridNioSslFilter(sslCtx, true, ByteOrder.nativeOrder(), gridLog); sslFilter.directMode(false); filters = new GridNioFilter[]{codecFilter, sslFilter}; } else filters = new GridNioFilter[]{codecFilter}; srv = GridNioServer.builder().address(U.getLocalHost()) .port(-1) .listener(new NioListener(log)) .filters(filters) .logger(gridLog) .selectorCount(Runtime.getRuntime().availableProcessors()) .sendQueueLimit(1024) .byteOrder(ByteOrder.nativeOrder()) .tcpNoDelay(cfg.isTcpNoDelay()) .directBuffer(true) .directMode(false) .socketReceiveBufferSize(0) .socketSendBufferSize(0) .idleTimeout(Long.MAX_VALUE) .igniteInstanceName(routerClient ? "routerClient" : "gridClient") .serverName("tcp-client") .daemon(cfg.isDaemon()) .build(); srv.start(); } catch (IOException | IgniteCheckedException e) { throw new GridClientException("Failed to start connection server.", e); } } } /** {@inheritDoc} */ @Override public void init(Collection<InetSocketAddress> srvs) throws GridClientException, InterruptedException { init0(); connect(srvs, conn -> { if (beforeNodeStart) { conn.messageBeforeStart(new GridClientNodeStateBeforeStartRequest()) .get(cfg.getConnectTimeout(), MILLISECONDS); } else { conn.topology(cfg.isAutoFetchAttributes(), cfg.isAutoFetchMetrics(), null) .get(cfg.getConnectTimeout(), MILLISECONDS); } }); } /** * Additional initialization. * * @throws GridClientException In case of error. */ protected abstract void init0() throws GridClientException; /** * Gets active communication facade. * * @param node Remote node to which connection should be established. * @throws GridServerUnreachableException If none of the servers can be reached after the exception. * @throws GridClientClosedException If client was closed manually. * @throws InterruptedException If connection was interrupted. */ @Override public GridClientConnection connection(GridClientNode node) throws GridClientClosedException, GridServerUnreachableException, InterruptedException { assert node != null; // Use router's connections if defined. if (!routers.isEmpty()) return connection(null, routers); GridClientConnection conn = nodeConns.get(node.nodeId()); if (conn != null) { // Ignore closed connections. if (conn.closeIfIdle(cfg.getMaxConnectionIdleTime())) closeIdle(); else return conn; } // Use node's connection, if node is available over rest. Collection<InetSocketAddress> endpoints = node.availableAddresses(cfg.getProtocol(), true); List<InetSocketAddress> resolvedEndpoints = new ArrayList<>(endpoints.size()); for (InetSocketAddress endpoint : endpoints) if (!endpoint.isUnresolved()) resolvedEndpoints.add(endpoint); if (resolvedEndpoints.isEmpty()) { throw new GridServerUnreachableException("No available endpoints to connect " + "(is rest enabled for this node?): " + node); } boolean sameHost = node.attributes().isEmpty() || F.containsAny(macs, node.attribute(ATTR_MACS).toString().split(", ")); Collection<InetSocketAddress> srvs = new LinkedHashSet<>(); if (sameHost) { Collections.sort(resolvedEndpoints, U.inetAddressesComparator(true)); srvs.addAll(resolvedEndpoints); } else { for (InetSocketAddress endpoint : resolvedEndpoints) if (!endpoint.getAddress().isLoopbackAddress()) srvs.add(endpoint); } return connection(node.nodeId(), srvs); } /** * Returns connection to one of the given addresses. * * @param nodeId {@code UUID} of node for mapping with connection. * {@code null} if no need of mapping. * @param srvs Collection of addresses to connect to. * @return Connection to use for operations, targeted for the given node. * @throws GridServerUnreachableException If connection can't be established. * @throws GridClientClosedException If connections manager has been closed already. * @throws InterruptedException If connection was interrupted. */ public GridClientConnection connection(@Nullable UUID nodeId, Collection<InetSocketAddress> srvs) throws GridServerUnreachableException, GridClientClosedException, InterruptedException { if (srvs == null || srvs.isEmpty()) throw new GridServerUnreachableException("Failed to establish connection to the grid" + " (address list is empty)."); checkClosed(); // Search for existent connection. for (InetSocketAddress endPoint : srvs) { assert endPoint != null; GridClientConnection conn = conns.get(endPoint); if (conn == null) continue; // Ignore closed connections. if (conn.closeIfIdle(cfg.getMaxConnectionIdleTime())) { closeIdle(); continue; } if (nodeId != null) nodeConns.put(nodeId, conn); return conn; } return connect(nodeId, srvs); } /** * Creates a connected facade and returns it. Called either from constructor or inside * a write lock. * * @param nodeId {@code UUID} of node for mapping with connection. * {@code null} if no need of mapping. * @param srvs List of server addresses that this method will try to connect to. * @return Established connection. * @throws GridServerUnreachableException If none of the servers can be reached. * @throws InterruptedException If connection was interrupted. */ protected GridClientConnection connect(@Nullable UUID nodeId, Collection<InetSocketAddress> srvs) throws GridServerUnreachableException, InterruptedException { if (srvs.isEmpty()) throw new GridServerUnreachableException("Failed to establish connection to the grid node (address " + "list is empty)."); Exception cause = null; for (InetSocketAddress srv : srvs) { try { return connect(nodeId, srv); } catch (InterruptedException e) { throw e; } catch (Exception e) { if (cause == null) cause = e; else if (log.isLoggable(INFO)) log.info("Unable to connect to grid node [srvAddr=" + srv + ", msg=" + e.getMessage() + ']'); } } assert cause != null; throw new GridServerUnreachableException("Failed to connect to any of the servers in list: " + srvs, cause); } /** * Create new connection to specified server. * * @param nodeId {@code UUID} of node for mapping with connection. * {@code null} if no need of mapping. * @param addr Remote socket to connect. * @return Established connection. * @throws IOException If connection failed. * @throws GridClientException If protocol error happened. * @throws InterruptedException If thread was interrupted before connection was established. */ protected GridClientConnection connect(@Nullable UUID nodeId, InetSocketAddress addr) throws IOException, GridClientException, InterruptedException { endpointStripedLock.lock(addr); try { GridClientConnection old = conns.get(addr); if (old != null) { if (old.isClosed()) { conns.remove(addr, old); if (nodeId != null) nodeConns.remove(nodeId, old); } else { if (nodeId != null) nodeConns.put(nodeId, old); return old; } } SecurityCredentials cred = null; try { if (cfg.getSecurityCredentialsProvider() != null) cred = cfg.getSecurityCredentialsProvider().credentials(); } catch (IgniteCheckedException e) { throw new GridClientException("Failed to obtain client credentials.", e); } GridClientConnection conn; if (cfg.getProtocol() == GridClientProtocol.TCP) { GridClientMarshaller marsh = cfg.getMarshaller(); try { conn = new GridClientNioTcpConnection(srv, clientId, addr, sslCtx, pingExecutor, cfg.getConnectTimeout(), cfg.getPingInterval(), cfg.getPingTimeout(), cfg.isTcpNoDelay(), marsh, marshId, top, cred, cfg.getUserAttributes()); } catch (GridClientException e) { if (marsh instanceof GridClientZipOptimizedMarshaller) { log.warning("Failed to connect with GridClientZipOptimizedMarshaller," + " trying to fallback to default marshaller: " + e); conn = new GridClientNioTcpConnection(srv, clientId, addr, sslCtx, pingExecutor, cfg.getConnectTimeout(), cfg.getPingInterval(), cfg.getPingTimeout(), cfg.isTcpNoDelay(), ((GridClientZipOptimizedMarshaller)marsh).defaultMarshaller(), marshId, top, cred, cfg.getUserAttributes()); } else throw e; } } else throw new GridServerUnreachableException("Failed to create client (protocol is not supported): " + cfg.getProtocol()); old = conns.putIfAbsent(addr, conn); assert old == null; if (nodeId != null) nodeConns.put(nodeId, conn); return conn; } finally { endpointStripedLock.unlock(addr); } } /** {@inheritDoc} */ @Override public void terminateConnection(GridClientConnection conn, GridClientNode node, Throwable e) { if (log.isLoggable(Level.FINE)) log.fine("Connection with remote node was terminated [node=" + node + ", srvAddr=" + conn.serverAddress() + ", errMsg=" + e.getMessage() + ']'); closeIdle(); conn.close(FAILED, false); } /** * Closes all opened connections. * * @param waitCompletion If {@code true} waits for all pending requests to be proceeded. */ @SuppressWarnings("TooBroadScope") @Override public void stop(boolean waitCompletion) { Collection<GridClientConnection> closeConns; if (closed) return; // Mark manager as closed. closed = true; // Remove all connections from cache. closeConns = new ArrayList<>(conns.values()); conns.clear(); nodeConns.clear(); // Close old connection outside the writer lock. for (GridClientConnection conn : closeConns) conn.close(CLIENT_CLOSED, waitCompletion); if (pingExecutor != null) GridClientUtils.shutdownNow(GridClientConnectionManager.class, pingExecutor, log); GridClientUtils.shutdownNow(GridClientConnectionManager.class, executor, log); if (srv != null) srv.stop(); } /** {@inheritDoc} */ @Override public GridClientConnection connection( Collection<InetSocketAddress> srvs ) throws GridClientException, InterruptedException { return connect(srvs, null); } /** * Returns connection to node using given server addresses. * * @param srvs Server addresses. * @param clo Client connection closure. * @return Established connection. * @throws GridClientException If failed. * @throws InterruptedException If was interrupted while waiting for connection to be established. */ private GridClientConnection connect( Collection<InetSocketAddress> srvs, @Nullable GridClientConnectionInClosure clo ) throws InterruptedException, GridClientException { GridClientException firstEx = null; for (int i = 0; i < INIT_RETRY_CNT; i++) { Collection<InetSocketAddress> srvsCp = new ArrayList<>(srvs); while (!srvsCp.isEmpty()) { GridClientConnection conn = null; try { conn = connect(null, srvsCp); if (clo != null) clo.apply(conn); return conn; } catch (GridServerUnreachableException e) { // No connection could be opened to any of initial addresses - exit to retry loop. assert conn == null : "GridClientConnectionResetException was thrown from GridClientConnection#topology"; if (firstEx == null) firstEx = e; break; } catch (GridClientConnectionResetException e) { // Connection was established but topology update failed - // trying other initial addresses if any. assert conn != null : "GridClientConnectionResetException was thrown from connect()"; if (firstEx == null) firstEx = e; if (!srvsCp.remove(conn.serverAddress())) // We have misbehaving collection or equals - just exit to avoid infinite loop. break; } } Thread.sleep(INIT_RETRY_INTERVAL); } for (GridClientConnection c : conns.values()) { conns.remove(c.serverAddress(), c); c.close(FAILED, false); } throw firstEx; } /** * Close all connections idling for more then * {@link GridClientConfiguration#getMaxConnectionIdleTime()} milliseconds. */ @SuppressWarnings("ForLoopReplaceableByForEach") private void closeIdle() { for (Iterator<Map.Entry<UUID, GridClientConnection>> it = nodeConns.entrySet().iterator(); it.hasNext(); ) { Map.Entry<UUID, GridClientConnection> entry = it.next(); GridClientConnection conn = entry.getValue(); if (conn.closeIfIdle(cfg.getMaxConnectionIdleTime())) { conns.remove(conn.serverAddress(), conn); nodeConns.remove(entry.getKey(), conn); } } for (GridClientConnection conn : conns.values()) if (conn.closeIfIdle(cfg.getMaxConnectionIdleTime())) conns.remove(conn.serverAddress(), conn); } /** * Checks and throws an exception if this client was closed. * * @throws GridClientClosedException If client was closed. */ private void checkClosed() throws GridClientClosedException { if (closed) throw new GridClientClosedException("Client was closed (no public methods of client can be used anymore)."); } /** */ private static class NioListener implements GridNioServerListener { /** */ private final Logger log; /** * @param log Logger. */ private NioListener(Logger log) { this.log = log; } /** {@inheritDoc} */ @Override public void onConnected(GridNioSession ses) { if (log.isLoggable(Level.FINE)) log.fine("Session connected: " + ses); } /** {@inheritDoc} */ @Override public void onDisconnected(GridNioSession ses, @Nullable Exception e) { if (log.isLoggable(Level.FINE)) log.fine("Session disconnected: " + ses); GridClientFutureAdapter<Boolean> handshakeFut = ses.removeMeta(GridClientNioTcpConnection.SES_META_HANDSHAKE); if (handshakeFut != null) handshakeFut.onDone( new GridClientConnectionResetException("Failed to perform handshake (connection failed).")); else { GridClientNioTcpConnection conn = ses.meta(GridClientNioTcpConnection.SES_META_CONN); if (conn != null) conn.close(FAILED, false); } } /** {@inheritDoc} */ @Override public void onMessageSent(GridNioSession ses, Object msg) { // No-op. } /** {@inheritDoc} */ @Override public void onMessage(GridNioSession ses, Object msg) { GridClientFutureAdapter<Boolean> handshakeFut = ses.removeMeta(GridClientNioTcpConnection.SES_META_HANDSHAKE); if (handshakeFut != null) { assert msg instanceof GridClientHandshakeResponse; handleHandshakeResponse(handshakeFut, (GridClientHandshakeResponse)msg); } else { GridClientNioTcpConnection conn = ses.meta(GridClientNioTcpConnection.SES_META_CONN); assert conn != null; if (msg instanceof GridClientPingPacket) conn.handlePingResponse(); else { try { conn.handleResponse((GridClientMessage)msg); } catch (IOException e) { log.log(Level.SEVERE, "Failed to parse response.", e); } } } } /** {@inheritDoc} */ @Override public void onFailure(FailureType failureType, Throwable failure) { // No-op. } /** * Handles client handshake response. * * @param handshakeFut Future. * @param msg A handshake response. */ private void handleHandshakeResponse(GridClientFutureAdapter<Boolean> handshakeFut, GridClientHandshakeResponse msg) { byte rc = msg.resultCode(); if (rc != GridClientHandshakeResponse.OK.resultCode()) { handshakeFut.onDone(new GridClientHandshakeException(rc, "Handshake failed due to internal error (see server log for more details).")); } else handshakeFut.onDone(true); } /** {@inheritDoc} */ @Override public void onSessionWriteTimeout(GridNioSession ses) { if (log.isLoggable(Level.FINE)) log.fine("Closing NIO session because of write timeout."); ses.close(); } /** {@inheritDoc} */ @Override public void onSessionIdleTimeout(GridNioSession ses) { if (log.isLoggable(Level.FINE)) log.fine("Closing NIO session because of idle timeout."); ses.close(); } } /** * Client connection in closure. */ @FunctionalInterface private static interface GridClientConnectionInClosure { /** * Closure body. * * @param conn Client connection. * @throws GridClientException If failed. */ void apply(GridClientConnection conn) throws GridClientException; } }
/* * Copyright @ 2017 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge; import org.eclipse.jetty.websocket.api.*; import org.jetbrains.annotations.*; import org.jitsi.utils.logging2.*; import org.jitsi.videobridge.datachannel.*; import org.jitsi.videobridge.datachannel.protocol.*; import org.jitsi.videobridge.message.*; import org.jitsi.videobridge.relay.*; import org.jitsi.videobridge.websocket.*; import org.json.simple.*; import java.lang.ref.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.function.*; import java.util.stream.*; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.jitsi.videobridge.VersionConfig.config; /** * Handles the functionality related to sending and receiving COLIBRI messages * for an {@link Endpoint}. Supports two underlying transport mechanisms -- * WebRTC data channels and {@code WebSocket}s. * * @author Boris Grozev */ public class EndpointMessageTransport extends AbstractEndpointMessageTransport implements DataChannelStack.DataChannelMessageListener, ColibriWebSocket.EventHandler { /** * The last accepted web-socket by this instance, if any. */ private ColibriWebSocket webSocket; /** * User to synchronize access to {@link #webSocket} */ private final Object webSocketSyncRoot = new Object(); /** * Whether the last active transport channel (i.e. the last to receive a * message from the remote endpoint) was the web socket (if {@code true}), * or the WebRTC data channel (if {@code false}). */ private boolean webSocketLastActive = false; private WeakReference<DataChannel> dataChannel = new WeakReference<>(null); private final Supplier<Videobridge.Statistics> statisticsSupplier; private final EndpointMessageTransportEventHandler eventHandler; private final AtomicInteger numOutgoingMessagesDropped = new AtomicInteger(0); /** * The number of sent message by type. */ private final Map<String, AtomicLong> sentMessagesCounts = new ConcurrentHashMap<>(); @NotNull private final Endpoint endpoint; /** * Initializes a new {@link EndpointMessageTransport} instance. * @param endpoint the associated {@link Endpoint}. * @param statisticsSupplier a {@link Supplier} which returns an instance * of {@link Videobridge.Statistics} which will * be used to update any stats generated by this * class */ EndpointMessageTransport( @NotNull Endpoint endpoint, Supplier<Videobridge.Statistics> statisticsSupplier, EndpointMessageTransportEventHandler eventHandler, Logger parentLogger) { super(parentLogger); this.endpoint = endpoint; this.statisticsSupplier = statisticsSupplier; this.eventHandler = eventHandler; } /** * {@inheritDoc} */ @Override protected void notifyTransportChannelConnected() { endpoint.endpointMessageTransportConnected(); eventHandler.endpointMessageTransportConnected(endpoint); } /** * {@inheritDoc} */ @Override public BridgeChannelMessage clientHello(ClientHelloMessage message) { // ClientHello was introduced for functional testing purposes. It // triggers a ServerHello response from Videobridge. The exchange // reveals (to the client) that the transport channel between the // remote endpoint and the Videobridge is operational. // We take care to send the reply using the same transport channel on // which we received the request.. return createServerHello(); } @Override public BridgeChannelMessage videoType(VideoTypeMessage videoTypeMessage) { endpoint.setVideoType(videoTypeMessage.getVideoType()); Conference conference = endpoint.getConference(); if (conference == null || conference.isExpired()) { getLogger().warn("Unable to forward VideoTypeMessage, conference is null or expired"); return null; } videoTypeMessage.setEndpointId(endpoint.getId()); /* Forward videoType messages to Octo. */ conference.sendMessage(videoTypeMessage, Collections.emptyList(), true); return null; } @Override public BridgeChannelMessage sourceVideoType(SourceVideoTypeMessage sourceVideoTypeMessage) { if (!MultiStreamConfig.config.getEnabled()) { return null; } String sourceName = sourceVideoTypeMessage.getSourceName(); if (getLogger().isDebugEnabled()) { getLogger().debug("Received video type of " + sourceName +": " + sourceVideoTypeMessage.getVideoType()); } endpoint.setVideoType(sourceName, sourceVideoTypeMessage.getVideoType()); Conference conference = endpoint.getConference(); if (conference == null || conference.isExpired()) { getLogger().warn("Unable to forward SourceVideoTypeMessage, conference is null or expired"); return null; } sourceVideoTypeMessage.setEndpointId(endpoint.getId()); /* Forward videoType messages to Octo. */ conference.sendMessage(sourceVideoTypeMessage, Collections.emptyList(), true); return null; } @Override public void unhandledMessage(BridgeChannelMessage message) { getLogger().warn("Received a message with an unexpected type: " + message.getType()); } /** * Sends a string via a particular transport channel. * @param dst the transport channel. * @param message the message to send. */ protected void sendMessage(Object dst, BridgeChannelMessage message) { super.sendMessage(dst, message); // Log message if (dst instanceof ColibriWebSocket) { sendMessage((ColibriWebSocket) dst, message); } else if (dst instanceof DataChannel) { sendMessage((DataChannel)dst, message); } else { throw new IllegalArgumentException("unknown transport:" + dst); } } /** * Sends a string via a particular {@link DataChannel}. * @param dst the data channel to send through. * @param message the message to send. */ private void sendMessage(DataChannel dst, BridgeChannelMessage message) { dst.sendString(message.toJson()); statisticsSupplier.get().totalDataChannelMessagesSent.incrementAndGet(); } /** * Sends a string via a particular {@link ColibriWebSocket} instance. * @param dst the {@link ColibriWebSocket} through which to send the message. * @param message the message to send. */ private void sendMessage(ColibriWebSocket dst, BridgeChannelMessage message) { RemoteEndpoint remote = dst.getRemote(); if (remote != null) { // We'll use the async version of sendString since this may be called // from multiple threads. It's just fire-and-forget though, so we // don't wait on the result remote.sendStringByFuture(message.toJson()); } statisticsSupplier.get().totalColibriWebSocketMessagesSent.incrementAndGet(); } @Override public void onDataChannelMessage(DataChannelMessage dataChannelMessage) { webSocketLastActive = false; statisticsSupplier.get().totalDataChannelMessagesReceived.incrementAndGet(); if (dataChannelMessage instanceof DataChannelStringMessage) { DataChannelStringMessage dataChannelStringMessage = (DataChannelStringMessage)dataChannelMessage; onMessage(dataChannel.get(), dataChannelStringMessage.data); } } /** * {@inheritDoc} */ @Override protected void sendMessage(@NotNull BridgeChannelMessage msg) { Object dst = getActiveTransportChannel(); if (dst == null) { getLogger().debug("No available transport channel, can't send a message"); numOutgoingMessagesDropped.incrementAndGet(); } else { sentMessagesCounts.computeIfAbsent( msg.getClass().getSimpleName(), (k) -> new AtomicLong()).incrementAndGet(); sendMessage(dst, msg); } } /** * @return the active transport channel for this * {@link EndpointMessageTransport} (either the {@link #webSocket}, or * the WebRTC data channel represented by a {@link DataChannel}). * </p> * The "active" channel is determined based on what channels are available, * and which one was the last to receive data. That is, if only one channel * is available, it will be returned. If two channels are available, the * last one to have received data will be returned. Otherwise, {@code null} * will be returned. */ //TODO(brian): seems like it'd be nice to have the websocket and datachannel // share a common parent class (or, at least, have a class that is returned // here and provides a common API but can wrap either a websocket or // datachannel) private Object getActiveTransportChannel() { DataChannel dataChannel = this.dataChannel.get(); ColibriWebSocket webSocket = this.webSocket; Object dst = null; if (webSocketLastActive) { dst = webSocket; } // Either the socket was not the last active channel, // or it has been closed. if (dst == null) { if (dataChannel != null && dataChannel.isReady()) { dst = dataChannel; } } // Maybe the WebRTC data channel is the last active, but it is not // currently available. If so, and a web-socket is available -- use it. if (dst == null && webSocket != null) { dst = webSocket; } return dst; } @Override public boolean isConnected() { return getActiveTransportChannel() != null; } /** * {@inheritDoc} */ @Override public void webSocketConnected(ColibriWebSocket ws) { synchronized (webSocketSyncRoot) { // If we already have a web-socket, discard it and use the new one. if (webSocket != null) { Session session = webSocket.getSession(); if (session != null) { session.close(200, "replaced"); } } webSocket = ws; webSocketLastActive = true; sendMessage(ws, createServerHello()); } try { notifyTransportChannelConnected(); } catch (Exception e) { getLogger().warn("Caught an exception in notifyTransportConnected", e); } } private ServerHelloMessage createServerHello() { if (config.announceVersion()) { return new ServerHelloMessage(endpoint.getConference().getVideobridge().getVersion().toString()); } else { return new ServerHelloMessage(); } } /** * {@inheritDoc} */ @Override public void webSocketClosed(ColibriWebSocket ws, int statusCode, String reason) { synchronized (webSocketSyncRoot) { if (ws != null && ws.equals(webSocket)) { webSocket = null; webSocketLastActive = false; getLogger().debug(() -> "Web socket closed, statusCode " + statusCode + " ( " + reason + ")."); } } } /** * {@inheritDoc} */ @Override public void close() { synchronized (webSocketSyncRoot) { if (webSocket != null) { // 410 Gone indicates that the resource requested is no longer // available and will not be available again. webSocket.getSession().close(410, "replaced"); webSocket = null; getLogger().debug(() -> "Endpoint expired, closed colibri web-socket."); } } } /** * {@inheritDoc} */ @Override public void webSocketTextReceived(ColibriWebSocket ws, String message) { if (ws == null || !ws.equals(webSocket)) { getLogger().warn("Received text from an unknown web socket."); return; } statisticsSupplier.get().totalColibriWebSocketMessagesReceived.incrementAndGet(); webSocketLastActive = true; onMessage(ws, message); } /** * Sets the data channel for this endpoint. * @param dataChannel the {@link DataChannel} to use for this transport */ void setDataChannel(DataChannel dataChannel) { DataChannel prevDataChannel = this.dataChannel.get(); if (prevDataChannel == null) { this.dataChannel = new WeakReference<>(dataChannel); // We install the handler first, otherwise the 'ready' might fire after we check it but before we // install the handler dataChannel.onDataChannelEvents(this::notifyTransportChannelConnected); if (dataChannel.isReady()) { notifyTransportChannelConnected(); } dataChannel.onDataChannelMessage(this); } else if (prevDataChannel == dataChannel) { //TODO: i think we should be able to ensure this doesn't happen, // so throwing for now. if there's a good // reason for this, we can make this a no-op throw new Error("Re-setting the same data channel"); } else { throw new Error("Overwriting a previous data channel!"); } } @SuppressWarnings("unchecked") @Override public JSONObject getDebugState() { JSONObject debugState = super.getDebugState(); debugState.put("numOutgoingMessagesDropped", numOutgoingMessagesDropped.get()); JSONObject sentCounts = new JSONObject(); sentCounts.putAll(sentMessagesCounts); debugState.put("sent_counts", sentCounts); return debugState; } /** * Notifies this {@code Endpoint} that a {@link SelectedEndpointsMessage} * has been received. * * @param message the message that was received. */ @Override public BridgeChannelMessage selectedEndpoint(SelectedEndpointMessage message) { String newSelectedEndpointID = message.getSelectedEndpoint(); List<String> newSelectedIDs = isBlank(newSelectedEndpointID) ? Collections.emptyList() : Collections.singletonList(newSelectedEndpointID); selectedEndpoints(new SelectedEndpointsMessage(newSelectedIDs)); return null; } /** * Notifies this {@code Endpoint} that a {@link SelectedEndpointsMessage} * has been received. * * @param message the message that was received. * @deprecated use receiverVideoConstraints, selecting endpoints will not be supported in the multi-stream mode */ @Override @Deprecated public BridgeChannelMessage selectedEndpoints(SelectedEndpointsMessage message) { List<String> newSelectedEndpoints = new ArrayList<>(message.getSelectedEndpoints()); getLogger().debug(() -> "Selected " + newSelectedEndpoints); endpoint.setSelectedEndpoints(newSelectedEndpoints); return null; } @Nullable @Override public BridgeChannelMessage receiverVideoConstraints(@NotNull ReceiverVideoConstraintsMessage message) { endpoint.setBandwidthAllocationSettings(message); return null; } /** * Notifies this {@code Endpoint} that a * {@link ReceiverVideoConstraintMessage} has been received * * @param message the message that was received. */ @Override public BridgeChannelMessage receiverVideoConstraint(ReceiverVideoConstraintMessage message) { int maxFrameHeight = message.getMaxFrameHeight(); getLogger().debug( () -> "Received a maxFrameHeight video constraint from " + endpoint.getId() + ": " + maxFrameHeight); endpoint.setMaxFrameHeight(maxFrameHeight); return null; } /** * Notifies this {@code Endpoint} that a {@link LastNMessage} has been * received. * * @param message the message that was received. */ @Override public BridgeChannelMessage lastN(LastNMessage message) { endpoint.setLastN(message.getLastN()); return null; } /** * Handles an opaque message from this {@code Endpoint} that should be forwarded to either: a) another client in * this conference (1:1 message) or b) all other clients in this conference (broadcast message). * * @param message the message that was received from the endpoint. */ @Override public BridgeChannelMessage endpointMessage(EndpointMessage message) { // First insert/overwrite the "from" to prevent spoofing. String from = endpoint.getId(); message.setFrom(from); Conference conference = endpoint.getConference(); if (conference == null || conference.isExpired()) { getLogger().warn("Unable to send EndpointMessage, conference is null or expired"); return null; } if (message.isBroadcast()) { // Broadcast message to all local endpoints + octo. List<Endpoint> targets = new LinkedList<>(conference.getLocalEndpoints()); targets.remove(endpoint); conference.sendMessage(message, targets, /* sendToOcto */ true); } else { // 1:1 message String to = message.getTo(); AbstractEndpoint targetEndpoint = conference.getEndpoint(to); if (targetEndpoint instanceof Endpoint) { ((Endpoint)targetEndpoint).sendMessage(message); } else if (targetEndpoint instanceof RelayedEndpoint) { ((RelayedEndpoint)targetEndpoint).getRelay().sendMessage(message); } else if (targetEndpoint != null) { conference.sendMessage(message, Collections.emptyList(), /* sendToOcto */ true); } else { getLogger().warn("Unable to find endpoint to send EndpointMessage to: " + to); } } return null; } /** * Handles an endpoint statistics message from this {@code Endpoint} that should be forwarded to * other endpoints as appropriate, and also to Octo. * * @param message the message that was received from the endpoint. */ @Override public BridgeChannelMessage endpointStats(@NotNull EndpointStats message) { // First insert/overwrite the "from" to prevent spoofing. String from = endpoint.getId(); message.setFrom(from); Conference conference = endpoint.getConference(); if (conference == null || conference.isExpired()) { getLogger().warn("Unable to send EndpointStats, conference is null or expired"); return null; } List<Endpoint> targets = conference.getLocalEndpoints().stream() .filter((ep) -> ep != endpoint && ep.wantsStatsFrom(endpoint)) .collect(Collectors.toList()); conference.sendMessage(message, targets, true); return null; } }
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.data; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import com.google.common.html.types.SafeHtml; import com.google.common.html.types.SafeHtmlBuilder; import com.google.common.html.types.SafeHtmlProto; import com.google.common.html.types.SafeHtmls; import com.google.common.html.types.SafeScript; import com.google.common.html.types.SafeScriptProto; import com.google.common.html.types.SafeScripts; import com.google.common.html.types.SafeStyleSheet; import com.google.common.html.types.SafeStyleSheetProto; import com.google.common.html.types.SafeStyleSheets; import com.google.common.html.types.SafeUrl; import com.google.common.html.types.SafeUrlProto; import com.google.common.html.types.SafeUrls; import com.google.template.soy.data.SanitizedContent.ContentKind; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for SanitizedContents utility class. * */ @RunWith(JUnit4.class) public class SanitizedContentsTest { @Test public void testUnsanitizedText() { assertThat(SanitizedContents.unsanitizedText("Hello World")) .isEqualTo(SanitizedContent.create("Hello World", ContentKind.TEXT, null)); } @Test public void testConcatCombinesHtml() throws Exception { String text1 = "one"; String text2 = "two"; String text3 = "three"; SanitizedContent content1 = SanitizedContent.create(text1, ContentKind.HTML, null); SanitizedContent content2 = SanitizedContent.create(text2, ContentKind.HTML, null); SanitizedContent content3 = SanitizedContent.create(text3, ContentKind.HTML, null); assertThat(SanitizedContents.concatHtml(content1, content2, content3)) .isEqualTo(SanitizedContent.create(text1 + text2 + text3, ContentKind.HTML, null)); } @Test public void testConcatReturnsEmpty() throws Exception { assertThat(SanitizedContents.concatHtml()) .isEqualTo(SanitizedContent.create("", ContentKind.HTML, Dir.NEUTRAL)); } @Test public void testConcatThrowsExceptionOnDifferentNonHtml() throws Exception { try { SanitizedContents.concatHtml( SanitizedContents.emptyString(ContentKind.HTML), SanitizedContents.emptyString(ContentKind.CSS)); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Can only concat HTML"); } } @Test public void testConcatCombinesHtmlDir() throws Exception { SanitizedContent EMPTY_HTML = SanitizedContents.emptyString(ContentKind.HTML); SanitizedContent LTR_HTML = SanitizedContent.create(".", ContentKind.HTML, Dir.LTR); SanitizedContent RTL_HTML = SanitizedContent.create(".", ContentKind.HTML, Dir.RTL); SanitizedContent NEUTRAL_HTML = SanitizedContent.create(".", ContentKind.HTML, Dir.NEUTRAL); SanitizedContent UNKNOWN_DIR_HTML = SanitizedContent.create(".", ContentKind.HTML, null); // empty -> neutral assertThat(SanitizedContents.concatHtml(EMPTY_HTML).getContentDirection()) .isEqualTo(Dir.NEUTRAL); // x -> x assertThat(SanitizedContents.concatHtml(LTR_HTML).getContentDirection()).isEqualTo(Dir.LTR); assertThat(SanitizedContents.concatHtml(RTL_HTML).getContentDirection()).isEqualTo(Dir.RTL); assertThat(SanitizedContents.concatHtml(NEUTRAL_HTML).getContentDirection()) .isEqualTo(Dir.NEUTRAL); assertThat(SanitizedContents.concatHtml(UNKNOWN_DIR_HTML).getContentDirection()).isNull(); // x + unknown -> unknown assertThat(SanitizedContents.concatHtml(LTR_HTML, UNKNOWN_DIR_HTML).getContentDirection()) .isNull(); assertThat(SanitizedContents.concatHtml(UNKNOWN_DIR_HTML, LTR_HTML).getContentDirection()) .isNull(); assertThat(SanitizedContents.concatHtml(RTL_HTML, UNKNOWN_DIR_HTML).getContentDirection()) .isNull(); assertThat(SanitizedContents.concatHtml(UNKNOWN_DIR_HTML, RTL_HTML).getContentDirection()) .isNull(); assertThat(SanitizedContents.concatHtml(NEUTRAL_HTML, UNKNOWN_DIR_HTML).getContentDirection()) .isNull(); assertThat(SanitizedContents.concatHtml(UNKNOWN_DIR_HTML, NEUTRAL_HTML).getContentDirection()) .isNull(); assertThat( SanitizedContents.concatHtml(UNKNOWN_DIR_HTML, UNKNOWN_DIR_HTML).getContentDirection()) .isNull(); // x + neutral -> x assertThat(SanitizedContents.concatHtml(LTR_HTML, NEUTRAL_HTML).getContentDirection()) .isEqualTo(Dir.LTR); assertThat(SanitizedContents.concatHtml(NEUTRAL_HTML, LTR_HTML).getContentDirection()) .isEqualTo(Dir.LTR); assertThat(SanitizedContents.concatHtml(RTL_HTML, NEUTRAL_HTML).getContentDirection()) .isEqualTo(Dir.RTL); assertThat(SanitizedContents.concatHtml(NEUTRAL_HTML, RTL_HTML).getContentDirection()) .isEqualTo(Dir.RTL); assertThat(SanitizedContents.concatHtml(NEUTRAL_HTML, NEUTRAL_HTML).getContentDirection()) .isEqualTo(Dir.NEUTRAL); // x + x -> x assertThat(SanitizedContents.concatHtml(LTR_HTML, LTR_HTML).getContentDirection()) .isEqualTo(Dir.LTR); assertThat(SanitizedContents.concatHtml(RTL_HTML, RTL_HTML).getContentDirection()) .isEqualTo(Dir.RTL); // LTR + RTL -> unknown assertThat(SanitizedContents.concatHtml(LTR_HTML, RTL_HTML).getContentDirection()).isNull(); assertThat(SanitizedContents.concatHtml(LTR_HTML, RTL_HTML).getContentDirection()).isNull(); } private void assertResourceNameValid(boolean valid, String resourceName, ContentKind kind) { try { SanitizedContents.pretendValidateResource(resourceName, kind); assertWithMessage("No exception was thrown, but wasn't expected to be valid.") .that(valid) .isTrue(); } catch (IllegalArgumentException e) { assertWithMessage("Exception was thrown, but was expected to be valid.") .that(valid) .isFalse(); } } @Test public void testPretendValidateResource() { // Correct resources. assertResourceNameValid(true, "test.js", ContentKind.JS); assertResourceNameValid(true, "/test/foo.bar.js", ContentKind.JS); assertResourceNameValid(true, "test.html", ContentKind.HTML); assertResourceNameValid(true, "test.svg", ContentKind.HTML); assertResourceNameValid(true, "test.css", ContentKind.CSS); // Wrong resource kind. assertResourceNameValid(false, "test.css", ContentKind.HTML); assertResourceNameValid(false, "test.html", ContentKind.JS); assertResourceNameValid(false, "test.js", ContentKind.CSS); // No file extensions supported for these kinds. assertResourceNameValid(false, "test.attributes", ContentKind.ATTRIBUTES); // Missing extension entirely. assertResourceNameValid(false, "test", ContentKind.JS); } @Test public void testGetDefaultDir() { assertThat(SanitizedContents.getDefaultDir(ContentKind.JS)).isEqualTo(Dir.LTR); assertThat(SanitizedContents.getDefaultDir(ContentKind.CSS)).isEqualTo(Dir.LTR); assertThat(SanitizedContents.getDefaultDir(ContentKind.ATTRIBUTES)).isEqualTo(Dir.LTR); assertThat(SanitizedContents.getDefaultDir(ContentKind.URI)).isEqualTo(Dir.LTR); assertThat(SanitizedContents.getDefaultDir(ContentKind.TEXT)).isNull(); assertThat(SanitizedContents.getDefaultDir(ContentKind.HTML)).isNull(); } @Test public void testConstantUri() { // Passing case. We actually can't test a failing case because it won't compile. SanitizedContent uri = SanitizedContents.constantUri("itms://blahblah"); assertThat(uri.getContent()).isEqualTo("itms://blahblah"); assertThat(uri.getContentKind()).isEqualTo(ContentKind.URI); assertThat(uri.getContentDirection()) .isEqualTo(SanitizedContents.getDefaultDir(ContentKind.URI)); } @Test public void testCommonSafeHtmlTypeConversions() { final String helloWorldHtml = "Hello <em>World</em>"; final SafeHtml safeHtml = SafeHtmls.concat( SafeHtmls.htmlEscape("Hello "), new SafeHtmlBuilder("em").escapeAndAppendContent("World").build()); final SanitizedContent sanitizedHtml = SanitizedContents.fromSafeHtml(safeHtml); assertThat(sanitizedHtml.getContentKind()).isEqualTo(ContentKind.HTML); assertThat(sanitizedHtml.getContent()).isEqualTo(helloWorldHtml); assertThat(sanitizedHtml.toSafeHtml()).isEqualTo(safeHtml); // Proto conversions. final SafeHtmlProto safeHtmlProto = sanitizedHtml.toSafeHtmlProto(); assertThat(SafeHtmls.fromProto(safeHtmlProto)).isEqualTo(safeHtml); assertThat(SanitizedContents.fromSafeHtmlProto(safeHtmlProto).getContent()) .isEqualTo(helloWorldHtml); } @Test public void testCommonSafeScriptTypeConversions() { final String testScript = "window.alert('hello');"; final SafeScript safeScript = SafeScripts.fromConstant(testScript); final SanitizedContent sanitizedScript = SanitizedContents.fromSafeScript(safeScript); assertThat(sanitizedScript.getContentKind()).isEqualTo(ContentKind.JS); assertThat(sanitizedScript.getContent()).isEqualTo(testScript); assertThat(sanitizedScript.getContent()).isEqualTo(safeScript.getSafeScriptString()); // Proto conversions. final SafeScriptProto safeScriptProto = SafeScripts.toProto(safeScript); assertThat(SafeScripts.fromProto(safeScriptProto)).isEqualTo(safeScript); assertThat(SanitizedContents.fromSafeScriptProto(safeScriptProto).getContent()) .isEqualTo(testScript); } @Test public void testCommonSafeStyleSheetTypeConversions() { final String testCss = "div { display: none; }"; final SafeStyleSheet safeCss = SafeStyleSheets.fromConstant(testCss); final SanitizedContent sanitizedCss = SanitizedContents.fromSafeStyleSheet(safeCss); assertThat(sanitizedCss.getContentKind()).isEqualTo(ContentKind.CSS); assertThat(sanitizedCss.getContent()).isEqualTo(testCss); assertThat(sanitizedCss.toSafeStyleSheet()).isEqualTo(safeCss); // Proto conversions. final SafeStyleSheetProto safeCssProto = sanitizedCss.toSafeStyleSheetProto(); assertThat(SafeStyleSheets.fromProto(safeCssProto)).isEqualTo(safeCss); assertThat(SanitizedContents.fromSafeStyleSheetProto(safeCssProto).getContent()) .isEqualTo(testCss); } @Test public void testCommonSafeUrlTypeConversions() { final String testUrl = "http://blahblah"; final SanitizedContent sanitizedConstantUri = SanitizedContents.constantUri(testUrl); final SafeUrl safeUrl = SafeUrls.fromConstant(testUrl); final SanitizedContent sanitizedUrl = SanitizedContents.fromSafeUrl(safeUrl); assertThat(sanitizedUrl.getContentKind()).isEqualTo(ContentKind.URI); assertThat(sanitizedUrl.getContent()).isEqualTo(testUrl); assertThat(sanitizedUrl).isEqualTo(sanitizedConstantUri); // Proto conversions. final SafeUrlProto safeUrlProto = SafeUrls.toProto(safeUrl); final SanitizedContent sanitizedUrlProto = SanitizedContents.fromSafeUrlProto(safeUrlProto); assertThat(sanitizedUrlProto.getContent()).isEqualTo(testUrl); assertThat(sanitizedUrlProto).isEqualTo(sanitizedConstantUri); } @Test public void testWrongContentKindThrows_html() { final SanitizedContent notHtml = UnsafeSanitizedContentOrdainer.ordainAsSafe("not HTML", ContentKind.CSS); try { notHtml.toSafeHtml(); fail("Should have thrown on SanitizedContent of kind other than HTML"); } catch (IllegalStateException expected) { } try { notHtml.toSafeHtmlProto(); fail("Should have thrown on SanitizedContent of kind other than HTML"); } catch (IllegalStateException expected) { } } @Test public void testWrongContentKindThrows_script() { final SanitizedContent notJs = UnsafeSanitizedContentOrdainer.ordainAsSafe("not JS", ContentKind.URI); try { notJs.toSafeScriptProto(); fail("Should have thrown on SanitizedContent of kind other than JS"); } catch (IllegalStateException expected) { } } @Test public void testWrongContentKindThrows_css() { final SanitizedContent notCss = UnsafeSanitizedContentOrdainer.ordainAsSafe("not CSS", ContentKind.HTML); try { notCss.toSafeStyleProto(); fail("Should have thrown on SanitizedContent of kind other than CSS"); } catch (IllegalStateException expected) { } try { notCss.toSafeStyleSheet(); fail("Should have thrown on SanitizedContent of kind other than CSS"); } catch (IllegalStateException expected) { } try { notCss.toSafeStyleSheetProto(); fail("Should have thrown on SanitizedContent of kind other than CSS"); } catch (IllegalStateException expected) { } } @Test public void testWrongContentKindThrows_uri() { final SanitizedContent notUri = UnsafeSanitizedContentOrdainer.ordainAsSafe("not URI", ContentKind.HTML); try { notUri.toSafeUrlProto(); fail("Should have thrown on SanitizedContent of kind other than URI"); } catch (IllegalStateException expected) { } try { notUri.toTrustedResourceUrlProto(); fail("Should have thrown on SanitizedContent of kind other than URI"); } catch (IllegalStateException expected) { } } @Test public void testInvalidStyleSheetContentThrows() { for (String css : new String[] { "display: none;", "{ display: none; }", "/* a comment */", "@import url('test.css');" }) { final SanitizedContent cssStyle = UnsafeSanitizedContentOrdainer.ordainAsSafe(css, ContentKind.CSS); try { cssStyle.toSafeStyleSheet(); fail("Should have thrown on CSS SanitizedContent with invalid stylesheet:" + css); } catch (IllegalStateException expected) { } try { cssStyle.toSafeStyleSheetProto(); fail("Should have thrown on CSS SanitizedContent with invalid stylesheet:" + css); } catch (IllegalStateException expected) { } } } }
/* * Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.wso2.carbon.registry.core.jdbc.dataaccess; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.ndatasource.rdbms.RDBMSConfiguration; import org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource; import org.wso2.carbon.registry.core.config.DataBaseConfiguration; import org.wso2.carbon.registry.core.dataaccess.*; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.DatabaseConstants; import org.wso2.carbon.registry.core.dataaccess.QueryProcessor; import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; /** * An implementation of {@link DataAccessManager} to access a back-end * JDBC-based database. */ public class JDBCDataAccessManager implements DataAccessManager { private static final Log log = LogFactory .getLog(JDBCDataAccessManager.class); private DataSource dataSource; private static ClusterLock clusterLock = new JDBCClusterLock(); private static DatabaseTransaction databaseTransaction = new JDBCDatabaseTransaction(); private static DAOManager daoManager = new JDBCDAOManager(); private static Map<String, DataSource> dataSources = new HashMap<String, DataSource>(); /** * Constructor accepting a JDBC data source. * * @param dataSource * the JDBC data source. */ public JDBCDataAccessManager(DataSource dataSource) { this.dataSource = dataSource; } /** * Creates a JDBC Data Access Manager from the given database configuration. * * @param dataBaseConfiguration * the database configuration. */ public JDBCDataAccessManager(DataBaseConfiguration dataBaseConfiguration) { final String dataSourceName = dataBaseConfiguration.getDataSourceName(); if (dataSourceName != null) { try { dataSource = dataSources.get(dataSourceName); if (dataSource == null) { Context context = new InitialContext(); dataSource = (DataSource) context.lookup(dataSourceName); dataSources.put(dataSourceName, dataSource); } } catch (NamingException e) { // Problems! log.error("Couldn't find dataSource '" + dataSourceName + "'", e); } } else { String configName = dataBaseConfiguration.getConfigName(); dataSource = dataSources.get(configName); if (dataSource == null) { dataSource = buildDataSource(dataBaseConfiguration); dataSources.put(configName, dataSource); } } } public ClusterLock getClusterLock() { return clusterLock; } public TransactionManager getTransactionManager() { return new JDBCTransactionManager(this); } public DatabaseTransaction getDatabaseTransaction() { return databaseTransaction; } public QueryProcessor getQueryProcessor() { return new SQLQueryProcessor(this); } public DAOManager getDAOManager() { return daoManager; } public void createDatabase() throws RegistryException { DatabaseCreator databaseCreator = new DatabaseCreator(getDataSource()); try { databaseCreator.createRegistryDatabase(); } catch (Exception e) { String msg = "Error in creating the database"; throw new RegistryException(msg, e); } } public boolean isDatabaseExisting() { try { if (log.isTraceEnabled()) { log.trace("Running a query to test the database tables existence."); } // check whether the tables are already created with a query Connection conn = dataSource.getConnection(); String sql = "SELECT REG_PATH_ID FROM REG_PATH WHERE REG_PATH_VALUE='/'"; Statement statement = null; try { statement = conn.createStatement(); ResultSet rs = statement.executeQuery(sql); if (rs != null) { rs.close(); } } finally { try { if (statement != null) { statement.close(); } } finally { if (conn != null) { conn.close(); } } } } catch (SQLException e) { return false; } return true; } /** * Method to retrieve the JDBC data source. * * @return the JDBC data source. */ public DataSource getDataSource() { return dataSource; } /** * Method to build a data source from a given database configuration. * * @param config * the database configuration. * * @return the built data source. */ public static DataSource buildDataSource(DataBaseConfiguration config) { RDBMSConfiguration dsConf = new RDBMSConfiguration(); dsConf.setUrl(config.getDbUrl()); dsConf.setDriverClassName(config.getDriverName()); dsConf.setUsername(config.getUserName()); dsConf.setPassword(config.getResolvedPassword()); if (config.getTestWhileIdle() != null) { dsConf.setTestWhileIdle(Boolean.parseBoolean(config .getTestWhileIdle())); } if (config.getTimeBetweenEvictionRunsMillis() != null) { dsConf.setTimeBetweenEvictionRunsMillis(Integer .parseInt(config.getTimeBetweenEvictionRunsMillis())); } if (config.getMinEvictableIdleTimeMillis() != null) { dsConf.setMinEvictableIdleTimeMillis(Integer.parseInt(config .getMinEvictableIdleTimeMillis())); } if (config.getNumTestsPerEvictionRun() != null) { dsConf.setNumTestsPerEvictionRun(Integer.parseInt(config .getNumTestsPerEvictionRun())); } if (config.getMaxActive() != null) { dsConf .setMaxActive(Integer.parseInt(config.getMaxActive())); } else { dsConf.setMaxActive(DatabaseConstants.DEFAULT_MAX_ACTIVE); } if (config.getMaxWait() != null) { dsConf.setMaxWait(Integer.parseInt(config.getMaxWait())); } else { dsConf.setMaxWait(DatabaseConstants.DEFAULT_MAX_WAIT); } if (config.getMaxIdle() != null) { dsConf.setMaxIdle(Integer.parseInt(config.getMaxIdle())); } if (config.getMinIdle() != null) { dsConf.setMinIdle(Integer.parseInt(config.getMinIdle())); } else { dsConf.setMinIdle(DatabaseConstants.DEFAULT_MIN_IDLE); } if (config.getValidationQuery() != null) { dsConf.setValidationQuery(config.getValidationQuery()); } try { return new RDBMSDataSource(dsConf).getDataSource(); } catch (Exception e) { throw new RuntimeException("Error in creating data source for the registry: " + e.getMessage(), e); } } }
/** * * Copyright (c) Microsoft and contributors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.azure.management.sql.models; import com.microsoft.windowsazure.core.LazyArrayList; import java.util.ArrayList; import java.util.Calendar; /** * Represents the properties of a Service Tier Advisor. */ public class ServiceTierAdvisorProperties { private Double activeTimeRatio; /** * Optional. Gets the activeTimeRatio for service tier advisor. * @return The ActiveTimeRatio value. */ public Double getActiveTimeRatio() { return this.activeTimeRatio; } /** * Optional. Gets the activeTimeRatio for service tier advisor. * @param activeTimeRatioValue The ActiveTimeRatio value. */ public void setActiveTimeRatio(final Double activeTimeRatioValue) { this.activeTimeRatio = activeTimeRatioValue; } private Double avgDtu; /** * Optional. Gets or sets avgDtu for service tier advisor. * @return The AvgDtu value. */ public Double getAvgDtu() { return this.avgDtu; } /** * Optional. Gets or sets avgDtu for service tier advisor. * @param avgDtuValue The AvgDtu value. */ public void setAvgDtu(final Double avgDtuValue) { this.avgDtu = avgDtuValue; } private double confidence; /** * Optional. Gets or sets confidence for service tier advisor. * @return The Confidence value. */ public double getConfidence() { return this.confidence; } /** * Optional. Gets or sets confidence for service tier advisor. * @param confidenceValue The Confidence value. */ public void setConfidence(final double confidenceValue) { this.confidence = confidenceValue; } private String currentServiceLevelObjective; /** * Optional. Gets or sets currentServiceLevelObjective for service tier * advisor. * @return The CurrentServiceLevelObjective value. */ public String getCurrentServiceLevelObjective() { return this.currentServiceLevelObjective; } /** * Optional. Gets or sets currentServiceLevelObjective for service tier * advisor. * @param currentServiceLevelObjectiveValue The CurrentServiceLevelObjective * value. */ public void setCurrentServiceLevelObjective(final String currentServiceLevelObjectiveValue) { this.currentServiceLevelObjective = currentServiceLevelObjectiveValue; } private String currentServiceLevelObjectiveId; /** * Optional. Gets or sets currentServiceLevelObjectiveId for service tier * advisor. * @return The CurrentServiceLevelObjectiveId value. */ public String getCurrentServiceLevelObjectiveId() { return this.currentServiceLevelObjectiveId; } /** * Optional. Gets or sets currentServiceLevelObjectiveId for service tier * advisor. * @param currentServiceLevelObjectiveIdValue The * CurrentServiceLevelObjectiveId value. */ public void setCurrentServiceLevelObjectiveId(final String currentServiceLevelObjectiveIdValue) { this.currentServiceLevelObjectiveId = currentServiceLevelObjectiveIdValue; } private String databaseSizeBasedRecommendationServiceLevelObjective; /** * Optional. Gets or sets * databaseSizeBasedRecommendationServiceLevelObjective for service tier * advisor. * @return The DatabaseSizeBasedRecommendationServiceLevelObjective value. */ public String getDatabaseSizeBasedRecommendationServiceLevelObjective() { return this.databaseSizeBasedRecommendationServiceLevelObjective; } /** * Optional. Gets or sets * databaseSizeBasedRecommendationServiceLevelObjective for service tier * advisor. * @param databaseSizeBasedRecommendationServiceLevelObjectiveValue The * DatabaseSizeBasedRecommendationServiceLevelObjective value. */ public void setDatabaseSizeBasedRecommendationServiceLevelObjective(final String databaseSizeBasedRecommendationServiceLevelObjectiveValue) { this.databaseSizeBasedRecommendationServiceLevelObjective = databaseSizeBasedRecommendationServiceLevelObjectiveValue; } private String databaseSizeBasedRecommendationServiceLevelObjectiveId; /** * Optional. Gets or sets * databaseSizeBasedRecommendationServiceLevelObjectiveId for service tier * advisor. * @return The DatabaseSizeBasedRecommendationServiceLevelObjectiveId value. */ public String getDatabaseSizeBasedRecommendationServiceLevelObjectiveId() { return this.databaseSizeBasedRecommendationServiceLevelObjectiveId; } /** * Optional. Gets or sets * databaseSizeBasedRecommendationServiceLevelObjectiveId for service tier * advisor. * @param databaseSizeBasedRecommendationServiceLevelObjectiveIdValue The * DatabaseSizeBasedRecommendationServiceLevelObjectiveId value. */ public void setDatabaseSizeBasedRecommendationServiceLevelObjectiveId(final String databaseSizeBasedRecommendationServiceLevelObjectiveIdValue) { this.databaseSizeBasedRecommendationServiceLevelObjectiveId = databaseSizeBasedRecommendationServiceLevelObjectiveIdValue; } private String disasterPlanBasedRecommendationServiceLevelObjective; /** * Optional. Gets or sets * disasterPlanBasedRecommendationServiceLevelObjective for service tier * advisor. * @return The DisasterPlanBasedRecommendationServiceLevelObjective value. */ public String getDisasterPlanBasedRecommendationServiceLevelObjective() { return this.disasterPlanBasedRecommendationServiceLevelObjective; } /** * Optional. Gets or sets * disasterPlanBasedRecommendationServiceLevelObjective for service tier * advisor. * @param disasterPlanBasedRecommendationServiceLevelObjectiveValue The * DisasterPlanBasedRecommendationServiceLevelObjective value. */ public void setDisasterPlanBasedRecommendationServiceLevelObjective(final String disasterPlanBasedRecommendationServiceLevelObjectiveValue) { this.disasterPlanBasedRecommendationServiceLevelObjective = disasterPlanBasedRecommendationServiceLevelObjectiveValue; } private String disasterPlanBasedRecommendationServiceLevelObjectiveId; /** * Optional. Gets or sets * disasterPlanBasedRecommendationServiceLevelObjectiveId for service tier * advisor. * @return The DisasterPlanBasedRecommendationServiceLevelObjectiveId value. */ public String getDisasterPlanBasedRecommendationServiceLevelObjectiveId() { return this.disasterPlanBasedRecommendationServiceLevelObjectiveId; } /** * Optional. Gets or sets * disasterPlanBasedRecommendationServiceLevelObjectiveId for service tier * advisor. * @param disasterPlanBasedRecommendationServiceLevelObjectiveIdValue The * DisasterPlanBasedRecommendationServiceLevelObjectiveId value. */ public void setDisasterPlanBasedRecommendationServiceLevelObjectiveId(final String disasterPlanBasedRecommendationServiceLevelObjectiveIdValue) { this.disasterPlanBasedRecommendationServiceLevelObjectiveId = disasterPlanBasedRecommendationServiceLevelObjectiveIdValue; } private Double maxDtu; /** * Optional. Gets or sets maxDtu for service tier advisor. * @return The MaxDtu value. */ public Double getMaxDtu() { return this.maxDtu; } /** * Optional. Gets or sets maxDtu for service tier advisor. * @param maxDtuValue The MaxDtu value. */ public void setMaxDtu(final Double maxDtuValue) { this.maxDtu = maxDtuValue; } private Double maxSizeInGB; /** * Optional. Gets or sets maxSizeInGB for service tier advisor. * @return The MaxSizeInGB value. */ public Double getMaxSizeInGB() { return this.maxSizeInGB; } /** * Optional. Gets or sets maxSizeInGB for service tier advisor. * @param maxSizeInGBValue The MaxSizeInGB value. */ public void setMaxSizeInGB(final Double maxSizeInGBValue) { this.maxSizeInGB = maxSizeInGBValue; } private Double minDtu; /** * Optional. Gets or sets minDtu for service tier advisor. * @return The MinDtu value. */ public Double getMinDtu() { return this.minDtu; } /** * Optional. Gets or sets minDtu for service tier advisor. * @param minDtuValue The MinDtu value. */ public void setMinDtu(final Double minDtuValue) { this.minDtu = minDtuValue; } private Calendar observationPeriodEnd; /** * Optional. Gets the observation period start. * @return The ObservationPeriodEnd value. */ public Calendar getObservationPeriodEnd() { return this.observationPeriodEnd; } /** * Optional. Gets the observation period start. * @param observationPeriodEndValue The ObservationPeriodEnd value. */ public void setObservationPeriodEnd(final Calendar observationPeriodEndValue) { this.observationPeriodEnd = observationPeriodEndValue; } private Calendar observationPeriodStart; /** * Optional. Gets the observation period start. * @return The ObservationPeriodStart value. */ public Calendar getObservationPeriodStart() { return this.observationPeriodStart; } /** * Optional. Gets the observation period start. * @param observationPeriodStartValue The ObservationPeriodStart value. */ public void setObservationPeriodStart(final Calendar observationPeriodStartValue) { this.observationPeriodStart = observationPeriodStartValue; } private String overallRecommendationServiceLevelObjective; /** * Optional. Gets or sets overallRecommendationServiceLevelObjective for * service tier advisor. * @return The OverallRecommendationServiceLevelObjective value. */ public String getOverallRecommendationServiceLevelObjective() { return this.overallRecommendationServiceLevelObjective; } /** * Optional. Gets or sets overallRecommendationServiceLevelObjective for * service tier advisor. * @param overallRecommendationServiceLevelObjectiveValue The * OverallRecommendationServiceLevelObjective value. */ public void setOverallRecommendationServiceLevelObjective(final String overallRecommendationServiceLevelObjectiveValue) { this.overallRecommendationServiceLevelObjective = overallRecommendationServiceLevelObjectiveValue; } private String overallRecommendationServiceLevelObjectiveId; /** * Optional. Gets or sets overallRecommendationServiceLevelObjectiveId for * service tier advisor. * @return The OverallRecommendationServiceLevelObjectiveId value. */ public String getOverallRecommendationServiceLevelObjectiveId() { return this.overallRecommendationServiceLevelObjectiveId; } /** * Optional. Gets or sets overallRecommendationServiceLevelObjectiveId for * service tier advisor. * @param overallRecommendationServiceLevelObjectiveIdValue The * OverallRecommendationServiceLevelObjectiveId value. */ public void setOverallRecommendationServiceLevelObjectiveId(final String overallRecommendationServiceLevelObjectiveIdValue) { this.overallRecommendationServiceLevelObjectiveId = overallRecommendationServiceLevelObjectiveIdValue; } private ArrayList<SloUsageMetric> serviceLevelObjectiveUsageMetrics; /** * Optional. Gets or sets serviceLevelObjectiveUsageMetrics for the service * tier advisor. * @return The ServiceLevelObjectiveUsageMetrics value. */ public ArrayList<SloUsageMetric> getServiceLevelObjectiveUsageMetrics() { return this.serviceLevelObjectiveUsageMetrics; } /** * Optional. Gets or sets serviceLevelObjectiveUsageMetrics for the service * tier advisor. * @param serviceLevelObjectiveUsageMetricsValue The * ServiceLevelObjectiveUsageMetrics value. */ public void setServiceLevelObjectiveUsageMetrics(final ArrayList<SloUsageMetric> serviceLevelObjectiveUsageMetricsValue) { this.serviceLevelObjectiveUsageMetrics = serviceLevelObjectiveUsageMetricsValue; } private String usageBasedRecommendationServiceLevelObjective; /** * Optional. Gets or sets usageBasedRecommendationServiceLevelObjective for * service tier advisor. * @return The UsageBasedRecommendationServiceLevelObjective value. */ public String getUsageBasedRecommendationServiceLevelObjective() { return this.usageBasedRecommendationServiceLevelObjective; } /** * Optional. Gets or sets usageBasedRecommendationServiceLevelObjective for * service tier advisor. * @param usageBasedRecommendationServiceLevelObjectiveValue The * UsageBasedRecommendationServiceLevelObjective value. */ public void setUsageBasedRecommendationServiceLevelObjective(final String usageBasedRecommendationServiceLevelObjectiveValue) { this.usageBasedRecommendationServiceLevelObjective = usageBasedRecommendationServiceLevelObjectiveValue; } private String usageBasedRecommendationServiceLevelObjectiveId; /** * Optional. Gets or sets usageBasedRecommendationServiceLevelObjectiveId * for service tier advisor. * @return The UsageBasedRecommendationServiceLevelObjectiveId value. */ public String getUsageBasedRecommendationServiceLevelObjectiveId() { return this.usageBasedRecommendationServiceLevelObjectiveId; } /** * Optional. Gets or sets usageBasedRecommendationServiceLevelObjectiveId * for service tier advisor. * @param usageBasedRecommendationServiceLevelObjectiveIdValue The * UsageBasedRecommendationServiceLevelObjectiveId value. */ public void setUsageBasedRecommendationServiceLevelObjectiveId(final String usageBasedRecommendationServiceLevelObjectiveIdValue) { this.usageBasedRecommendationServiceLevelObjectiveId = usageBasedRecommendationServiceLevelObjectiveIdValue; } /** * Initializes a new instance of the ServiceTierAdvisorProperties class. * */ public ServiceTierAdvisorProperties() { this.setServiceLevelObjectiveUsageMetrics(new LazyArrayList<SloUsageMetric>()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan; import org.apache.pig.data.Tuple; import org.apache.pig.impl.io.FileSpec; import org.apache.pig.impl.plan.OperatorKey; import org.apache.pig.impl.plan.VisitorException; /** * The MapReduce Split operator. * <p> * The assumption here is that * the logical to physical translation * will create this dummy operator with * just the filename using which the input * branch will be stored and used for loading * Also the translation should make sure that * appropriate filter operators are configured * as outputs of this operator using the conditions * specified in the LOSplit. So LOSplit will be converted * into: * * | | | * Filter1 Filter2 ... Filter3 * | | ... | * | | ... | * ---- POSplit -... ---- * This is different than the existing implementation * where the POSplit writes to sidefiles after filtering * and then loads the appropriate file. * <p> * The approach followed here is as good as the old * approach if not better in many cases because * of the availability of attachinInputs. An optimization * that can ensue is if there are multiple loads that * load the same file, they can be merged into one and * then the operators that take input from the load * can be stored. This can be used when * the mapPlan executes to read the file only once and * attach the resulting tuple as inputs to all the * operators that take input from this load. * * In some cases where the conditions are exclusive and * some outputs are ignored, this approach can be worse. * But this leads to easier management of the Split and * also allows to reuse this data stored from the split * job whenever necessary. */ public class POSplit extends PhysicalOperator { private static final long serialVersionUID = 1L; /* * The filespec that is used to store and load the output of the split job * which is the job containing the split */ private FileSpec splitStore; /* * The list of sub-plans the inner plan is composed of */ private List<PhysicalPlan> myPlans = new ArrayList<PhysicalPlan>(); private BitSet processedSet = new BitSet(); private transient boolean inpEOP = false; /** * Constructs an operator with the specified key * @param k the operator key */ public POSplit(OperatorKey k) { this(k,-1,null); } /** * Constructs an operator with the specified key * and degree of parallelism * @param k the operator key * @param rp the degree of parallelism requested */ public POSplit(OperatorKey k, int rp) { this(k,rp,null); } /** * Constructs an operator with the specified key and inputs * @param k the operator key * @param inp the inputs that this operator will read data from */ public POSplit(OperatorKey k, List<PhysicalOperator> inp) { this(k,-1,inp); } /** * Constructs an operator with the specified key, * degree of parallelism and inputs * @param k the operator key * @param rp the degree of parallelism requested * @param inp the inputs that this operator will read data from */ public POSplit(OperatorKey k, int rp, List<PhysicalOperator> inp) { super(k, rp, inp); } @Override public void visit(PhyPlanVisitor v) throws VisitorException { v.visitSplit(this); } @Override public String name() { return getAliasString() + "Split - " + mKey.toString(); } @Override public boolean supportsMultipleInputs() { return false; } @Override public boolean supportsMultipleOutputs() { return true; } /** * Returns the name of the file associated with this operator * @return the FileSpec associated with this operator */ public FileSpec getSplitStore() { return splitStore; } /** * Sets the name of the file associated with this operator * @param splitStore the FileSpec used to store the data */ public void setSplitStore(FileSpec splitStore) { this.splitStore = splitStore; } /** * Returns the list of nested plans. * @return the list of the nested plans * @see org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PlanPrinter */ public List<PhysicalPlan> getPlans() { return myPlans; } /** * Appends the specified plan to the end of * the nested input plan list * @param inPlan plan to be appended to the list */ public void addPlan(PhysicalPlan inPlan) { myPlans.add(inPlan); processedSet.set(myPlans.size()-1); } /** * Removes plan from * the nested input plan list * @param plan plan to be removed */ public void removePlan(PhysicalPlan plan) { myPlans.remove(plan); processedSet.clear(myPlans.size()); } @Override public Result getNextTuple() throws ExecException { if (this.parentPlan.endOfAllInput) { return getStreamCloseResult(); } if (processedSet.cardinality() == myPlans.size()) { Result inp = processInput(); if (inp.returnStatus == POStatus.STATUS_EOP && this.parentPlan.endOfAllInput) { return getStreamCloseResult(); } if (inp.returnStatus == POStatus.STATUS_EOP || inp.returnStatus == POStatus.STATUS_ERR ) { return inp; } Tuple tuple = (Tuple)inp.result; for (PhysicalPlan pl : myPlans) { pl.attachInput(tuple); } processedSet.clear(); } return processPlan(); } private Result processPlan() throws ExecException { int idx = processedSet.nextClearBit(0); PhysicalOperator leaf = myPlans.get(idx).getLeaves().get(0); Result res = runPipeline(leaf); if (res.returnStatus == POStatus.STATUS_EOP) { processedSet.set(idx++); if (idx < myPlans.size()) { res = processPlan(); } } return (res.returnStatus == POStatus.STATUS_OK || res.returnStatus == POStatus.STATUS_ERR ) ? res : RESULT_EMPTY; } private Result runPipeline(PhysicalOperator leaf) throws ExecException { Result res = null; while (true) { res = leaf.getNextTuple(); if (res.returnStatus == POStatus.STATUS_OK) { break; } else if (res.returnStatus == POStatus.STATUS_NULL) { continue; } else if (res.returnStatus == POStatus.STATUS_EOP) { break; } else if (res.returnStatus == POStatus.STATUS_ERR) { break; } } return res; } private Result getStreamCloseResult() throws ExecException { Result res = null; while (true) { if (processedSet.cardinality() == myPlans.size()) { Result inp = processInput(); if (inp.returnStatus == POStatus.STATUS_OK) { Tuple tuple = (Tuple)inp.result; for (PhysicalPlan pl : myPlans) { pl.attachInput(tuple); } inpEOP = false; } else if (inp.returnStatus == POStatus.STATUS_EOP){ inpEOP = true; } else if (inp.returnStatus == POStatus.STATUS_NULL) { inpEOP = false; } else if (inp.returnStatus == POStatus.STATUS_ERR) { return inp; } processedSet.clear(); } int idx = processedSet.nextClearBit(0); if (inpEOP ) { myPlans.get(idx).endOfAllInput = true; } PhysicalOperator leaf = myPlans.get(idx).getLeaves().get(0); res = leaf.getNextTuple(); if (res.returnStatus == POStatus.STATUS_EOP) { processedSet.set(idx++); if (idx < myPlans.size()) { continue; } } else { break; } if (!inpEOP && res.returnStatus == POStatus.STATUS_EOP) { continue; } else { break; } } return res; } @Override public POSplit clone() throws CloneNotSupportedException { POSplit opClone = (POSplit) super.clone(); opClone.processedSet = new BitSet(); opClone.myPlans = clonePlans(myPlans); return opClone; } @Override public Tuple illustratorMarkup(Object in, Object out, int eqClassIndex) { // no op return null; } }
package org.jhove2.module.identify; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jdom.Element; import org.jdom.output.XMLOutputter; import uk.gov.nationalarchives.droid.ConfigFile; import uk.gov.nationalarchives.droid.FileCollection; import uk.gov.nationalarchives.droid.IdentificationFile; import uk.gov.nationalarchives.droid.JHOVE2AnalysisControllerUtil; import uk.gov.nationalarchives.droid.JHOVE2IAnalysisController; import uk.gov.nationalarchives.droid.MessageDisplay; import uk.gov.nationalarchives.droid.signatureFile.FFSignatureFile; import uk.gov.nationalarchives.droid.signatureFile.FileFormat; import uk.gov.nationalarchives.droid.xmlReader.PronomWebService; /** * This is a condensation and adaptation of {@link uk.gov.nationalarchives.droid.AnalysisController} * Essentially, methods here have been copied from the altered version of that class included * in the JHOVE2 distribution, with some additional accessor/mutator and convenience methods, * and a few additional modification to suppress unwanted features. * * Please see the file DROID-LICENSE.txt in the JHOVE2 distribution for a complete statement * of the BSD license rights governing the use of DROID source code. * * @author smorrissey * */ public class DROIDAnalysisController implements JHOVE2IAnalysisController { /** * Contains a list of all format names from the current signature file */ public List<String> formatName = new ArrayList<String>(); /** * Contains a list of all PUIDs from the current signature file */ public List<String> PUID = new ArrayList<String>(); /** * Contains a list of all Mime Types from the current signature file */ public List<String> mimeType = new ArrayList<String>(); /** * Contains a list of all format details (PUID, format name etc) from the current signature file */ public List<String> version = new ArrayList<String>(); /** * Contains a list of all format details (PUID, format name etc) from the current signature file */ public List<String> fileFormatDetail = new ArrayList<String>(); /** * Indicates whether fileFormatDetail was successfully populated */ public boolean isFileFormatPopulated = false; //class variables: private ConfigFile configFile = new ConfigFile(); private FileCollection fileCollection = new FileCollection(); private FFSignatureFile sigFile; /** * output formats to be used for saving results at end of run */ /** * base file name to be used for saving results at end of run */ public DROIDAnalysisController() { fileCollection = new FileCollection(); } /** * This is used to collect file format information from the current signature file */ public void getFileFormatsDetails() { formatName = new ArrayList<String>(); PUID = new ArrayList<String>(); mimeType = new ArrayList<String>(); fileFormatDetail = new ArrayList<String>(); version = new ArrayList<String>(); try { for (int i = 0; i < sigFile.getNumFileFormats(); i++) { try { FileFormat ff = sigFile.getFileFormat(i); String strFormatName = ff.getName(); String strPUID = ff.getPUID(); String strMimeType = ff.getMimeType(); String strVersion = ff.getVersion(); String strFormatDetail = ""; if (strPUID != null) { PUID.add(strPUID.trim()); } if (strFormatDetail != null) { if (!formatName.contains(strFormatName.trim())) { formatName.add(strFormatName.trim()); } } if(strVersion != null && !strVersion.equals("")){ if (!strVersion.equals("") && !version.contains(strVersion.trim())) { version.add(strVersion.trim()); } } if (strMimeType != null && !strMimeType.equals("")) { if (!mimeType.contains(strMimeType.trim())) { mimeType.add(strMimeType.trim()); } } } catch (Exception ex) { System.out.println(ex.toString()); } } } catch (Exception ex) { isFileFormatPopulated= false; } Collections.sort(PUID); Collections.sort(formatName); Collections.sort(mimeType); isFileFormatPopulated=true; } /** * Reads a configuration file, and loads the contents into memory. * * @param theFileName The name of the configuration file to open * @throws Exception on error */ public void readConfiguration(String theFileName) throws Exception { configFile = JHOVE2AnalysisControllerUtil.loadConfigFile(theFileName); return; } /** * Reads in and parses the signature file * Updates the configuration file with this signature file * * @param theSigFileName Name of the signature file * @return name of sig file * @throws Exception on error */ public String readSigFile(String theSigFileName) throws Exception { sigFile = JHOVE2AnalysisControllerUtil.loadSigFile(configFile, theSigFileName); return sigFile.getVersion(); } /** * Empties the file list */ public void resetFileList() { fileCollection.removeAll(); } /** * Add files to list of files ready for identifier. * Calls addFile(fileFolderName, false) * * @param fileFolderName file or folder to add to */ public void addFile(String fileFolderName) { addFile(fileFolderName, false); } /** * Add file to list of files ready for identifier. * If the file is already in list, then does not add it. * If the file is a folder, then adds all files it contains. * If isRecursive is set to true, then it also searches recursively through any subfolders. * * @param fileFolderName file or folder to add to * @param isRecursive whether or not to search folders recursively */ public void addFile(String fileFolderName, boolean isRecursive) { fileCollection.addFile(fileFolderName, isRecursive); } /** * Remove file from the file list * * @param theFileName the name of the file to remove */ public void removeFile(String theFileName) { fileCollection.removeFile(theFileName); } public void removeFile(int theIndex) { fileCollection.removeFile(theIndex); } /** * Returns an identificationFile object based on its index in the list * * @param theIndex index of file in file collection * @return identifier file */ public IdentificationFile getFile(int theIndex) { IdentificationFile theFile = null; try { theFile = fileCollection.getFile(theIndex); } catch (Exception e){ // } return theFile; } /** * Returns the number of files in identifier file list * * @return num of files */ public int getNumFiles() { int theNumFiles = 0; try { theNumFiles = fileCollection.getNumFiles(); } catch (Exception e) { // } return theNumFiles; //return fileCollection.getNumFiles() ; } /** * Get an iterator for the file collection * * @return iterator */ public Iterator<IdentificationFile> getFileIterator() { return this.fileCollection.getIterator(); } /** * Return the version of the currently loaded signature file * * @return version */ public int getSigFileVersion() { int theVersion = 0; try { theVersion = Integer.parseInt(sigFile.getVersion()); } catch (Exception e) {} return theVersion; } public FFSignatureFile getSigFile() { return sigFile; } /** * Return the version of the uk application * * @return string */ public static String getDROIDVersion() { String theVersion = DROID_VERSION; //remove number after last . This is a development version, not to be displayed in About box int theLastDot = theVersion.lastIndexOf("."); if (theLastDot > -1) { if (theVersion.indexOf(".") < theLastDot) { theVersion = theVersion.substring(0, theLastDot); } } return theVersion; } /** * Access to the file collection * * @return the current file collection */ public FileCollection getFileCollection() { return fileCollection; } /** * checks whether there is a signature file available through the PRONOM web service * which is a later version than the one currently loaded. * * @return boolean */ public boolean isNewerSigFileAvailable() { return isNewerSigFileAvailable(this.getSigFileVersion()); } /** * checks whether there is a signature file available through the PRONOM web service * which is a later version than the specified version number. * * @param currentVersion the version * @return boolean */ public boolean isNewerSigFileAvailable(int currentVersion) { int theLatestVersion; try { Element versionXML = PronomWebService.sendRequest(configFile.getSigFileURL(), configFile.getProxyHost(), configFile.getProxyPort(), "getSignatureFileVersionV1", null); Boolean deprecated = Boolean.parseBoolean(PronomWebService.extractXMLelement(versionXML, "Deprecated").getValue()); if (deprecated) { String message = "A new version of DROID is available.\nPlease visit http://droid.sourceforge.net"; MessageDisplay.generalInformation(message); } theLatestVersion = Integer.parseInt(PronomWebService.extractXMLelement(versionXML, "Version").getValue()); int sigFileLatestVersion = theLatestVersion; MessageDisplay.setStatusText("The latest signature file available is V" + sigFileLatestVersion); } catch (Exception e) { MessageDisplay.generalWarning("Unable to get signature file version from PRONOM website:\n" + e.getMessage()); return false; } return (theLatestVersion > currentVersion); } /** * Download the latest signature file from the PRONOM web service, save it to file * An input flag determines whether or not to load it in to the current instance of uk * * @param theFileName file where to save signature file * @param isLoadSigFile Flag indicating whether to load the signature file into the current instance of uk */ public void downloadwwwSigFile(String theFileName, boolean isLoadSigFile) { try { Element sigFile = PronomWebService.sendRequest(configFile.getSigFileURL(), configFile.getProxyHost(), configFile.getProxyPort(), "getSignatureFileV1", "FFSignatureFile"); try { XMLOutputter outputter = new XMLOutputter(); java.io.BufferedWriter out = new java.io.BufferedWriter(new java.io.FileWriter(theFileName)); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); outputter.output(sigFile, out); out.close(); if (isLoadSigFile) { try { configFile.setDateLastDownload(); readSigFile(theFileName); getFileFormatsDetails(); } catch (Exception e) { MessageDisplay.generalWarning("Unable to read in downloaded signature file "); } } } catch (Exception e) { String locaion = theFileName.substring(0,theFileName.lastIndexOf(File.separatorChar)); MessageDisplay.generalWarning("Unable to save downloaded signature file to location: "+locaion+".\nEither the location does not exist or DROID does not have Write permissions to this location"); } } catch (Exception e) { MessageDisplay.generalWarning("Unable to download signature file from the PRONOM web service"); } } /** * Download the latest signature file from the PRONOM web service, save it to file * and load it in to the current instance of uk * * @param theFileName file where to save signature file */ public void downloadwwwSigFile(String theFileName) { downloadwwwSigFile(theFileName, true); } /** * Download the latest signature file from the PRONOM web service, save it to a DEFAULT location * and load it in to the current instance of uk * Saves to same folder as current signature file but as * DROID_Signature_V[X].xml , where [X] is the version number of the signature file */ public void downloadwwwSigFile() { try { int theLatestVersion = Integer.parseInt(PronomWebService.sendRequest(configFile.getSigFileURL(), configFile.getProxyHost(), configFile.getProxyPort(), "getSignatureFileVersionV1", "Version").getValue()); java.io.File currentSigFile = new java.io.File(configFile.getSigFileName()); String currentPath = ""; if (currentSigFile != null) { currentPath = (currentSigFile.getAbsoluteFile()).getParent() + java.io.File.separator; } final String newSigFileName = currentPath + "DROID_SignatureFile_V" + theLatestVersion + ".xml"; downloadwwwSigFile(newSigFileName); } catch (Exception e) { MessageDisplay.generalWarning("Unable to download signature file from the PRONOM web service"); } } /** * Checks whether a new signature file download is due * based on current date and settings in the configuration file * * @return boolean */ public boolean isSigFileDownloadDue() { return configFile.isDownloadDue(); } /** * Returns the date current signature file was created * * @return date signature file was created */ public String getSignatureFileDate() { String theDate = ""; try { theDate = sigFile.getDateCreated(); } catch (Exception e) { // } if (theDate.equals("")) { theDate = "No date given"; } return theDate; //return sigFile.getDateCreated() ; } /** * Returns the file path of the signature file * * @return signature file file path */ public String getSignatureFileName() { return configFile.getSigFileName(); } /** * Get the PUID resolution base URL * * @return PUID resolution */ public String getPuidResolutionURL() { return configFile.getPuidResolution(); } /** * Sets the URL of the signature file webservices * * @param sigFileURL signature file */ public void setSigFileURL(String sigFileURL) { configFile.setSigFileURL(sigFileURL); } /** * Gets the number of days after which user should be alerted for new signature file * * @return number of days after which user should be alerted for new signature file */ public int getSigFileCheckFreq() { return configFile.getSigFileCheckFreq(); } /** * Updates the configuration parameter which records the interval after which * the signature file should be updated. * * @param theFreq The number of days after which the user will be prompted to check for a newer signature file */ public void setSigFileCheckFreq(String theFreq) { configFile.setSigFileCheckFreq(theFreq); } /** * updates the DateLastDownload element of the configuration file and updates * the configuration file. This is to be used whenever the user checks for * a signature file update, but one is not found */ public void updateDateLastDownload() { //set the DateLastDownload to now configFile.setDateLastDownload(); //save to file try { configFile.saveConfiguration(); } catch (IOException e) { MessageDisplay.generalWarning("Unable to save configuration updates"); } } public ConfigFile getConfigFile() { return configFile; } public void setConfigFile(ConfigFile configFile) { this.configFile = configFile; } public ConfigFile loadConfigFile(String theFileName) throws Exception{ this.readConfiguration(theFileName); return this.configFile; } public void setSigFile(FFSignatureFile sigFile) { this.sigFile = sigFile; } }
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.def; import java.io.IOException; import org.auraframework.def.DefDescriptor.DefType; import org.auraframework.test.UnitTestCase; import org.auraframework.throwable.quickfix.QuickFixException; import org.auraframework.util.json.Json; public class DescriptorFilterTest extends UnitTestCase { public DescriptorFilterTest(String name) { super(name); } private String getLabel(DescriptorFilter dm, boolean expected, String what, String value) { String match; if (expected) { match = "Failed to match "; } else { match = "Matched "; } return dm.toString() + ": " + match + " " + what + ": " + value; } private void checkPrefix(DescriptorFilter dm, String prefix, boolean value) { assertEquals(getLabel(dm, value, "prefix", prefix), value, dm.matchPrefix(prefix)); } private void checkNamespace(DescriptorFilter dm, String namespace, boolean value) { assertEquals(getLabel(dm, value, "namespace", namespace), value, dm.matchNamespace(namespace)); } private void checkName(DescriptorFilter dm, String name, boolean value) { assertEquals(getLabel(dm, value, "name", name), value, dm.matchName(name)); } private void checkType(DescriptorFilter dm, DefType type, boolean value) { assertEquals(getLabel(dm, value, "type", type.toString()), value, dm.matchType(type)); } public void testInvalid() throws Exception { try { new DescriptorFilter("bah.humbug://a:b"); fail("should have gotten an exception"); } catch (IllegalArgumentException expected) { assertTrue("exception should name prefix", expected.getMessage().contains("prefix")); } try { new DescriptorFilter("a://bah.humbug:b"); fail("should have gotten an exception"); } catch (IllegalArgumentException expected) { assertTrue("exception should name namespace", expected.getMessage().contains("namespace")); } try { new DescriptorFilter("a://b:bah.humbug"); fail("should have gotten an exception"); } catch (IllegalArgumentException expected) { assertTrue("exception should name name", expected.getMessage().contains(" name ")); } try { new DescriptorFilter("a://b:c", "bah.humbug"); fail("should have gotten an exception"); } catch (IllegalArgumentException expected) { } } public void testPrefixOnly() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("notfound://"); checkPrefix(dm, "hi", false); checkPrefix(dm, "css", false); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", true); checkName(dm, "hi", true); checkName(dm, "css", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testPrefixPlusNamespace() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("notfound://hi"); checkPrefix(dm, "hi", false); checkPrefix(dm, "css", false); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", false); checkName(dm, "hi", true); checkName(dm, "css", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testNamespaceOnly() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("hi"); checkPrefix(dm, "hi", true); checkPrefix(dm, "css", true); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", false); checkName(dm, "hi", true); checkName(dm, "css", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testNamespaceAndName() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("hi:ho"); checkPrefix(dm, "hi", true); checkPrefix(dm, "css", true); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", false); checkName(dm, "ho", true); checkName(dm, "hi", false); checkName(dm, "css", false); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testFullWildcardMatcher() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("*://*:*"); checkPrefix(dm, "hi", true); checkPrefix(dm, "css", true); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", true); checkName(dm, "hi", true); checkName(dm, "css", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testNoprefixWildcardMatcher() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("notfound://*:*"); checkPrefix(dm, "hi", false); checkPrefix(dm, "css", false); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", true); checkName(dm, "hi", true); checkName(dm, "css", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testNonamespaceWildcardMatcher() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("*://notfound:*"); checkPrefix(dm, "hi", true); checkPrefix(dm, "css", true); checkNamespace(dm, "hi", false); checkNamespace(dm, "css", false); checkName(dm, "hi", true); checkName(dm, "css", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testNonameWildcardMatcher() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("*://*:notfound"); checkPrefix(dm, "hi", true); checkPrefix(dm, "css", true); checkNamespace(dm, "hi", true); checkNamespace(dm, "css", true); checkName(dm, "hi", false); checkName(dm, "css", false); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testExactMatcher() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("exactprefix://exactnamespace:exactname"); checkPrefix(dm, "exactprefix1", false); checkPrefix(dm, "1exactprefix", false); checkPrefix(dm, "exactnamespace", false); checkPrefix(dm, "exactname", false); checkPrefix(dm, "exactprefix", true); checkNamespace(dm, "exactnamespace1", false); checkNamespace(dm, "1exactnamespace", false); checkNamespace(dm, "exactprefix", false); checkNamespace(dm, "exactname", false); checkNamespace(dm, "exactnamespace", true); checkName(dm, "exactname1", false); checkName(dm, "1exactname", false); checkName(dm, "exactprefix", false); checkName(dm, "exactnamespace", false); checkName(dm, "exactname", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testAlmostMatcher() throws Exception { DescriptorFilter dm; dm = new DescriptorFilter("almostprefix*://almostnamespace*:almostname*"); checkPrefix(dm, "almostprefix1", true); checkPrefix(dm, "1almostprefix", false); checkPrefix(dm, "almostnamespace", false); checkPrefix(dm, "almostname", false); checkPrefix(dm, "almostprefix", true); checkNamespace(dm, "almostnamespace1", true); checkNamespace(dm, "1almostnamespace", false); checkNamespace(dm, "almostprefix", false); checkNamespace(dm, "almostname", false); checkNamespace(dm, "almostnamespace", true); checkName(dm, "almostname1", true); checkName(dm, "1almostname", false); checkName(dm, "almostprefix", false); checkName(dm, "almostnamespace", true); // note that this is true.... checkName(dm, "almostname", true); for (DefType type : DefType.values()) { checkType(dm, type, true); } } public void testTypeMatcher() throws Exception { for (DefType type : DefType.values()) { DescriptorFilter dm = new DescriptorFilter("exactprefix://exactnamespace:exactname", type.toString()); checkType(dm, type, true); for (DefType otype : DefType.values()) { if (!otype.equals(type)) { checkType(dm, otype, false); } } } } @SuppressWarnings("serial") private static class FakeDefDescriptor implements DefDescriptor<Definition> { private final String name; private final String prefix; private final String namespace; private final DefType defType; public FakeDefDescriptor(String prefix, String namespace, String name, DefType defType) { this.prefix = prefix; this.namespace = namespace; this.name = name; this.defType = defType; } @Override public void serialize(Json json) throws IOException { throw new IOException("ook"); } @Override public String getName() { return this.name; } @Override public String getQualifiedName() { return null; } @Override public String getDescriptorName() { return null; } @Override public String getPrefix() { return this.prefix; } @Override public String getNamespace() { return this.namespace; } @Override public String getNameParameters() { return null; } @Override public boolean isParameterized() { return false; } @Override public DefType getDefType() { return this.defType; } @Override public Definition getDef() throws QuickFixException { return null; } @Override public boolean exists() { return true; } @Override public String toString() { return this.prefix + "://" + this.namespace + ":" + this.name + "(" + this.defType.toString() + ")"; } @Override public int compareTo(DefDescriptor<?> other) { // Can't use the helper on DefDescriptorImpl in this non-impl test // package... return getQualifiedName().compareToIgnoreCase(other.getQualifiedName()); } @Override public DefDescriptor<? extends Definition> getBundle() { return null; } } public void testDescriptor() { DescriptorFilter dm; FakeDefDescriptor dd; dm = new DescriptorFilter("exactprefix://exactnamespace:exactname", "APPLICATION"); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.APPLICATION); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.COMPONENT); assertEquals(getLabel(dm, false, "dd", dd.toString()), false, dm.matchDescriptor(dd)); dm = new DescriptorFilter("exactprefix://exactnamespace:exactname", "APPLICATION,COMPONENT"); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.APPLICATION); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.COMPONENT); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.STYLE); assertEquals(getLabel(dm, false, "dd", dd.toString()), false, dm.matchDescriptor(dd)); dm = new DescriptorFilter("exactprefix://exactnamespace:exactname", "*"); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.APPLICATION); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.COMPONENT); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.STYLE); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dm = new DescriptorFilter("exactprefix://exactnamespace:exactname", null); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.APPLICATION); assertEquals(getLabel(dm, false, "dd", dd.toString()), false, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.COMPONENT); assertEquals(getLabel(dm, true, "dd", dd.toString()), true, dm.matchDescriptor(dd)); dd = new FakeDefDescriptor("exactprefix", "exactnamespace", "exactname", DefType.STYLE); assertEquals(getLabel(dm, false, "dd", dd.toString()), false, dm.matchDescriptor(dd)); } }
// Copyright 2009, 2010, 2011, 2012 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.internal.services; import org.apache.tapestry5.Link; import org.apache.tapestry5.MetaDataConstants; import org.apache.tapestry5.TapestryConstants; import org.apache.tapestry5.internal.EmptyEventContext; import org.apache.tapestry5.internal.InternalConstants; import org.apache.tapestry5.internal.test.InternalBaseTestCase; import org.apache.tapestry5.ioc.services.TypeCoercer; import org.apache.tapestry5.services.*; import org.apache.tapestry5.services.security.ClientWhitelist; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Locale; /** * Most of the testing is implemented through legacy tests against code that uses CELE. * * @since 5.1.0.1 */ public class ComponentEventLinkEncoderImplTest extends InternalBaseTestCase { private TypeCoercer typeCoercer; private ContextPathEncoder contextPathEncoder; @BeforeClass public void setup() { typeCoercer = getService(TypeCoercer.class); contextPathEncoder = getService(ContextPathEncoder.class); } @Test public void locale_not_encoded() { RequestSecurityManager manager = mockRequestSecurityManager(); Request request = mockRequest(); Response response = mockResponse(); ContextPathEncoder contextPathEncoder = getService(ContextPathEncoder.class); expect(manager.checkPageSecurity("MyPage")).andReturn(LinkSecurity.INSECURE); train_getContextPath(request, "/myapp"); train_encodeURL(response, "/myapp/mypage", "MAGIC"); replay(); ComponentEventLinkEncoder encoder = new ComponentEventLinkEncoderImpl(null, contextPathEncoder, null, request, response, manager, null, null, false, "", null, null); PageRenderRequestParameters parameters = new PageRenderRequestParameters("MyPage", new EmptyEventContext()); Link link = encoder.createPageRenderLink(parameters); assertEquals(link.toURI(), "MAGIC"); verify(); } @Test public void index_stripped_off() { RequestSecurityManager manager = mockRequestSecurityManager(); Request request = mockRequest(); Response response = mockResponse(); ContextPathEncoder contextPathEncoder = getService(ContextPathEncoder.class); expect(manager.checkPageSecurity("admin/Index")).andReturn(LinkSecurity.INSECURE); train_getContextPath(request, ""); train_encodeURL(response, "/admin/abc", "MAGIC"); replay(); ComponentEventLinkEncoder encoder = new ComponentEventLinkEncoderImpl(null, contextPathEncoder, null, request, response, manager, null, null, false, "", null, null); PageRenderRequestParameters parameters = new PageRenderRequestParameters("admin/Index", new ArrayEventContext( typeCoercer, "abc")); Link link = encoder.createPageRenderLink(parameters); assertEquals(link.toURI(), "MAGIC"); verify(); } @Test public void root_index_page_gone() { RequestSecurityManager manager = mockRequestSecurityManager(); Request request = mockRequest(); Response response = mockResponse(); ContextPathEncoder contextPathEncoder = getService(ContextPathEncoder.class); expect(manager.checkPageSecurity("Index")).andReturn(LinkSecurity.INSECURE); train_getContextPath(request, ""); train_encodeURL(response, "/", "MAGIC"); replay(); ComponentEventLinkEncoder encoder = new ComponentEventLinkEncoderImpl(null, contextPathEncoder, null, request, response, manager, null, null, false, "", null, null); PageRenderRequestParameters parameters = new PageRenderRequestParameters("Index", new EmptyEventContext()); Link link = encoder.createPageRenderLink(parameters); assertEquals(link.toURI(), "MAGIC"); verify(); } @Test public void empty_path() throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(); Response response = mockResponse(); LocalizationSetter ls = mockLocalizationSetter(); train_getPath(request, ""); train_setLocaleFromLocaleName(ls, "", false); train_isPageName(resolver, "", false); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, response, null, null, null, true, "", null, null); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertNull(parameters); verify(); } @Test public void not_a_page_request() throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(); Response response = mockResponse(); LocalizationSetter ls = mockLocalizationSetter(); stub_isPageName(resolver, false); train_setLocaleFromLocaleName(ls, "foo", false); train_getPath(request, "/foo/Bar.baz"); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, response, null, null, null, true, "", null, null); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertNull(parameters); verify(); } @Test public void just_the_locale_name() throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(); Response response = mockResponse(); LocalizationSetter ls = mockLocalizationSetter(); train_getPath(request, "/en"); train_setLocaleFromLocaleName(ls, "en", true); train_isPageName(resolver, "", false); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, response, null, null, null, true, "", null, null); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertNull(parameters); verify(); } private Request mockRequest(boolean isLoopback) { Request request = mockRequest(); train_getParameter(request, TapestryConstants.PAGE_LOOPBACK_PARAMETER_NAME, isLoopback ? "t" : null); return request; } /** * TAPESTRY-2226 */ @Test public void page_activation_context_for_root_index_page() throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(false); LocalizationSetter ls = mockLocalizationSetter(); MetaDataLocator metaDataLocator = neverWhitelistProtected(); train_getPath(request, "/foo/bar"); train_setLocaleFromLocaleName(ls, "foo", false); train_isPageName(resolver, "foo/bar", false); train_isPageName(resolver, "foo", false); train_isPageName(resolver, "", true); train_canonicalizePageName(resolver, "", "index"); train_getLocale(request, Locale.ITALIAN); ls.setNonPeristentLocaleFromLocaleName("it"); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, null, null, null, null, true, "", metaDataLocator, null); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertEquals(parameters.getLogicalPageName(), "index"); assertArraysEqual(parameters.getActivationContext().toStrings(), "foo", "bar"); assertFalse(parameters.isLoopback()); verify(); } @Test public void no_extra_context_without_final_slash() throws Exception { no_extra_context(false); } @Test public void no_extra_context_with_final_slash() throws Exception { no_extra_context(true); } private void no_extra_context(boolean finalSlash) throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(false); LocalizationSetter ls = mockLocalizationSetter(); MetaDataLocator metaDataLocator = neverWhitelistProtected(); String path = "/foo/Bar" + (finalSlash ? "/" : ""); train_getPath(request, path); train_setLocaleFromLocaleName(ls, "foo", false); train_isPageName(resolver, "foo/Bar", true); train_canonicalizePageName(resolver, "foo/Bar", "foo/bar"); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, null, null, null, null, true, "", metaDataLocator, null); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertEquals(parameters.getLogicalPageName(), "foo/bar"); assertEquals(parameters.getActivationContext().getCount(), 0); assertFalse(parameters.isLoopback()); verify(); } @Test public void page_requires_whitelist_and_client_on_whitelist() throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(false); LocalizationSetter ls = mockLocalizationSetter(); MetaDataLocator metaDataLocator = mockMetaDataLocator(); ClientWhitelist whitelist = newMock(ClientWhitelist.class); String path = "/foo/Bar"; train_getPath(request, path); train_setLocaleFromLocaleName(ls, "foo", false); train_isPageName(resolver, "foo/Bar", true); train_canonicalizePageName(resolver, "foo/Bar", "foo/bar"); expect(metaDataLocator.findMeta(MetaDataConstants.WHITELIST_ONLY_PAGE, "foo/bar", boolean.class)).andReturn(true); expect(whitelist.isClientRequestOnWhitelist()).andReturn(true); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, null, null, null, null, true, "", metaDataLocator, whitelist); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertEquals(parameters.getLogicalPageName(), "foo/bar"); assertEquals(parameters.getActivationContext().getCount(), 0); assertFalse(parameters.isLoopback()); verify(); } @Test public void page_requires_whitelist_and_client_not_on_whitelist() { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(); LocalizationSetter ls = mockLocalizationSetter(); MetaDataLocator metaDataLocator = mockMetaDataLocator(); ClientWhitelist whitelist = newMock(ClientWhitelist.class); String path = "/foo/Bar"; train_getPath(request, path); train_setLocaleFromLocaleName(ls, "foo", false); train_isPageName(resolver, "foo/Bar", true); train_canonicalizePageName(resolver, "foo/Bar", "foo/bar"); expect(metaDataLocator.findMeta(MetaDataConstants.WHITELIST_ONLY_PAGE, "foo/bar", boolean.class)).andReturn(true); expect(whitelist.isClientRequestOnWhitelist()).andReturn(false); train_isPageName(resolver, "foo", false); train_isPageName(resolver, "", false); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, null, null, null, null, true, "", metaDataLocator, whitelist); assertNull(linkEncoder.decodePageRenderRequest(request)); verify(); } @Test public void context_passed_in_path_without_final_slash() throws Exception { context_passed_in_path(false); } @Test public void context_passed_in_path_with_final_slash() throws Exception { context_passed_in_path(true); } private void context_passed_in_path(boolean finalSlash) throws Exception { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(true); LocalizationSetter ls = mockLocalizationSetter(); MetaDataLocator metaDataLocator = neverWhitelistProtected(); String path = "/foo/Bar/zip/zoom" + (finalSlash ? "/" : ""); train_getPath(request, path); train_setLocaleFromLocaleName(ls, "foo", false); train_isPageName(resolver, "foo/Bar/zip/zoom", false); train_isPageName(resolver, "foo/Bar/zip", false); train_isPageName(resolver, "foo/Bar", true); train_canonicalizePageName(resolver, "foo/Bar", "foo/bar"); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, null, null, null, null, true, "", metaDataLocator, null); PageRenderRequestParameters parameters = linkEncoder.decodePageRenderRequest(request); assertEquals(parameters.getLogicalPageName(), "foo/bar"); assertArraysEqual(parameters.getActivationContext().toStrings(), "zip", "zoom"); assertTrue(parameters.isLoopback()); verify(); } @Test public void page_name_includes_dash_in_component_event_request() { ComponentClassResolver resolver = mockComponentClassResolver(); Request request = mockRequest(); LocalizationSetter ls = mockLocalizationSetter(); MetaDataLocator metaDataLocator = neverWhitelistProtected(); expect(ls.isSupportedLocaleName("foo-bar")).andReturn(false); train_getParameter(request, InternalConstants.PAGE_CONTEXT_NAME, null); train_getParameter(request, InternalConstants.CONTAINER_PAGE_NAME, null); train_getLocale(request, Locale.ENGLISH); ls.setNonPeristentLocaleFromLocaleName("en"); String path = "/foo-bar/baz.biff"; train_getPath(request, path); train_isPageName(resolver, "foo-bar/baz", true); train_canonicalizePageName(resolver, "foo-bar/baz", "foo-bar/Baz"); replay(); ComponentEventLinkEncoderImpl linkEncoder = new ComponentEventLinkEncoderImpl(resolver, contextPathEncoder, ls, request, null, null, null, null, true, "", metaDataLocator, null); ComponentEventRequestParameters parameters = linkEncoder.decodeComponentEventRequest(request); assertEquals(parameters.getActivePageName(), "foo-bar/Baz"); assertEquals(parameters.getNestedComponentId(), "biff"); verify(); } }
/* Copyright (c) 2017 lib4j * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.libx4j.rdb.jsql; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.math.BigInteger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.temporal.TemporalUnit; import java.util.List; import org.lib4j.io.Readers; import org.lib4j.io.Streams; import org.libx4j.rdb.jsql.type.BLOB; import org.libx4j.rdb.jsql.type.ENUM; import org.libx4j.rdb.vendor.DBVendor; import org.libx4j.rdb.vendor.Dialect; final class PostgreSQLCompiler extends Compiler { @Override protected DBVendor getVendor() { return DBVendor.POSTGRE_SQL; } @Override protected void onRegister(final Connection connection) throws SQLException { try (final Statement statement = connection.createStatement()) { final StringBuilder modulus = new StringBuilder("CREATE OR REPLACE FUNCTION MODULUS(dividend double precision, divisor double precision) RETURNS numeric AS $$"); modulus.append("DECLARE"); modulus.append(" factor double precision;"); modulus.append(" result double precision;"); modulus.append("BEGIN"); modulus.append(" factor := dividend / divisor;"); modulus.append(" IF factor < 0 THEN"); modulus.append(" factor := CEIL(factor);"); modulus.append(" ELSE"); modulus.append(" factor := FLOOR(factor);"); modulus.append(" END IF;"); modulus.append(" RETURN dividend - divisor * factor;"); modulus.append("END;"); modulus.append("$$ LANGUAGE plpgsql;"); statement.execute(modulus.toString()); final StringBuilder log2 = new StringBuilder("CREATE OR REPLACE FUNCTION LOG2(num numeric) RETURNS numeric AS $$"); log2.append("DECLARE"); log2.append(" result double precision;"); log2.append("BEGIN"); log2.append(" RETURN LOG(2, num);"); log2.append("END;"); log2.append("$$ LANGUAGE plpgsql;"); statement.execute(log2.toString()); final StringBuilder log10 = new StringBuilder("CREATE OR REPLACE FUNCTION LOG10(num numeric) RETURNS numeric AS $$"); log10.append("DECLARE"); log10.append(" result double precision;"); log10.append("BEGIN"); log10.append(" RETURN LOG(10, num);"); log10.append("END;"); log10.append("$$ LANGUAGE plpgsql;"); statement.execute(log10.toString()); } catch (final SQLException e) { if (!"X0Y68".equals(e.getSQLState())) throw e; } } @Override protected String translateEnum(final type.ENUM<?> from, final type.ENUM<?> to) { final EntityEnum.Spec spec = to.type().getAnnotation(EntityEnum.Spec.class); return "::text::" + Dialect.getTypeName(spec.table(), spec.column()); } @Override protected void compile(final CaseImpl.Simple.CASE<?,?> case_, final CaseImpl.ELSE<?> _else, final Compilation compilation) throws IOException { compilation.append("CASE "); if (case_.variable instanceof type.ENUM && _else instanceof CaseImpl.CHAR.ELSE) toChar((type.ENUM<?>)case_.variable, compilation); else case_.variable.compile(compilation); } @Override protected void compile(final CaseImpl.WHEN<?> when, final CaseImpl.THEN<?,?> then, final CaseImpl.ELSE<?> _else, final Compilation compilation) throws IOException { final Class<?> conditionClass = when.condition instanceof Predicate ? ((Predicate)when.condition).dataType.getClass() : when.condition.getClass(); if ((when.condition instanceof type.ENUM || then.value instanceof type.ENUM) && (conditionClass != then.value.getClass() || _else instanceof CaseImpl.CHAR.ELSE)) { compilation.append(" WHEN "); if (when.condition instanceof type.ENUM) toChar((type.ENUM<?>)when.condition, compilation); else when.condition.compile(compilation); compilation.append(" THEN "); if (then.value instanceof type.ENUM) toChar((type.ENUM<?>)then.value, compilation); else then.value.compile(compilation); } else { super.compile(when, then, _else, compilation); } } @Override protected void compile(final CaseImpl.ELSE<?> _else, final Compilation compilation) throws IOException { compilation.append(" ELSE "); if (_else instanceof CaseImpl.CHAR.ELSE && _else.value instanceof type.ENUM) toChar((type.ENUM<?>)_else.value, compilation); else _else.value.compile(compilation); compilation.append(" END"); } @Override protected void compile(final expression.Concat expression, final Compilation compilation) throws IOException { compilation.append("CONCAT("); for (int i = 0; i < expression.args.length; i++) { final Compilable arg = compilable(expression.args[i]); if (i > 0) compilation.append(", "); arg.compile(compilation); } compilation.append(')'); } @Override protected void compile(final Interval interval, final Compilation compilation) { final List<TemporalUnit> units = interval.getUnits(); final StringBuilder clause = new StringBuilder(); for (final TemporalUnit unit : units) { final long component; final String unitString; if (unit == Interval.Unit.MICROS) { component = interval.get(unit); unitString = "MICROSECOND"; } else if (unit == Interval.Unit.MILLIS) { component = interval.get(unit); unitString = "MILLISECOND"; } else if (unit == Interval.Unit.QUARTERS) { component = interval.get(unit) * 3; unitString = "MONTH"; } else if (unit == Interval.Unit.CENTURIES) { component = interval.get(unit) * 100; unitString = "YEARS"; } else if (unit == Interval.Unit.MILLENNIA) { component = interval.get(unit) * 1000; unitString = "YEARS"; } else { component = interval.get(unit); unitString = unit.toString().substring(0, unit.toString().length() - 1); } clause.append(' ').append(component).append(" " + unitString); } compilation.append("INTERVAL '").append(clause.substring(1)).append('\''); } @Override protected String getPreparedStatementMark(final type.DataType<?> dataType) { if (!(dataType instanceof ENUM)) return "?"; final EntityEnum.Spec spec = dataType.type().getAnnotation(EntityEnum.Spec.class); return "?::" + Dialect.getTypeName(spec.table(), spec.column()); } @Override protected String compile(final BLOB dataType) throws IOException { if (dataType.get() == null) return "NULL"; final BigInteger integer = new BigInteger(Streams.readBytes(dataType.get())); return "E'\\" + integer.toString(8); // FIXME: This is only half done } private static void toChar(final type.ENUM<?> dataType, final Compilation compilation) throws IOException { compilation.append("CAST("); dataType.compile(compilation); compilation.append(" AS CHAR(").append(dataType.length()).append("))"); } @Override protected final void compile(final ComparisonPredicate<?> predicate, final Compilation compilation) throws IOException { if (predicate.a.getClass() == predicate.b.getClass() || (!(predicate.a instanceof type.ENUM) && !(predicate.b instanceof type.ENUM))) { super.compile(predicate, compilation); } else { if (predicate.a instanceof type.ENUM) toChar((type.ENUM<?>)predicate.a, compilation); else predicate.a.compile(compilation); compilation.append(' ').append(predicate.operator).append(' '); if (predicate.b instanceof type.ENUM) toChar((type.ENUM<?>)predicate.b, compilation); else predicate.b.compile(compilation); } } @Override protected void compile(final function.Mod function, final Compilation compilation) throws IOException { compilation.append("MODULUS("); function.a.compile(compilation); compilation.append(", "); function.b.compile(compilation); compilation.append(')'); } private static void compileCastNumeric(final Compilable dateType, final Compilation compilation) throws IOException { if (dateType instanceof type.ApproxNumeric) { compilation.append("CAST("); dateType.compile(compilation); compilation.append(" AS NUMERIC)"); } else { dateType.compile(compilation); } } private static void compileLog(final String sqlFunction, final function.Generic function, final Compilation compilation) throws IOException { compilation.append(sqlFunction).append('('); compileCastNumeric(function.a, compilation); if (function.b != null) { compilation.append(", "); compileCastNumeric(function.b, compilation); } compilation.append(')'); } @Override protected void compile(final function.Ln function, final Compilation compilation) throws IOException { compileLog("LN", function, compilation); } @Override protected void compile(final function.Log function, final Compilation compilation) throws IOException { compileLog("LOG", function, compilation); } @Override protected void compile(final function.Log2 function, final Compilation compilation) throws IOException { compileLog("LOG2", function, compilation); } @Override protected void compile(final function.Log10 function, final Compilation compilation) throws IOException { compileLog("LOG10", function, compilation); } @Override protected void compile(final function.Round function, final Compilation compilation) throws IOException { compilation.append("ROUND("); if (function.b instanceof type.Numeric<?> && ((type.Numeric<?>)function.b).get() != null && ((type.Numeric<?>)function.b).get().intValue() == 0) { function.a.compile(compilation); } else { compileCastNumeric(function.a, compilation); compilation.append(", "); function.b.compile(compilation); } compilation.append(')'); } @Override protected void setParameter(final type.CLOB dataType, final PreparedStatement statement, final int parameterIndex) throws IOException, SQLException { if (dataType.get() != null) statement.setString(parameterIndex, Readers.readFully(dataType.get())); else statement.setNull(parameterIndex, dataType.sqlType()); } @Override protected Reader getParameter(final type.CLOB clob, final ResultSet resultSet, final int columnIndex) throws SQLException { final String value = resultSet.getString(columnIndex); return value == null ? null : new StringReader(value); } @Override protected void setParameter(final type.BLOB dataType, final PreparedStatement statement, final int parameterIndex) throws IOException, SQLException { if (dataType.get() != null) statement.setBytes(parameterIndex, Streams.readBytes(dataType.get())); else statement.setNull(parameterIndex, dataType.sqlType()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.tools.ant.taskdefs; import org.apache.tools.ant.Project; import org.apache.tools.ant.PropertyHelper; import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ExitStatusException; import org.apache.tools.ant.taskdefs.condition.Condition; import org.apache.tools.ant.taskdefs.condition.ConditionBase; /** * Exits the active build, giving an additional message * if available. * * The <code>if</code> and <code>unless</code> attributes make the * failure conditional -both probe for the named property being defined. * The <code>if</code> tests for the property being defined, the * <code>unless</code> for a property being undefined. * * If both attributes are set, then the test fails only if both tests * are true. i.e. * <pre>fail := defined(ifProperty) && !defined(unlessProperty)</pre> * * A single nested<code>&lt;condition&gt;</code> element can be specified * instead of using <code>if</code>/<code>unless</code> (a combined * effect can be achieved using <code>isset</code> conditions). * * @since Ant 1.2 * * @ant.task name="fail" category="control" */ public class Exit extends Task { private static class NestedCondition extends ConditionBase implements Condition { public boolean eval() { if (countConditions() != 1) { throw new BuildException( "A single nested condition is required."); } return ((Condition) (getConditions().nextElement())).eval(); } } private String message; private Object ifCondition, unlessCondition; private NestedCondition nestedCondition; private Integer status; /** * A message giving further information on why the build exited. * * @param value message to output */ public void setMessage(String value) { this.message = value; } /** * Only fail if the given expression evaluates to true or the name * of an existing property. * @param c property name or evaluated expression * @since Ant 1.8.0 */ public void setIf(Object c) { ifCondition = c; } /** * Only fail if the given expression evaluates to true or the name * of an existing property. * @param c property name or evaluated expression */ public void setIf(String c) { setIf((Object) c); } /** * Only fail if the given expression evaluates to false or tno * property of the given name exists. * @param c property name or evaluated expression * @since Ant 1.8.0 */ public void setUnless(Object c) { unlessCondition = c; } /** * Only fail if the given expression evaluates to false or tno * property of the given name exists. * @param c property name or evaluated expression */ public void setUnless(String c) { setUnless((Object) c); } /** * Set the status code to associate with the thrown Exception. * @param i the <code>int</code> status */ public void setStatus(int i) { status = new Integer(i); } /** * Throw a <code>BuildException</code> to exit (fail) the build. * If specified, evaluate conditions: * A single nested condition is accepted, but requires that the * <code>if</code>/<code>unless</code> attributes be omitted. * If the nested condition evaluates to true, or the * ifCondition is true or unlessCondition is false, the build will exit. * The error message is constructed from the text fields, from * the nested condition (if specified), or finally from * the if and unless parameters (if present). * @throws BuildException on error */ public void execute() throws BuildException { boolean fail = (nestedConditionPresent()) ? testNestedCondition() : (testIfCondition() && testUnlessCondition()); if (fail) { String text = null; if (message != null && message.trim().length() > 0) { text = message.trim(); } else { if (ifCondition != null && !"".equals(ifCondition) && testIfCondition()) { text = "if=" + ifCondition; } if (unlessCondition != null && !"".equals(unlessCondition) && testUnlessCondition()) { if (text == null) { text = ""; } else { text += " and "; } text += "unless=" + unlessCondition; } if (nestedConditionPresent()) { text = "condition satisfied"; } else { if (text == null) { text = "No message"; } } } log("failing due to " + text, Project.MSG_DEBUG); throw ((status == null) ? new BuildException(text) : new ExitStatusException(text, status.intValue())); } } /** * Set a multiline message. * @param msg the message to display */ public void addText(String msg) { if (message == null) { message = ""; } message += getProject().replaceProperties(msg); } /** * Add a condition element. * @return <code>ConditionBase</code>. * @since Ant 1.6.2 */ public ConditionBase createCondition() { if (nestedCondition != null) { throw new BuildException("Only one nested condition is allowed."); } nestedCondition = new NestedCondition(); return nestedCondition; } /** * test the if condition * @return true if there is no if condition, or the named property exists */ private boolean testIfCondition() { return PropertyHelper.getPropertyHelper(getProject()) .testIfCondition(ifCondition); } /** * test the unless condition * @return true if there is no unless condition, * or there is a named property but it doesn't exist */ private boolean testUnlessCondition() { return PropertyHelper.getPropertyHelper(getProject()) .testUnlessCondition(unlessCondition); } /** * test the nested condition * @return true if there is none, or it evaluates to true */ private boolean testNestedCondition() { boolean result = nestedConditionPresent(); if (result && ifCondition != null || unlessCondition != null) { throw new BuildException("Nested conditions " + "not permitted in conjunction with if/unless attributes"); } return result && nestedCondition.eval(); } /** * test whether there is a nested condition. * @return <code>boolean</code>. */ private boolean nestedConditionPresent() { return (nestedCondition != null); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES 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.wso2.carbon.iot.android.sense.data.publisher.mqtt; import android.content.Context; import android.util.Log; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.MQTTTransportHandler; import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.TransportHandlerException; import org.wso2.carbon.iot.android.sense.constants.SenseConstants; import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords; import org.wso2.carbon.iot.android.sense.util.LocalRegistry; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * This is an example for the use of the MQTT capabilities provided by the IoT-Server. This example depicts the use * of MQTT Transport for the Android Sense device-type. This class extends the abstract class * "MQTTTransportHandler". "MQTTTransportHandler" consists of the MQTT client specific functionality and implements * the "TransportHandler" interface. The actual functionality related to the "TransportHandler" interface is * implemented here, in this concrete class. Whilst the abstract class "MQTTTransportHandler" is intended to provide * the common MQTT functionality, this class (which is its extension) provides the implementation specific to the * MQTT communication of the Device-Type (Android Sense) in concern. * <p/> * Hence, the methods of this class are implementation of the "TransportHandler" interface which handles the device * specific logic to connect-to, publish-to, process-incoming-messages-from and disconnect-from the MQTT broker * listed in the configurations. */ public class AndroidSenseMQTTHandler extends MQTTTransportHandler { private static final String TAG = "AndroidSenseMQTTHandler"; private static volatile AndroidSenseMQTTHandler mInstance; private Context context; /** * return a sigleton Instance * @param context is the android context object. * @return AndroidSenseMQTTHandler. */ public static AndroidSenseMQTTHandler getInstance(Context context) { context = context; if (mInstance == null) { Class clazz = AndroidSenseMQTTHandler.class; synchronized (clazz) { if (mInstance == null) { mInstance = new AndroidSenseMQTTHandler(context); } } } return mInstance; } /** * Default constructor for the AndroidSenseMQTTHandler. */ private AndroidSenseMQTTHandler(Context context) { super(context); } /** * {@inheritDoc} * AndroidSense device-type specific implementation to connect to the MQTT broker and subscribe to a topic. * This method is called to initiate a MQTT communication. */ @Override public void connect() { Runnable connector = new Runnable() { public void run() { while (!isConnected()) { try { connectToQueue(); } catch (TransportHandlerException e) { Log.e(TAG, "Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e); try { Thread.sleep(timeoutInterval); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); Log.e(TAG, "MQTT-Connector: Thread Sleep Interrupt Exception.", ex); } } try { subscribeToQueue(); } catch (TransportHandlerException e) { Log.w(TAG, "Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e); } } } }; Thread connectorThread = new Thread(connector); connectorThread.start(); } /** * {@inheritDoc} * AndroidSense device-type specific implementation to process incoming messages. This is the specific * method signature of the overloaded "processIncomingMessage" method that gets called from the messageArrived() * callback of the "MQTTTransportHandler". */ @Override public void processIncomingMessage(MqttMessage mqttMessage, String... messageParams) { if (messageParams.length != 0) { // owner and the deviceId are extracted from the MQTT topic to which the message was received. // <Topic> = [ServerName/Owner/DeviceType/DeviceId/#] String topic = messageParams[0]; String[] topicParams = topic.split("/"); String owner = topicParams[1]; String deviceId = topicParams[3]; Log.d(TAG, "Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]"); String msg; msg = mqttMessage.toString(); Log.d(TAG, "MQTT: Received Message [" + msg + "] topic: [" + topic + "]"); if (topic.contains("threshold")) { try { ProcessWords.setThreshold(Integer.parseInt(msg)); } catch (NumberFormatException e) { Log.e(TAG, "Invalid threshold value " + msg); } } else if (topic.contains("words")) { String words[] = msg.split(" "); ProcessWords.addWords(Arrays.asList(words)); } else if (topic.contains("remove")) { String words[] = msg.split(" "); for (String word: words) { ProcessWords.removeWord(word); } } } else { String errorMsg = "MQTT message [" + mqttMessage.toString() + "] was received without the topic information."; Log.w(TAG, errorMsg); } } /** * {@inheritDoc} * AndroidSense device-type specific implementation to publish data to the device. This method calls the * {@link #publishToQueue(String, MqttMessage)} method of the "MQTTTransportHandler" class. */ @Override public void publishDeviceData(String... publishData) throws TransportHandlerException { if (publishData.length != 4) { String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " + "Need to be [owner, deviceId, content]"; Log.e(TAG, errorMsg); throw new TransportHandlerException(errorMsg); } String deviceOwner = publishData[0]; String deviceId = publishData[1]; String resource = publishData[2]; MqttMessage pushMessage = new MqttMessage(); String publishTopic = publishData[3]; String actualMessage = resource; pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8)); pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE); pushMessage.setRetained(false); publishToQueue(publishTopic, pushMessage); } /** * {@inheritDoc} * Android Sense device-type specific implementation to disconnect from the MQTT broker. */ @Override public void disconnect() { Runnable stopConnection = new Runnable() { public void run() { while (isConnected()) { try { closeConnection(); } catch (MqttException e) { Log.w(TAG, "Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint + " for device-type - " + SenseConstants.DEVICE_TYPE, e); try { Thread.sleep(timeoutInterval); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); Log.e(TAG, "MQTT-Terminator: Thread Sleep Interrupt Exception at device-type - " + SenseConstants.DEVICE_TYPE, e1); } } } } }; Thread terminatorThread = new Thread(stopConnection); terminatorThread.start(); } /** * {@inheritDoc} */ @Override public void publishDeviceData() { // nothing to do } @Override public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException { } /** * {@inheritDoc} */ @Override public void processIncomingMessage() { // nothing to do } @Override public void processIncomingMessage(MqttMessage message) throws TransportHandlerException { } }
package com.noticeditorteam.noticeditor.io; import com.noticeditorteam.noticeditor.controller.NoticeController; import com.noticeditorteam.noticeditor.controller.PasswordManager; import com.noticeditorteam.noticeditor.exceptions.DismissException; import com.noticeditorteam.noticeditor.model.*; import java.io.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import javafx.scene.control.TreeItem; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.AesKeyStrength; import net.lingala.zip4j.model.enums.CompressionLevel; import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.model.enums.EncryptionMethod; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Document format that stores to zip archive with index.json. * * @author aNNiMON */ public class ZipWithIndexFormat { private static final String INDEX_JSON = "index.json"; private static final String BRANCH_PREFIX = "branch_"; private static final String NOTE_PREFIX = "note_"; public static ZipWithIndexFormat with(File file) throws ZipException { return new ZipWithIndexFormat(file, null); } public static ZipWithIndexFormat with(File file, String password) throws ZipException { return new ZipWithIndexFormat(file, password.toCharArray()); } private final Set<String> paths; private final ZipFile zip; private final ZipParameters parameters; private String zipPassword; private ZipWithIndexFormat(File file, char[] password) throws ZipException { paths = new HashSet<>(); zip = new ZipFile(file, password); parameters = new ZipParameters(); } public ZipWithIndexFormat encrypted() { parameters.setEncryptFiles(true); parameters.setEncryptionMethod(EncryptionMethod.AES); parameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256); return this; } private void checkEncryption() throws ZipException { final boolean isEncrypted = zip.isEncrypted(); NoticeController.getController().setIsEncryptedZip(isEncrypted); if (isEncrypted) { if (zipPassword == null) { zipPassword = PasswordManager.askPassword(zip.getFile().getAbsolutePath()).orElse(""); } if (zipPassword.isEmpty()) throw new DismissException(); zip.setPassword(zipPassword.toCharArray()); } } //<editor-fold defaultstate="collapsed" desc="Import"> public NoticeTree importDocument() throws IOException, JSONException, ZipException { checkEncryption(); String indexContent = readFile(INDEX_JSON); if (indexContent.isEmpty()) { throw new IOException("Invalid file format"); } JSONObject index = new JSONObject(indexContent); return new NoticeTree(readNotices("", index)); } private String readFile(String path) throws IOException, ZipException { FileHeader header = zip.getFileHeader(path); if (header == null) return ""; try (InputStream is = zip.getInputStream(header)) { return IOUtil.stringFromStream(is); } } private byte[] readBytes(String path) throws IOException, ZipException { FileHeader header = zip.getFileHeader(path); if (header == null) return new byte[0]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream is = zip.getInputStream(header)) { IOUtil.copy(is, baos); } baos.flush(); return baos.toByteArray(); } private NoticeTreeItem readNotices(String dir, JSONObject index) throws IOException, JSONException, ZipException { final String title = index.getString(JsonFields.KEY_TITLE); final String filename = index.getString(JsonFields.KEY_FILENAME); final int status = index.optInt(JsonFields.KEY_STATUS, NoticeItem.STATUS_NORMAL); final String dirPrefix = index.has(JsonFields.KEY_CHILDREN) ? BRANCH_PREFIX : NOTE_PREFIX; final String newDir = dir + dirPrefix + filename + "/"; if (index.has(JsonFields.KEY_CHILDREN)) { JSONArray children = index.getJSONArray(JsonFields.KEY_CHILDREN); NoticeTreeItem branch = new NoticeTreeItem(title); for (int i = 0; i < children.length(); i++) { branch.addChild(readNotices(newDir, children.getJSONObject(i))); } return branch; } else { // ../note_filename/filename.md final String mdPath = newDir + filename + ".md"; final NoticeTreeItem item = new NoticeTreeItem(title, readFile(mdPath), status); if (index.has(JsonFields.KEY_ATTACHMENTS)) { Attachments attachments = readAttachments(newDir, index.getJSONArray(JsonFields.KEY_ATTACHMENTS)); item.setAttachments(attachments); } return item; } } private Attachments readAttachments(String newDir, JSONArray jsonAttachments) throws IOException, JSONException, ZipException { Attachments attachments = new Attachments(); final int length = jsonAttachments.length(); for (int i = 0; i < length; i++) { JSONObject jsonAttachment = jsonAttachments.getJSONObject(i); final String name = jsonAttachment.getString(JsonFields.KEY_ATTACHMENT_NAME); Attachment attachment = new Attachment(name, readBytes(newDir + name)); attachments.add(attachment); } return attachments; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Export"> public void export(NoticeTreeItem notice) throws IOException, JSONException, ZipException { parameters.setCompressionMethod(CompressionMethod.DEFLATE); parameters.setCompressionLevel(CompressionLevel.NORMAL); JSONObject index = new JSONObject(); writeNoticesAndFillIndex("", notice, index); storeFile(INDEX_JSON, index.toString()); } public void export(NoticeTree tree) throws IOException, JSONException, ZipException { export(tree.getRoot()); } private void storeFile(String path, String content) throws IOException, ZipException { parameters.setFileNameInZip(path); try (InputStream stream = IOUtil.toStream(content)) { zip.addStream(stream, parameters); } } private void storeFile(String path, byte[] data) throws IOException, ZipException { parameters.setFileNameInZip(path); try (InputStream stream = new ByteArrayInputStream(data)) { zip.addStream(stream, parameters); } } private void writeNoticesAndFillIndex(String dir, NoticeTreeItem item, JSONObject index) throws IOException, JSONException, ZipException { final String title = item.getTitle(); final String dirPrefix = item.isBranch() ? BRANCH_PREFIX : NOTE_PREFIX; String filename = IOUtil.sanitizeFilename(title); String newDir = dir + dirPrefix + filename; if (paths.contains(newDir)) { // solve collision int counter = 1; String newFileName = filename; while (paths.contains(newDir)) { newFileName = String.format("%s_(%d)", filename, counter++); newDir = dir + dirPrefix + newFileName; } filename = newFileName; } paths.add(newDir); index.put(JsonFields.KEY_TITLE, title); index.put(JsonFields.KEY_FILENAME, filename); if (item.isBranch()) { // ../branch_filename ArrayList list = new ArrayList(); for (TreeItem<NoticeItem> object : item.getInternalChildren()) { NoticeTreeItem child = (NoticeTreeItem) object; JSONObject indexEntry = new JSONObject(); writeNoticesAndFillIndex(newDir + "/", child, indexEntry); list.add(indexEntry); } index.put(JsonFields.KEY_CHILDREN, new JSONArray(list)); } else { // ../note_filename/filename.md index.put(JsonFields.KEY_STATUS, item.getStatus()); storeFile(newDir + "/" + filename + ".md", item.getContent()); writeAttachments(newDir, item.getAttachments(), index); } } private void writeAttachments(String newDir, Attachments attachments, JSONObject index) throws JSONException, IOException, ZipException { // Store filenames in index.json and content in file. final JSONArray jsonAttachments = new JSONArray(); for (Attachment attachment : attachments) { final JSONObject jsonAttachment = new JSONObject(); jsonAttachment.put(JsonFields.KEY_ATTACHMENT_NAME, attachment.getName()); jsonAttachments.put(jsonAttachment); storeFile(newDir + "/" + attachment.getName(), attachment.getData()); } index.put(JsonFields.KEY_ATTACHMENTS, jsonAttachments); } //</editor-fold> }
package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "adult", "backdrop_path", "belongs_to_collection", "budget", "movieGetGenres", "homepage", "id", "imdb_id", "original_language", "original_title", "overview", "popularity", "poster_path", "production_companies", "production_countries", "release_date", "revenue", "runtime", "spoken_languages", "status", "tagline", "title", "video", "vote_average", "vote_count", "external_ids" }) public class MovieGet { @JsonProperty("adult") private Boolean adult; @JsonProperty("backdrop_path") private String backdropPath; @JsonProperty("belongs_to_collection") private MovieGetBelongsToCollection belongsToCollection; @JsonProperty("budget") private Integer budget; @JsonProperty("movieGetGenres") private List<MovieGetGenre> movieGetGenres = null; @JsonProperty("homepage") private String homepage; @JsonProperty("id") private Integer id; @JsonProperty("imdb_id") private String imdbId; @JsonProperty("original_language") private String originalLanguage; @JsonProperty("original_title") private String originalTitle; @JsonProperty("overview") private String overview; @JsonProperty("popularity") private Double popularity; @JsonProperty("poster_path") private String posterPath; @JsonProperty("production_companies") private List<MovieGetProductionCompany> productionCompanies = null; @JsonProperty("production_countries") private List<MovieGetProductionCountry> productionCountries = null; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") @JsonProperty("release_date") private Date releaseDate; @JsonProperty("revenue") private Integer revenue; @JsonProperty("runtime") private Integer runtime; @JsonProperty("spoken_languages") private List<MovieGetSpokenLanguage> movieGetSpokenLanguages = null; @JsonProperty("status") private String status; @JsonProperty("tagline") private String tagline; @JsonProperty("title") private String title; @JsonProperty("video") private Boolean video; @JsonProperty("vote_average") private Double voteAverage; @JsonProperty("vote_count") private Integer voteCount; @JsonProperty("external_ids") private MovieGetExternalIds movieGetExternalIds; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("adult") public Boolean getAdult() { return adult; } @JsonProperty("adult") public void setAdult(Boolean adult) { this.adult = adult; } @JsonProperty("backdrop_path") public String getBackdropPath() { return backdropPath; } @JsonProperty("backdrop_path") public void setBackdropPath(String backdropPath) { this.backdropPath = backdropPath; } @JsonProperty("belongs_to_collection") public MovieGetBelongsToCollection getBelongsToCollection() { return belongsToCollection; } @JsonProperty("belongs_to_collection") public void setBelongsToCollection(MovieGetBelongsToCollection belongsToCollection) { this.belongsToCollection = belongsToCollection; } @JsonProperty("budget") public Integer getBudget() { return budget; } @JsonProperty("budget") public void setBudget(Integer budget) { this.budget = budget; } @JsonProperty("movieGetGenres") public List<MovieGetGenre> getMovieGetGenres() { return movieGetGenres; } @JsonProperty("movieGetGenres") public void setMovieGetGenres(List<MovieGetGenre> movieGetGenres) { this.movieGetGenres = movieGetGenres; } @JsonProperty("homepage") public String getHomepage() { return homepage; } @JsonProperty("homepage") public void setHomepage(String homepage) { this.homepage = homepage; } @JsonProperty("id") public Integer getId() { return id; } @JsonProperty("id") public void setId(Integer id) { this.id = id; } @JsonProperty("imdb_id") public String getImdbId() { return imdbId; } @JsonProperty("imdb_id") public void setImdbId(String imdbId) { this.imdbId = imdbId; } @JsonProperty("original_language") public String getOriginalLanguage() { return originalLanguage; } @JsonProperty("original_language") public void setOriginalLanguage(String originalLanguage) { this.originalLanguage = originalLanguage; } @JsonProperty("original_title") public String getOriginalTitle() { return originalTitle; } @JsonProperty("original_title") public void setOriginalTitle(String originalTitle) { this.originalTitle = originalTitle; } @JsonProperty("overview") public String getOverview() { return overview; } @JsonProperty("overview") public void setOverview(String overview) { this.overview = overview; } @JsonProperty("popularity") public Double getPopularity() { return popularity; } @JsonProperty("popularity") public void setPopularity(Double popularity) { this.popularity = popularity; } @JsonProperty("poster_path") public String getPosterPath() { return posterPath; } @JsonProperty("poster_path") public void setPosterPath(String posterPath) { this.posterPath = posterPath; } @JsonProperty("production_companies") public List<MovieGetProductionCompany> getProductionCompanies() { return productionCompanies; } @JsonProperty("production_companies") public void setProductionCompanies(List<MovieGetProductionCompany> productionCompanies) { this.productionCompanies = productionCompanies; } @JsonProperty("production_countries") public List<MovieGetProductionCountry> getProductionCountries() { return productionCountries; } @JsonProperty("production_countries") public void setProductionCountries(List<MovieGetProductionCountry> productionCountries) { this.productionCountries = productionCountries; } @JsonProperty("release_date") public Date getReleaseDate() { return releaseDate; } @JsonProperty("release_date") public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } @JsonProperty("revenue") public Integer getRevenue() { return revenue; } @JsonProperty("revenue") public void setRevenue(Integer revenue) { this.revenue = revenue; } @JsonProperty("runtime") public Integer getRuntime() { return runtime; } @JsonProperty("runtime") public void setRuntime(Integer runtime) { this.runtime = runtime; } @JsonProperty("spoken_languages") public List<MovieGetSpokenLanguage> getMovieGetSpokenLanguages() { return movieGetSpokenLanguages; } @JsonProperty("spoken_languages") public void setMovieGetSpokenLanguages(List<MovieGetSpokenLanguage> movieGetSpokenLanguages) { this.movieGetSpokenLanguages = movieGetSpokenLanguages; } @JsonProperty("status") public String getStatus() { return status; } @JsonProperty("status") public void setStatus(String status) { this.status = status; } @JsonProperty("tagline") public String getTagline() { return tagline; } @JsonProperty("tagline") public void setTagline(String tagline) { this.tagline = tagline; } @JsonProperty("title") public String getTitle() { return title; } @JsonProperty("title") public void setTitle(String title) { this.title = title; } @JsonProperty("video") public Boolean getVideo() { return video; } @JsonProperty("video") public void setVideo(Boolean video) { this.video = video; } @JsonProperty("vote_average") public Double getVoteAverage() { return voteAverage; } @JsonProperty("vote_average") public void setVoteAverage(Double voteAverage) { this.voteAverage = voteAverage; } @JsonProperty("vote_count") public Integer getVoteCount() { return voteCount; } @JsonProperty("vote_count") public void setVoteCount(Integer voteCount) { this.voteCount = voteCount; } @JsonProperty("external_ids") public MovieGetExternalIds getMovieGetExternalIds() { return movieGetExternalIds; } @JsonProperty("external_ids") public void setMovieGetExternalIds(MovieGetExternalIds movieGetExternalIds) { this.movieGetExternalIds = movieGetExternalIds; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } //@JsonInclude(JsonInclude.Include.NON_NULL) //@JsonPropertyOrder({ // "id", // "name", // "poster_path", // "backdrop_path" //}) //class MovieGetBelongsToCollection { // // @JsonProperty("id") // private Integer id; // @JsonProperty("name") // private String name; // @JsonProperty("poster_path") // private String posterPath; // @JsonProperty("backdrop_path") // private String backdropPath; // @JsonIgnore // private Map<String, Object> additionalProperties = new HashMap<String, Object>(); // // @JsonProperty("id") // public Integer getId() { // return id; // } // // @JsonProperty("id") // public void setId(Integer id) { // this.id = id; // } // // @JsonProperty("name") // public String getName() { // return name; // } // // @JsonProperty("name") // public void setName(String name) { // this.name = name; // } // // @JsonProperty("poster_path") // public String getPosterPath() { // return posterPath; // } // // @JsonProperty("poster_path") // public void setPosterPath(String posterPath) { // this.posterPath = posterPath; // } // // @JsonProperty("backdrop_path") // public String getBackdropPath() { // return backdropPath; // } // // @JsonProperty("backdrop_path") // public void setBackdropPath(String backdropPath) { // this.backdropPath = backdropPath; // } // // @JsonAnyGetter // public Map<String, Object> getAdditionalProperties() { // return this.additionalProperties; // } // // @JsonAnySetter // public void setAdditionalProperty(String name, Object value) { // this.additionalProperties.put(name, value); // } // //}
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.cassandra.cql3.statements; import java.nio.ByteBuffer; import java.util.*; import org.apache.cassandra.cql3.*; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.*; import org.apache.cassandra.db.composites.Composite; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.exceptions.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.Pair; /** * An <code>UPDATE</code> statement parsed from a CQL query statement. * */ public class UpdateStatement extends ModificationStatement { private static final Constants.Value EMPTY = new Constants.Value(ByteBufferUtil.EMPTY_BYTE_BUFFER); private UpdateStatement(StatementType type, int boundTerms, CFMetaData cfm, Attributes attrs) { super(type, boundTerms, cfm, attrs); } public boolean requireFullClusteringKey() { return true; } public void addUpdateForKey(ColumnFamily cf, ByteBuffer key, Composite prefix, UpdateParameters params) throws InvalidRequestException { // Inserting the CQL row marker (see #4361) // We always need to insert a marker for INSERT, because of the following situation: // CREATE TABLE t ( k int PRIMARY KEY, c text ); // INSERT INTO t(k, c) VALUES (1, 1) // DELETE c FROM t WHERE k = 1; // SELECT * FROM t; // The last query should return one row (but with c == null). Adding the marker with the insert make sure // the semantic is correct (while making sure a 'DELETE FROM t WHERE k = 1' does remove the row entirely) // // We do not insert the marker for UPDATE however, as this amount to updating the columns in the WHERE // clause which is inintuitive (#6782) // // We never insert markers for Super CF as this would confuse the thrift side. if (type == StatementType.INSERT && cfm.isCQL3Table() && !prefix.isStatic()) cf.addColumn(params.makeColumn(cfm.comparator.rowMarker(prefix), ByteBufferUtil.EMPTY_BYTE_BUFFER)); List<Operation> updates = getOperations(); if (cfm.comparator.isDense()) { if (prefix.isEmpty()) throw new InvalidRequestException(String.format("Missing PRIMARY KEY part %s", cfm.clusteringColumns().get(0))); // An empty name for the compact value is what we use to recognize the case where there is not column // outside the PK, see CreateStatement. if (!cfm.compactValueColumn().name.bytes.hasRemaining()) { // There is no column outside the PK. So no operation could have passed through validation assert updates.isEmpty(); new Constants.Setter(cfm.compactValueColumn(), EMPTY).execute(key, cf, prefix, params); } else { // dense means we don't have a row marker, so don't accept to set only the PK. See CASSANDRA-5648. if (updates.isEmpty()) throw new InvalidRequestException(String.format("Column %s is mandatory for this COMPACT STORAGE table", cfm.compactValueColumn().name)); for (Operation update : updates) update.execute(key, cf, prefix, params); } } else { for (Operation update : updates) update.execute(key, cf, prefix, params); } } public static class ParsedInsert extends ModificationStatement.Parsed { private final List<ColumnIdentifier.Raw> columnNames; private final List<Term.Raw> columnValues; /** * A parsed <code>INSERT</code> statement. * * @param name column family being operated on * @param columnNames list of column names * @param columnValues list of column values (corresponds to names) * @param attrs additional attributes for statement (CL, timestamp, timeToLive) */ public ParsedInsert(CFName name, Attributes.Raw attrs, List<ColumnIdentifier.Raw> columnNames, List<Term.Raw> columnValues, boolean ifNotExists) { super(name, attrs, null, ifNotExists, false); this.columnNames = columnNames; this.columnValues = columnValues; } protected ModificationStatement prepareInternal(CFMetaData cfm, VariableSpecifications boundNames, Attributes attrs) throws InvalidRequestException { UpdateStatement stmt = new UpdateStatement(ModificationStatement.StatementType.INSERT,boundNames.size(), cfm, attrs); // Created from an INSERT if (stmt.isCounter()) throw new InvalidRequestException("INSERT statement are not allowed on counter tables, use UPDATE instead"); if (columnNames.size() != columnValues.size()) throw new InvalidRequestException("Unmatched column names/values"); if (columnNames.isEmpty()) throw new InvalidRequestException("No columns provided to INSERT"); for (int i = 0; i < columnNames.size(); i++) { ColumnDefinition def = cfm.getColumnDefinition(columnNames.get(i).prepare(cfm)); if (def == null) throw new InvalidRequestException(String.format("Unknown identifier %s", columnNames.get(i))); for (int j = 0; j < i; j++) if (def.name.equals(columnNames.get(j))) throw new InvalidRequestException(String.format("Multiple definitions found for column %s", def.name)); Term.Raw value = columnValues.get(i); switch (def.kind) { case PARTITION_KEY: case CLUSTERING_COLUMN: Term t = value.prepare(keyspace(), def); t.collectMarkerSpecification(boundNames); stmt.addKeyValue(def, t); break; default: Operation operation = new Operation.SetValue(value).prepare(keyspace(), def); operation.collectMarkerSpecification(boundNames); stmt.addOperation(operation); break; } } return stmt; } } public static class ParsedUpdate extends ModificationStatement.Parsed { // Provided for an UPDATE private final List<Pair<ColumnIdentifier.Raw, Operation.RawUpdate>> updates; private final List<Relation> whereClause; /** * Creates a new UpdateStatement from a column family name, columns map, consistency * level, and key term. * * @param name column family being operated on * @param attrs additional attributes for statement (timestamp, timeToLive) * @param updates a map of column operations to perform * @param whereClause the where clause */ public ParsedUpdate(CFName name, Attributes.Raw attrs, List<Pair<ColumnIdentifier.Raw, Operation.RawUpdate>> updates, List<Relation> whereClause, List<Pair<ColumnIdentifier.Raw, ColumnCondition.Raw>> conditions) { super(name, attrs, conditions, false, false); this.updates = updates; this.whereClause = whereClause; } protected ModificationStatement prepareInternal(CFMetaData cfm, VariableSpecifications boundNames, Attributes attrs) throws InvalidRequestException { UpdateStatement stmt = new UpdateStatement(ModificationStatement.StatementType.UPDATE, boundNames.size(), cfm, attrs); for (Pair<ColumnIdentifier.Raw, Operation.RawUpdate> entry : updates) { ColumnDefinition def = cfm.getColumnDefinition(entry.left.prepare(cfm)); if (def == null) throw new InvalidRequestException(String.format("Unknown identifier %s", entry.left)); Operation operation = entry.right.prepare(keyspace(), def); operation.collectMarkerSpecification(boundNames); switch (def.kind) { case PARTITION_KEY: case CLUSTERING_COLUMN: throw new InvalidRequestException(String.format("PRIMARY KEY part %s found in SET part", entry.left)); default: stmt.addOperation(operation); break; } } stmt.processWhereClause(whereClause, boundNames); return stmt; } } }
package com.fasterxml.jackson.databind.ser.filter; import java.io.IOException; import java.lang.annotation.*; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.*; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.fasterxml.jackson.databind.ser.std.MapProperty; @SuppressWarnings("serial") public class TestMapFiltering extends BaseMapTest { @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface CustomOffset { public int value(); } @JsonFilter("filterForMaps") static class FilteredBean extends LinkedHashMap<String,Integer> { } static class MapBean { @JsonFilter("filterX") @CustomOffset(1) public Map<String,Integer> values; public MapBean() { values = new LinkedHashMap<String,Integer>(); values.put("a", 1); values.put("b", 5); values.put("c", 9); } } static class MapBeanNoOffset { @JsonFilter("filterX") public Map<String,Integer> values; public MapBeanNoOffset() { values = new LinkedHashMap<String,Integer>(); values.put("a", 1); values.put("b", 2); values.put("c", 3); } } static class TestMapFilter implements PropertyFilter { @Override public void serializeAsField(Object bean, JsonGenerator g, SerializerProvider provider, PropertyWriter writer) throws Exception { String name = writer.getName(); // sanity checks assertNotNull(writer.getType()); assertEquals(name, writer.getFullName().getSimpleName()); if (!"a".equals(name)) { return; } CustomOffset n = writer.findAnnotation(CustomOffset.class); int offset = (n == null) ? 0 : n.value(); // 12-Jun-2017, tatu: With 2.9, `value` is the surrounding POJO, so // need to do casting MapProperty prop = (MapProperty) writer; Integer old = (Integer) prop.getValue(); prop.setValue(Integer.valueOf(offset + old.intValue())); writer.serializeAsField(bean, g, provider); } @Override public void serializeAsElement(Object elementValue, JsonGenerator jgen, SerializerProvider prov, PropertyWriter writer) throws Exception { // not needed for testing } @Override @Deprecated public void depositSchemaProperty(PropertyWriter writer, ObjectNode propertiesNode, SerializerProvider provider) { } @Override public void depositSchemaProperty(PropertyWriter writer, JsonObjectFormatVisitor objectVisitor, SerializerProvider provider) { } } // [databind#527] static class NoNullValuesMapContainer { @JsonInclude(content=JsonInclude.Include.NON_NULL) public Map<String,String> stuff = new LinkedHashMap<String,String>(); public NoNullValuesMapContainer add(String key, String value) { stuff.put(key, value); return this; } } // [databind#527] @JsonInclude(content=JsonInclude.Include.NON_NULL) static class NoNullsStringMap extends LinkedHashMap<String,String> { public NoNullsStringMap add(String key, String value) { put(key, value); return this; } } // [databind#527] @JsonInclude(content=JsonInclude.Include.NON_ABSENT) static class NoAbsentStringMap extends LinkedHashMap<String, AtomicReference<?>> { public NoAbsentStringMap add(String key, Object value) { put(key, new AtomicReference<Object>(value)); return this; } } // [databind#527] @JsonInclude(content=JsonInclude.Include.NON_EMPTY) static class NoEmptyStringsMap extends LinkedHashMap<String,String> { public NoEmptyStringsMap add(String key, String value) { put(key, value); return this; } } // [databind#497]: both Map AND contents excluded if empty static class Wrapper497 { @JsonInclude(content=JsonInclude.Include.NON_EMPTY, value=JsonInclude.Include.NON_EMPTY) public StringMap497 values; public Wrapper497(StringMap497 v) { values = v; } } static class StringMap497 extends LinkedHashMap<String,String> { public StringMap497 add(String key, String value) { put(key, value); return this; } } /* /********************************************************** /* Unit tests /********************************************************** */ final ObjectMapper MAPPER = objectMapper(); public void testMapFilteringViaProps() throws Exception { FilterProvider prov = new SimpleFilterProvider().addFilter("filterX", SimpleBeanPropertyFilter.filterOutAllExcept("b")); String json = MAPPER.writer(prov).writeValueAsString(new MapBean()); assertEquals(a2q("{'values':{'b':5}}"), json); } public void testMapFilteringViaClass() throws Exception { FilteredBean bean = new FilteredBean(); bean.put("a", 4); bean.put("b", 3); FilterProvider prov = new SimpleFilterProvider().addFilter("filterForMaps", SimpleBeanPropertyFilter.filterOutAllExcept("b")); String json = MAPPER.writer(prov).writeValueAsString(bean); assertEquals(a2q("{'b':3}"), json); } // [databind#527] public void testNonNullValueMapViaProp() throws IOException { String json = MAPPER.writeValueAsString(new NoNullValuesMapContainer() .add("a", "foo") .add("b", null) .add("c", "bar")); assertEquals(a2q("{'stuff':{'a':'foo','c':'bar'}}"), json); } // [databind#522] public void testMapFilteringWithAnnotations() throws Exception { FilterProvider prov = new SimpleFilterProvider().addFilter("filterX", new TestMapFilter()); String json = MAPPER.writer(prov).writeValueAsString(new MapBean()); // a=1 should become a=2 assertEquals(a2q("{'values':{'a':2}}"), json); // and then one without annotation as contrast json = MAPPER.writer(prov).writeValueAsString(new MapBeanNoOffset()); assertEquals(a2q("{'values':{'a':1}}"), json); } // [databind#527] public void testMapNonNullValue() throws IOException { String json = MAPPER.writeValueAsString(new NoNullsStringMap() .add("a", "foo") .add("b", null) .add("c", "bar")); assertEquals(a2q("{'a':'foo','c':'bar'}"), json); } // [databind#527] public void testMapNonEmptyValue() throws IOException { String json = MAPPER.writeValueAsString(new NoEmptyStringsMap() .add("a", "foo") .add("b", "bar") .add("c", "")); assertEquals(a2q("{'a':'foo','b':'bar'}"), json); } // Test to ensure absent content of AtomicReference handled properly // [databind#527] public void testMapAbsentValue() throws IOException { String json = MAPPER.writeValueAsString(new NoAbsentStringMap() .add("a", "foo") .add("b", null)); assertEquals(a2q("{'a':'foo'}"), json); } @SuppressWarnings("deprecation") public void testMapNullSerialization() throws IOException { ObjectMapper m = new ObjectMapper(); Map<String,String> map = new HashMap<String,String>(); map.put("a", null); // by default, should output null-valued entries: assertEquals("{\"a\":null}", m.writeValueAsString(map)); // but not if explicitly asked not to (note: config value is dynamic here) m = new ObjectMapper(); m.disable(SerializationFeature.WRITE_NULL_MAP_VALUES); assertEquals("{}", m.writeValueAsString(map)); } // [databind#527] public void testMapWithOnlyEmptyValues() throws IOException { String json; // First, non empty: json = MAPPER.writeValueAsString(new Wrapper497(new StringMap497() .add("a", "123"))); assertEquals(a2q("{'values':{'a':'123'}}"), json); // then empty json = MAPPER.writeValueAsString(new Wrapper497(new StringMap497() .add("a", "") .add("b", null))); assertEquals(a2q("{}"), json); } public void testMapViaGlobalNonEmpty() throws Exception { // basic Map<String,String> subclass: ObjectMapper mapper = new ObjectMapper(); mapper.setDefaultPropertyInclusion(JsonInclude.Value.empty() .withContentInclusion(JsonInclude.Include.NON_EMPTY)); assertEquals(a2q("{'a':'b'}"), mapper.writeValueAsString( new StringMap497() .add("x", "") .add("a", "b") )); } public void testMapViaTypeOverride() throws Exception { // basic Map<String,String> subclass: ObjectMapper mapper = new ObjectMapper(); mapper.configOverride(Map.class) .setInclude(JsonInclude.Value.empty() .withContentInclusion(JsonInclude.Include.NON_EMPTY)); assertEquals(a2q("{'a':'b'}"), mapper.writeValueAsString( new StringMap497() .add("foo", "") .add("a", "b") )); } }
package com.tinkerpop.gremlin.process.computer.traversal; import com.tinkerpop.gremlin.process.Traversal; import com.tinkerpop.gremlin.process.TraversalEngine; import com.tinkerpop.gremlin.process.TraversalStrategies; import com.tinkerpop.gremlin.process.Traverser; import com.tinkerpop.gremlin.process.TraverserGenerator; import com.tinkerpop.gremlin.process.computer.MapReduce; import com.tinkerpop.gremlin.process.computer.Memory; import com.tinkerpop.gremlin.process.computer.MessageType; import com.tinkerpop.gremlin.process.computer.Messenger; import com.tinkerpop.gremlin.process.computer.VertexProgram; import com.tinkerpop.gremlin.process.computer.traversal.step.sideEffect.mapreduce.TraverserMapReduce; import com.tinkerpop.gremlin.process.computer.util.AbstractVertexProgramBuilder; import com.tinkerpop.gremlin.process.computer.util.LambdaHolder; import com.tinkerpop.gremlin.process.graph.marker.MapReducer; import com.tinkerpop.gremlin.process.graph.step.sideEffect.GraphStep; import com.tinkerpop.gremlin.process.graph.step.sideEffect.SideEffectCapStep; import com.tinkerpop.gremlin.process.util.DefaultTraversalSideEffects; import com.tinkerpop.gremlin.process.util.EmptyStep; import com.tinkerpop.gremlin.process.util.SingleIterator; import com.tinkerpop.gremlin.process.util.TraversalHelper; import com.tinkerpop.gremlin.process.util.TraverserSet; import com.tinkerpop.gremlin.structure.Direction; import com.tinkerpop.gremlin.structure.Element; import com.tinkerpop.gremlin.structure.Graph; import com.tinkerpop.gremlin.structure.Vertex; import com.tinkerpop.gremlin.structure.util.StringFactory; import org.apache.commons.configuration.Configuration; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; /** * TraversalVertexProgram enables the evaluation of a {@link Traversal} on a {@link com.tinkerpop.gremlin.process.computer.GraphComputer}. * At the start of the computation, each {@link Vertex} (or {@link com.tinkerpop.gremlin.structure.Edge}) is assigned a single {@link Traverser}. * For each traverser that is local to the vertex, the vertex looks up its current location in the traversal and processes that step. * If the outputted traverser of the step references a local structure on the vertex (e.g. the vertex, an incident edge, its properties, or an arbitrary object), * then the vertex continues to compute the next traverser. If the traverser references another location in the graph, * then the traverser is sent to that location in the graph via a message. The messages of TraversalVertexProgram are traversers. * This continues until all traversers in the computation have halted. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public final class TraversalVertexProgram implements VertexProgram<Traverser.Admin<?>> { // TODO: if not an adjacent traversal, use Local message type -- a dual messaging system. public static final String HALTED_TRAVERSERS = Graph.Key.hide("gremlin.traversalVertexProgram.haltedTraversers"); private static final String VOTE_TO_HALT = "gremlin.traversalVertexProgram.voteToHalt"; public static final String TRAVERSAL_SUPPLIER = "gremlin.traversalVertexProgram.traversalSupplier"; private LambdaHolder<Supplier<Traversal>> traversalSupplier; private Traversal traversal; private final Set<MapReduce> mapReducers = new HashSet<>(); private static final Set<String> MEMORY_COMPUTE_KEYS = new HashSet<String>() {{ add(VOTE_TO_HALT); }}; private final Set<String> elementComputeKeys = new HashSet<String>() {{ add(HALTED_TRAVERSERS); add(Traversal.SideEffects.SIDE_EFFECTS); }}; private TraversalVertexProgram() { } private TraversalVertexProgram(final Configuration configuration) { this.traversalSupplier = LambdaHolder.loadState(configuration, TRAVERSAL_SUPPLIER); this.traversal = this.traversalSupplier.get().get(); if (null == this.traversalSupplier) { throw new IllegalArgumentException("The configuration does not have a traversal supplier"); } final Traversal<?, ?> traversal = this.traversalSupplier.get().get(); traversal.getSteps().stream().filter(step -> step instanceof MapReducer).forEach(step -> { final MapReduce mapReduce = ((MapReducer) step).getMapReduce(); this.mapReducers.add(mapReduce); }); if (!(TraversalHelper.getEnd(traversal) instanceof SideEffectCapStep)) this.mapReducers.add(new TraverserMapReduce(TraversalHelper.getEnd(traversal))); } /** * A helper method that yields a {@link com.tinkerpop.gremlin.process.Traversal.SideEffects} view of the distributed sideEffects within the currently processed {@link com.tinkerpop.gremlin.structure.Vertex}. * * @param localVertex the currently executing vertex * @return a sideEffect API to get and put sideEffect data onto the vertex */ public static Traversal.SideEffects getLocalSideEffects(final Vertex localVertex) { return new DefaultTraversalSideEffects(localVertex); // TODO: use a worker static object } /** * A helper method to yield a {@link Supplier} of {@link Traversal} from the {@link Configuration}. * The supplier is either a {@link Class}, {@link com.tinkerpop.gremlin.process.computer.util.ScriptEngineLambda}, or a direct Java8 lambda. * * @param configuration The configuration containing the public static TRAVERSAL_SUPPLIER key. * @return the traversal supplier in the configuration */ public static Supplier<Traversal> getTraversalSupplier(final Configuration configuration) { return LambdaHolder.<Supplier<Traversal>>loadState(configuration, TraversalVertexProgram.TRAVERSAL_SUPPLIER).get(); } public Traversal getTraversal() { return this.traversal; } @Override public void loadState(final Configuration configuration) { this.traversalSupplier = LambdaHolder.loadState(configuration, TRAVERSAL_SUPPLIER); this.traversal = this.traversalSupplier.get().get(); } @Override public void storeState(final Configuration configuration) { VertexProgram.super.storeState(configuration); this.traversalSupplier.storeState(configuration); } @Override public void setup(final Memory memory) { memory.set(VOTE_TO_HALT, true); } @Override public void execute(final Vertex vertex, final Messenger<Traverser.Admin<?>> messenger, Memory memory) { this.traversal.sideEffects().setLocalVertex(vertex); if (memory.isInitialIteration()) { final TraverserSet<Object> haltedTraversers = new TraverserSet<>(); vertex.property(HALTED_TRAVERSERS, haltedTraversers); if (!(this.traversal.getSteps().get(0) instanceof GraphStep)) throw new UnsupportedOperationException("TraversalVertexProgram currently only supports GraphStep starts on vertices or edges"); final GraphStep<Element> startStep = (GraphStep<Element>) this.traversal.getSteps().get(0); // TODO: make this generic to Traversal final TraverserGenerator traverserGenerator = TraversalStrategies.GlobalCache.getStrategies(this.traversal.getClass()).getTraverserGenerator(this.traversal, TraversalEngine.COMPUTER); final String future = startStep.getNextStep() instanceof EmptyStep ? Traverser.Admin.HALT : startStep.getNextStep().getLabel(); final AtomicBoolean voteToHalt = new AtomicBoolean(true); final Iterator<? extends Element> starts = startStep.returnsVertices() ? new SingleIterator<>(vertex) : vertex.iterators().edgeIterator(Direction.OUT); starts.forEachRemaining(element -> { final Traverser.Admin<Element> traverser = traverserGenerator.generate(element, startStep); traverser.setFuture(future); traverser.detach(); if (traverser.isHalted()) haltedTraversers.add((Traverser.Admin) traverser); else { voteToHalt.set(false); messenger.sendMessage(MessageType.Global.of(vertex), traverser); } }); memory.and(VOTE_TO_HALT, voteToHalt.get()); } else { memory.and(VOTE_TO_HALT, TraverserExecutor.execute(vertex, messenger, this.traversal)); } } @Override public boolean terminate(final Memory memory) { final boolean voteToHalt = memory.<Boolean>get(VOTE_TO_HALT); if (voteToHalt) { return true; } else { memory.set(VOTE_TO_HALT, true); return false; } } @Override public Set<String> getElementComputeKeys() { return this.elementComputeKeys; } @Override public Set<String> getMemoryComputeKeys() { return MEMORY_COMPUTE_KEYS; } @Override public Set<MapReduce> getMapReducers() { return this.mapReducers; } @Override public String toString() { final String traversalString = this.traversal.toString().substring(1); return StringFactory.vertexProgramString(this, traversalString.substring(0, traversalString.length() - 1)); } @Override public Features getFeatures() { return new Features() { @Override public boolean requiresGlobalMessageTypes() { return true; } @Override public boolean requiresVertexPropertyAddition() { return true; } }; } ////////////// public static Builder build() { return new Builder(); } public static class Builder extends AbstractVertexProgramBuilder<Builder> { public Builder() { super(TraversalVertexProgram.class); } public Builder traversal(final String scriptEngine, final String traversalScript) { LambdaHolder.storeState(this.configuration, LambdaHolder.Type.SCRIPT, TRAVERSAL_SUPPLIER, new String[]{scriptEngine, traversalScript}); return this; } public Builder traversal(final String traversalScript) { return traversal(GREMLIN_GROOVY, traversalScript); } public Builder traversal(final Supplier<Traversal> traversal) { LambdaHolder.storeState(this.configuration, LambdaHolder.Type.OBJECT, TRAVERSAL_SUPPLIER, traversal); return this; } public Builder traversal(final Class<Supplier<Traversal>> traversalClass) { LambdaHolder.storeState(this.configuration, LambdaHolder.Type.CLASS, TRAVERSAL_SUPPLIER, traversalClass); return this; } @Override public <P extends VertexProgram> P create() { return (P) new TraversalVertexProgram(this.configuration); } // TODO Builder resolveElements(boolean) to be fed to ComputerResultStep } }